repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
googledatalab/pydatalab
datalab/bigquery/commands/_bigquery.py
_get_schema
def _get_schema(name): """ Given a variable or table name, get the Schema if it exists. """ item = datalab.utils.commands.get_notebook_item(name) if not item: item = _get_table(name) if isinstance(item, datalab.bigquery.Schema): return item if hasattr(item, 'schema') and isinstance(item.schema, datalab.bigquery._schema.Schema): return item.schema return None
python
def _get_schema(name): """ Given a variable or table name, get the Schema if it exists. """ item = datalab.utils.commands.get_notebook_item(name) if not item: item = _get_table(name) if isinstance(item, datalab.bigquery.Schema): return item if hasattr(item, 'schema') and isinstance(item.schema, datalab.bigquery._schema.Schema): return item.schema return None
[ "def", "_get_schema", "(", "name", ")", ":", "item", "=", "datalab", ".", "utils", ".", "commands", ".", "get_notebook_item", "(", "name", ")", "if", "not", "item", ":", "item", "=", "_get_table", "(", "name", ")", "if", "isinstance", "(", "item", ",", "datalab", ".", "bigquery", ".", "Schema", ")", ":", "return", "item", "if", "hasattr", "(", "item", ",", "'schema'", ")", "and", "isinstance", "(", "item", ".", "schema", ",", "datalab", ".", "bigquery", ".", "_schema", ".", "Schema", ")", ":", "return", "item", ".", "schema", "return", "None" ]
Given a variable or table name, get the Schema if it exists.
[ "Given", "a", "variable", "or", "table", "name", "get", "the", "Schema", "if", "it", "exists", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/commands/_bigquery.py#L574-L584
train
237,900
googledatalab/pydatalab
datalab/bigquery/commands/_bigquery.py
_render_table
def _render_table(data, fields=None): """ Helper to render a list of dictionaries as an HTML display object. """ return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))
python
def _render_table(data, fields=None): """ Helper to render a list of dictionaries as an HTML display object. """ return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))
[ "def", "_render_table", "(", "data", ",", "fields", "=", "None", ")", ":", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "datalab", ".", "utils", ".", "commands", ".", "HtmlBuilder", ".", "render_table", "(", "data", ",", "fields", ")", ")" ]
Helper to render a list of dictionaries as an HTML display object.
[ "Helper", "to", "render", "a", "list", "of", "dictionaries", "as", "an", "HTML", "display", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/commands/_bigquery.py#L636-L638
train
237,901
googledatalab/pydatalab
datalab/bigquery/commands/_bigquery.py
_datasets_line
def _datasets_line(args): """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. """ 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_)])
python
def _datasets_line(args): """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. """ 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_)])
[ "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_", ")", "]", ")" ]
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.
[ "Implements", "the", "BigQuery", "datasets", "magic", "used", "to", "display", "datasets", "in", "a", "project", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/commands/_bigquery.py#L646-L660
train
237,902
googledatalab/pydatalab
datalab/bigquery/commands/_bigquery.py
_tables_line
def _tables_line(args): """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. """ 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.bigquery.Datasets(args['project']) tables = [] for dataset in datasets: tables.extend([str(table) for table in dataset if fnmatch.fnmatch(str(table), filter_)]) return _render_list(tables)
python
def _tables_line(args): """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. """ 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.bigquery.Datasets(args['project']) tables = [] for dataset in datasets: tables.extend([str(table) for table in dataset if fnmatch.fnmatch(str(table), filter_)]) return _render_list(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", ".", "bigquery", ".", "Datasets", "(", "args", "[", "'project'", "]", ")", "tables", "=", "[", "]", "for", "dataset", "in", "datasets", ":", "tables", ".", "extend", "(", "[", "str", "(", "table", ")", "for", "table", "in", "dataset", "if", "fnmatch", ".", "fnmatch", "(", "str", "(", "table", ")", ",", "filter_", ")", "]", ")", "return", "_render_list", "(", "tables", ")" ]
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.
[ "Implements", "the", "BigQuery", "tables", "magic", "used", "to", "display", "tables", "in", "a", "dataset", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/commands/_bigquery.py#L663-L688
train
237,903
googledatalab/pydatalab
datalab/bigquery/commands/_bigquery.py
_extract_line
def _extract_line(args): """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. """ 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 Exception('Table %s does not exist' % name) else: job = source.extract(args['destination'], format='CSV' if args['format'] == 'csv' else 'NEWLINE_DELIMITED_JSON', compress=args['compress'], csv_delimiter=args['delimiter'], csv_header=args['header']) if job.failed: raise Exception('Extract failed: %s' % str(job.fatal_error)) elif job.errors: raise Exception('Extract completed with errors: %s' % str(job.errors))
python
def _extract_line(args): """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. """ 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 Exception('Table %s does not exist' % name) else: job = source.extract(args['destination'], format='CSV' if args['format'] == 'csv' else 'NEWLINE_DELIMITED_JSON', compress=args['compress'], csv_delimiter=args['delimiter'], csv_header=args['header']) if job.failed: raise Exception('Extract failed: %s' % str(job.fatal_error)) elif job.errors: raise Exception('Extract completed with errors: %s' % str(job.errors))
[ "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", "Exception", "(", "'Table %s does not exist'", "%", "name", ")", "else", ":", "job", "=", "source", ".", "extract", "(", "args", "[", "'destination'", "]", ",", "format", "=", "'CSV'", "if", "args", "[", "'format'", "]", "==", "'csv'", "else", "'NEWLINE_DELIMITED_JSON'", ",", "compress", "=", "args", "[", "'compress'", "]", ",", "csv_delimiter", "=", "args", "[", "'delimiter'", "]", ",", "csv_header", "=", "args", "[", "'header'", "]", ")", "if", "job", ".", "failed", ":", "raise", "Exception", "(", "'Extract failed: %s'", "%", "str", "(", "job", ".", "fatal_error", ")", ")", "elif", "job", ".", "errors", ":", "raise", "Exception", "(", "'Extract completed with errors: %s'", "%", "str", "(", "job", ".", "errors", ")", ")" ]
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.
[ "Implements", "the", "BigQuery", "extract", "magic", "used", "to", "extract", "table", "data", "to", "GCS", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/commands/_bigquery.py#L691-L722
train
237,904
googledatalab/pydatalab
datalab/bigquery/commands/_bigquery.py
bigquery
def bigquery(line, cell=None): """Implements the bigquery cell magic for ipython notebooks. The supported syntax is: %%bigquery <command> [<args>] <cell> or: %bigquery <command> [<args>] Use %bigquery --help for a list of commands, or %bigquery <command> --help for help on a specific command. """ namespace = {} if line.find('$') >= 0: # We likely have variables to expand; get the appropriate context. namespace = datalab.utils.commands.notebook_environment() return datalab.utils.commands.handle_magic_line(line, cell, _bigquery_parser, namespace=namespace)
python
def bigquery(line, cell=None): """Implements the bigquery cell magic for ipython notebooks. The supported syntax is: %%bigquery <command> [<args>] <cell> or: %bigquery <command> [<args>] Use %bigquery --help for a list of commands, or %bigquery <command> --help for help on a specific command. """ namespace = {} if line.find('$') >= 0: # We likely have variables to expand; get the appropriate context. namespace = datalab.utils.commands.notebook_environment() return datalab.utils.commands.handle_magic_line(line, cell, _bigquery_parser, namespace=namespace)
[ "def", "bigquery", "(", "line", ",", "cell", "=", "None", ")", ":", "namespace", "=", "{", "}", "if", "line", ".", "find", "(", "'$'", ")", ">=", "0", ":", "# We likely have variables to expand; get the appropriate context.", "namespace", "=", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "return", "datalab", ".", "utils", ".", "commands", ".", "handle_magic_line", "(", "line", ",", "cell", ",", "_bigquery_parser", ",", "namespace", "=", "namespace", ")" ]
Implements the bigquery cell magic for ipython notebooks. The supported syntax is: %%bigquery <command> [<args>] <cell> or: %bigquery <command> [<args>] Use %bigquery --help for a list of commands, or %bigquery <command> --help for help on a specific command.
[ "Implements", "the", "bigquery", "cell", "magic", "for", "ipython", "notebooks", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/commands/_bigquery.py#L840-L860
train
237,905
googledatalab/pydatalab
google/datalab/bigquery/_query_output.py
QueryOutput.table
def table(name=None, mode='create', use_cache=True, priority='interactive', allow_large_results=False): """ Construct a query output object where the result is a table Args: name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query results or ignore cache. Has no effect if destination is specified (default True). priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much as three hours but are not rate-limited. allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is slower and requires a name to be specified) (default False). """ output = QueryOutput() output._output_type = 'table' output._table_name = name output._table_mode = mode output._use_cache = use_cache output._priority = priority output._allow_large_results = allow_large_results return output
python
def table(name=None, mode='create', use_cache=True, priority='interactive', allow_large_results=False): """ Construct a query output object where the result is a table Args: name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query results or ignore cache. Has no effect if destination is specified (default True). priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much as three hours but are not rate-limited. allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is slower and requires a name to be specified) (default False). """ output = QueryOutput() output._output_type = 'table' output._table_name = name output._table_mode = mode output._use_cache = use_cache output._priority = priority output._allow_large_results = allow_large_results return output
[ "def", "table", "(", "name", "=", "None", ",", "mode", "=", "'create'", ",", "use_cache", "=", "True", ",", "priority", "=", "'interactive'", ",", "allow_large_results", "=", "False", ")", ":", "output", "=", "QueryOutput", "(", ")", "output", ".", "_output_type", "=", "'table'", "output", ".", "_table_name", "=", "name", "output", ".", "_table_mode", "=", "mode", "output", ".", "_use_cache", "=", "use_cache", "output", ".", "_priority", "=", "priority", "output", ".", "_allow_large_results", "=", "allow_large_results", "return", "output" ]
Construct a query output object where the result is a table Args: name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query results or ignore cache. Has no effect if destination is specified (default True). priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much as three hours but are not rate-limited. allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is slower and requires a name to be specified) (default False).
[ "Construct", "a", "query", "output", "object", "where", "the", "result", "is", "a", "table" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_query_output.py#L19-L43
train
237,906
googledatalab/pydatalab
google/datalab/bigquery/_query_output.py
QueryOutput.file
def file(path, format='csv', csv_delimiter=',', csv_header=True, compress=False, use_cache=True): """ Construct a query output object where the result is either a local file or a GCS path Note that there are two jobs that may need to be run sequentially, one to run the query, and the second to extract the resulting table. These are wrapped by a single outer Job. If the query has already been executed and you would prefer to get a Job just for the extract, you can can call extract[_async] on the QueryResultsTable returned by the query Args: path: the destination path. Can either be a local or GCS URI (starting with gs://) format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for CSV exports, the field delimiter to use (default ','). csv_header: for CSV exports, whether to include an initial header line (default True). compress: whether to compress the data on export. Compression is not supported for AVRO format (default False). Applies only to GCS URIs. use_cache: whether to use cached results or not (default True). """ output = QueryOutput() output._output_type = 'file' output._file_path = path output._file_format = format output._csv_delimiter = csv_delimiter output._csv_header = csv_header output._compress_file = compress return output
python
def file(path, format='csv', csv_delimiter=',', csv_header=True, compress=False, use_cache=True): """ Construct a query output object where the result is either a local file or a GCS path Note that there are two jobs that may need to be run sequentially, one to run the query, and the second to extract the resulting table. These are wrapped by a single outer Job. If the query has already been executed and you would prefer to get a Job just for the extract, you can can call extract[_async] on the QueryResultsTable returned by the query Args: path: the destination path. Can either be a local or GCS URI (starting with gs://) format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for CSV exports, the field delimiter to use (default ','). csv_header: for CSV exports, whether to include an initial header line (default True). compress: whether to compress the data on export. Compression is not supported for AVRO format (default False). Applies only to GCS URIs. use_cache: whether to use cached results or not (default True). """ output = QueryOutput() output._output_type = 'file' output._file_path = path output._file_format = format output._csv_delimiter = csv_delimiter output._csv_header = csv_header output._compress_file = compress return output
[ "def", "file", "(", "path", ",", "format", "=", "'csv'", ",", "csv_delimiter", "=", "','", ",", "csv_header", "=", "True", ",", "compress", "=", "False", ",", "use_cache", "=", "True", ")", ":", "output", "=", "QueryOutput", "(", ")", "output", ".", "_output_type", "=", "'file'", "output", ".", "_file_path", "=", "path", "output", ".", "_file_format", "=", "format", "output", ".", "_csv_delimiter", "=", "csv_delimiter", "output", ".", "_csv_header", "=", "csv_header", "output", ".", "_compress_file", "=", "compress", "return", "output" ]
Construct a query output object where the result is either a local file or a GCS path Note that there are two jobs that may need to be run sequentially, one to run the query, and the second to extract the resulting table. These are wrapped by a single outer Job. If the query has already been executed and you would prefer to get a Job just for the extract, you can can call extract[_async] on the QueryResultsTable returned by the query Args: path: the destination path. Can either be a local or GCS URI (starting with gs://) format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for CSV exports, the field delimiter to use (default ','). csv_header: for CSV exports, whether to include an initial header line (default True). compress: whether to compress the data on export. Compression is not supported for AVRO format (default False). Applies only to GCS URIs. use_cache: whether to use cached results or not (default True).
[ "Construct", "a", "query", "output", "object", "where", "the", "result", "is", "either", "a", "local", "file", "or", "a", "GCS", "path" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_query_output.py#L46-L73
train
237,907
googledatalab/pydatalab
google/datalab/bigquery/_query_output.py
QueryOutput.dataframe
def dataframe(start_row=0, max_rows=None, use_cache=True): """ Construct a query output object where the result is a 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). use_cache: whether to use cached results or not (default True). """ output = QueryOutput() output._output_type = 'dataframe' output._dataframe_start_row = start_row output._dataframe_max_rows = max_rows output._use_cache = use_cache return output
python
def dataframe(start_row=0, max_rows=None, use_cache=True): """ Construct a query output object where the result is a 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). use_cache: whether to use cached results or not (default True). """ output = QueryOutput() output._output_type = 'dataframe' output._dataframe_start_row = start_row output._dataframe_max_rows = max_rows output._use_cache = use_cache return output
[ "def", "dataframe", "(", "start_row", "=", "0", ",", "max_rows", "=", "None", ",", "use_cache", "=", "True", ")", ":", "output", "=", "QueryOutput", "(", ")", "output", ".", "_output_type", "=", "'dataframe'", "output", ".", "_dataframe_start_row", "=", "start_row", "output", ".", "_dataframe_max_rows", "=", "max_rows", "output", ".", "_use_cache", "=", "use_cache", "return", "output" ]
Construct a query output object where the result is a 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). use_cache: whether to use cached results or not (default True).
[ "Construct", "a", "query", "output", "object", "where", "the", "result", "is", "a", "dataframe" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_query_output.py#L76-L89
train
237,908
googledatalab/pydatalab
google/datalab/ml/_tensorboard.py
TensorBoard.list
def list(): """List running TensorBoard instances.""" running_list = [] parser = argparse.ArgumentParser() parser.add_argument('--logdir') parser.add_argument('--port') for p in psutil.process_iter(): if p.name() != 'tensorboard' or p.status() == psutil.STATUS_ZOMBIE: continue cmd_args = p.cmdline() del cmd_args[0:2] # remove 'python' and 'tensorboard' args = parser.parse_args(cmd_args) running_list.append({'pid': p.pid, 'logdir': args.logdir, 'port': args.port}) return pd.DataFrame(running_list)
python
def list(): """List running TensorBoard instances.""" running_list = [] parser = argparse.ArgumentParser() parser.add_argument('--logdir') parser.add_argument('--port') for p in psutil.process_iter(): if p.name() != 'tensorboard' or p.status() == psutil.STATUS_ZOMBIE: continue cmd_args = p.cmdline() del cmd_args[0:2] # remove 'python' and 'tensorboard' args = parser.parse_args(cmd_args) running_list.append({'pid': p.pid, 'logdir': args.logdir, 'port': args.port}) return pd.DataFrame(running_list)
[ "def", "list", "(", ")", ":", "running_list", "=", "[", "]", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--logdir'", ")", "parser", ".", "add_argument", "(", "'--port'", ")", "for", "p", "in", "psutil", ".", "process_iter", "(", ")", ":", "if", "p", ".", "name", "(", ")", "!=", "'tensorboard'", "or", "p", ".", "status", "(", ")", "==", "psutil", ".", "STATUS_ZOMBIE", ":", "continue", "cmd_args", "=", "p", ".", "cmdline", "(", ")", "del", "cmd_args", "[", "0", ":", "2", "]", "# remove 'python' and 'tensorboard'", "args", "=", "parser", ".", "parse_args", "(", "cmd_args", ")", "running_list", ".", "append", "(", "{", "'pid'", ":", "p", ".", "pid", ",", "'logdir'", ":", "args", ".", "logdir", ",", "'port'", ":", "args", ".", "port", "}", ")", "return", "pd", ".", "DataFrame", "(", "running_list", ")" ]
List running TensorBoard instances.
[ "List", "running", "TensorBoard", "instances", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_tensorboard.py#L33-L47
train
237,909
googledatalab/pydatalab
google/datalab/ml/_tensorboard.py
TensorBoard.start
def start(logdir): """Start a TensorBoard instance. Args: logdir: the logdir to run TensorBoard on. Raises: Exception if the instance cannot be started. """ if logdir.startswith('gs://'): # Check user does have access. TensorBoard will start successfully regardless # the user has read permissions or not so we check permissions here to # give user alerts if needed. datalab.storage._api.Api.verify_permitted_to_read(logdir) port = datalab.utils.pick_unused_port() args = ['tensorboard', '--logdir=' + logdir, '--port=' + str(port)] p = subprocess.Popen(args) retry = 10 while (retry > 0): if datalab.utils.is_http_running_on(port): basepath = os.environ.get('DATALAB_ENDPOINT_URL', '') url = '%s/_proxy/%d/' % (basepath.rstrip('/'), port) html = '<p>TensorBoard was started successfully with pid %d. ' % p.pid html += 'Click <a href="%s" target="_blank">here</a> to access it.</p>' % url IPython.display.display_html(html, raw=True) return p.pid time.sleep(1) retry -= 1 raise Exception('Cannot start TensorBoard.')
python
def start(logdir): """Start a TensorBoard instance. Args: logdir: the logdir to run TensorBoard on. Raises: Exception if the instance cannot be started. """ if logdir.startswith('gs://'): # Check user does have access. TensorBoard will start successfully regardless # the user has read permissions or not so we check permissions here to # give user alerts if needed. datalab.storage._api.Api.verify_permitted_to_read(logdir) port = datalab.utils.pick_unused_port() args = ['tensorboard', '--logdir=' + logdir, '--port=' + str(port)] p = subprocess.Popen(args) retry = 10 while (retry > 0): if datalab.utils.is_http_running_on(port): basepath = os.environ.get('DATALAB_ENDPOINT_URL', '') url = '%s/_proxy/%d/' % (basepath.rstrip('/'), port) html = '<p>TensorBoard was started successfully with pid %d. ' % p.pid html += 'Click <a href="%s" target="_blank">here</a> to access it.</p>' % url IPython.display.display_html(html, raw=True) return p.pid time.sleep(1) retry -= 1 raise Exception('Cannot start TensorBoard.')
[ "def", "start", "(", "logdir", ")", ":", "if", "logdir", ".", "startswith", "(", "'gs://'", ")", ":", "# Check user does have access. TensorBoard will start successfully regardless", "# the user has read permissions or not so we check permissions here to", "# give user alerts if needed.", "datalab", ".", "storage", ".", "_api", ".", "Api", ".", "verify_permitted_to_read", "(", "logdir", ")", "port", "=", "datalab", ".", "utils", ".", "pick_unused_port", "(", ")", "args", "=", "[", "'tensorboard'", ",", "'--logdir='", "+", "logdir", ",", "'--port='", "+", "str", "(", "port", ")", "]", "p", "=", "subprocess", ".", "Popen", "(", "args", ")", "retry", "=", "10", "while", "(", "retry", ">", "0", ")", ":", "if", "datalab", ".", "utils", ".", "is_http_running_on", "(", "port", ")", ":", "basepath", "=", "os", ".", "environ", ".", "get", "(", "'DATALAB_ENDPOINT_URL'", ",", "''", ")", "url", "=", "'%s/_proxy/%d/'", "%", "(", "basepath", ".", "rstrip", "(", "'/'", ")", ",", "port", ")", "html", "=", "'<p>TensorBoard was started successfully with pid %d. '", "%", "p", ".", "pid", "html", "+=", "'Click <a href=\"%s\" target=\"_blank\">here</a> to access it.</p>'", "%", "url", "IPython", ".", "display", ".", "display_html", "(", "html", ",", "raw", "=", "True", ")", "return", "p", ".", "pid", "time", ".", "sleep", "(", "1", ")", "retry", "-=", "1", "raise", "Exception", "(", "'Cannot start TensorBoard.'", ")" ]
Start a TensorBoard instance. Args: logdir: the logdir to run TensorBoard on. Raises: Exception if the instance cannot be started.
[ "Start", "a", "TensorBoard", "instance", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_tensorboard.py#L50-L79
train
237,910
googledatalab/pydatalab
google/datalab/ml/_tensorboard.py
TensorBoard.stop
def stop(pid): """Shut down a specific process. Args: pid: the pid of the process to shutdown. """ if psutil.pid_exists(pid): try: p = psutil.Process(pid) p.kill() except Exception: pass
python
def stop(pid): """Shut down a specific process. Args: pid: the pid of the process to shutdown. """ if psutil.pid_exists(pid): try: p = psutil.Process(pid) p.kill() except Exception: pass
[ "def", "stop", "(", "pid", ")", ":", "if", "psutil", ".", "pid_exists", "(", "pid", ")", ":", "try", ":", "p", "=", "psutil", ".", "Process", "(", "pid", ")", "p", ".", "kill", "(", ")", "except", "Exception", ":", "pass" ]
Shut down a specific process. Args: pid: the pid of the process to shutdown.
[ "Shut", "down", "a", "specific", "process", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_tensorboard.py#L82-L93
train
237,911
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_preprocess.py
EmbeddingsGraph.build_graph
def build_graph(self): """Forms the core by building a wrapper around the inception graph. Here we add the necessary input & output tensors, to decode jpegs, serialize embeddings, restore from checkpoint etc. To use other Inception models modify this file. Note that to use other models beside Inception, you should make sure input_shape matches their input. Resizing or other modifications may be necessary as well. See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for details about InceptionV3. Returns: input_jpeg: A tensor containing raw image bytes as the input layer. embedding: The embeddings tensor, that will be materialized later. """ import tensorflow as tf input_jpeg = tf.placeholder(tf.string, shape=None) image = tf.image.decode_jpeg(input_jpeg, channels=self.CHANNELS) # Note resize expects a batch_size, but we are feeding a single image. # So we have to expand then squeeze. Resize returns float32 in the # range [0, uint8_max] image = tf.expand_dims(image, 0) # convert_image_dtype also scales [0, uint8_max] -> [0 ,1). image = tf.image.convert_image_dtype(image, dtype=tf.float32) image = tf.image.resize_bilinear( image, [self.HEIGHT, self.WIDTH], align_corners=False) # Then rescale range to [-1, 1) for Inception. image = tf.subtract(image, 0.5) inception_input = tf.multiply(image, 2.0) # Build Inception layers, which expect a tensor of type float from [-1, 1) # and shape [batch_size, height, width, channels]. with tf.contrib.slim.arg_scope(_inceptionlib.inception_v3_arg_scope()): _, end_points = _inceptionlib.inception_v3(inception_input, is_training=False) embedding = end_points['PreLogits'] return input_jpeg, embedding
python
def build_graph(self): """Forms the core by building a wrapper around the inception graph. Here we add the necessary input & output tensors, to decode jpegs, serialize embeddings, restore from checkpoint etc. To use other Inception models modify this file. Note that to use other models beside Inception, you should make sure input_shape matches their input. Resizing or other modifications may be necessary as well. See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for details about InceptionV3. Returns: input_jpeg: A tensor containing raw image bytes as the input layer. embedding: The embeddings tensor, that will be materialized later. """ import tensorflow as tf input_jpeg = tf.placeholder(tf.string, shape=None) image = tf.image.decode_jpeg(input_jpeg, channels=self.CHANNELS) # Note resize expects a batch_size, but we are feeding a single image. # So we have to expand then squeeze. Resize returns float32 in the # range [0, uint8_max] image = tf.expand_dims(image, 0) # convert_image_dtype also scales [0, uint8_max] -> [0 ,1). image = tf.image.convert_image_dtype(image, dtype=tf.float32) image = tf.image.resize_bilinear( image, [self.HEIGHT, self.WIDTH], align_corners=False) # Then rescale range to [-1, 1) for Inception. image = tf.subtract(image, 0.5) inception_input = tf.multiply(image, 2.0) # Build Inception layers, which expect a tensor of type float from [-1, 1) # and shape [batch_size, height, width, channels]. with tf.contrib.slim.arg_scope(_inceptionlib.inception_v3_arg_scope()): _, end_points = _inceptionlib.inception_v3(inception_input, is_training=False) embedding = end_points['PreLogits'] return input_jpeg, embedding
[ "def", "build_graph", "(", "self", ")", ":", "import", "tensorflow", "as", "tf", "input_jpeg", "=", "tf", ".", "placeholder", "(", "tf", ".", "string", ",", "shape", "=", "None", ")", "image", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "input_jpeg", ",", "channels", "=", "self", ".", "CHANNELS", ")", "# Note resize expects a batch_size, but we are feeding a single image.", "# So we have to expand then squeeze. Resize returns float32 in the", "# range [0, uint8_max]", "image", "=", "tf", ".", "expand_dims", "(", "image", ",", "0", ")", "# convert_image_dtype also scales [0, uint8_max] -> [0 ,1).", "image", "=", "tf", ".", "image", ".", "convert_image_dtype", "(", "image", ",", "dtype", "=", "tf", ".", "float32", ")", "image", "=", "tf", ".", "image", ".", "resize_bilinear", "(", "image", ",", "[", "self", ".", "HEIGHT", ",", "self", ".", "WIDTH", "]", ",", "align_corners", "=", "False", ")", "# Then rescale range to [-1, 1) for Inception.", "image", "=", "tf", ".", "subtract", "(", "image", ",", "0.5", ")", "inception_input", "=", "tf", ".", "multiply", "(", "image", ",", "2.0", ")", "# Build Inception layers, which expect a tensor of type float from [-1, 1)", "# and shape [batch_size, height, width, channels].", "with", "tf", ".", "contrib", ".", "slim", ".", "arg_scope", "(", "_inceptionlib", ".", "inception_v3_arg_scope", "(", ")", ")", ":", "_", ",", "end_points", "=", "_inceptionlib", ".", "inception_v3", "(", "inception_input", ",", "is_training", "=", "False", ")", "embedding", "=", "end_points", "[", "'PreLogits'", "]", "return", "input_jpeg", ",", "embedding" ]
Forms the core by building a wrapper around the inception graph. Here we add the necessary input & output tensors, to decode jpegs, serialize embeddings, restore from checkpoint etc. To use other Inception models modify this file. Note that to use other models beside Inception, you should make sure input_shape matches their input. Resizing or other modifications may be necessary as well. See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for details about InceptionV3. Returns: input_jpeg: A tensor containing raw image bytes as the input layer. embedding: The embeddings tensor, that will be materialized later.
[ "Forms", "the", "core", "by", "building", "a", "wrapper", "around", "the", "inception", "graph", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_preprocess.py#L126-L167
train
237,912
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_preprocess.py
EmbeddingsGraph.restore_from_checkpoint
def restore_from_checkpoint(self, checkpoint_path): """To restore inception model variables from the checkpoint file. Some variables might be missing in the checkpoint file, so it only loads the ones that are avialable, assuming the rest would be initialized later. Args: checkpoint_path: Path to the checkpoint file for the Inception graph. """ import tensorflow as tf # Get all variables to restore. Exclude Logits and AuxLogits because they # depend on the input data and we do not need to intialize them from # checkpoint. all_vars = tf.contrib.slim.get_variables_to_restore( exclude=['InceptionV3/AuxLogits', 'InceptionV3/Logits', 'global_step']) saver = tf.train.Saver(all_vars) saver.restore(self.tf_session, checkpoint_path)
python
def restore_from_checkpoint(self, checkpoint_path): """To restore inception model variables from the checkpoint file. Some variables might be missing in the checkpoint file, so it only loads the ones that are avialable, assuming the rest would be initialized later. Args: checkpoint_path: Path to the checkpoint file for the Inception graph. """ import tensorflow as tf # Get all variables to restore. Exclude Logits and AuxLogits because they # depend on the input data and we do not need to intialize them from # checkpoint. all_vars = tf.contrib.slim.get_variables_to_restore( exclude=['InceptionV3/AuxLogits', 'InceptionV3/Logits', 'global_step']) saver = tf.train.Saver(all_vars) saver.restore(self.tf_session, checkpoint_path)
[ "def", "restore_from_checkpoint", "(", "self", ",", "checkpoint_path", ")", ":", "import", "tensorflow", "as", "tf", "# Get all variables to restore. Exclude Logits and AuxLogits because they", "# depend on the input data and we do not need to intialize them from", "# checkpoint.", "all_vars", "=", "tf", ".", "contrib", ".", "slim", ".", "get_variables_to_restore", "(", "exclude", "=", "[", "'InceptionV3/AuxLogits'", ",", "'InceptionV3/Logits'", ",", "'global_step'", "]", ")", "saver", "=", "tf", ".", "train", ".", "Saver", "(", "all_vars", ")", "saver", ".", "restore", "(", "self", ".", "tf_session", ",", "checkpoint_path", ")" ]
To restore inception model variables from the checkpoint file. Some variables might be missing in the checkpoint file, so it only loads the ones that are avialable, assuming the rest would be initialized later. Args: checkpoint_path: Path to the checkpoint file for the Inception graph.
[ "To", "restore", "inception", "model", "variables", "from", "the", "checkpoint", "file", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_preprocess.py#L169-L186
train
237,913
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_preprocess.py
EmbeddingsGraph.calculate_embedding
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embedding, feed_dict={self.input_jpeg: batch_image_bytes})
python
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embedding, feed_dict={self.input_jpeg: batch_image_bytes})
[ "def", "calculate_embedding", "(", "self", ",", "batch_image_bytes", ")", ":", "return", "self", ".", "tf_session", ".", "run", "(", "self", ".", "embedding", ",", "feed_dict", "=", "{", "self", ".", "input_jpeg", ":", "batch_image_bytes", "}", ")" ]
Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output)
[ "Get", "the", "embeddings", "for", "a", "given", "JPEG", "image", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_preprocess.py#L188-L198
train
237,914
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_model.py
Model.add_final_training_ops
def add_final_training_ops(self, embeddings, all_labels_count, bottleneck_tensor_size, hidden_layer_size=BOTTLENECK_TENSOR_SIZE / 4, dropout_keep_prob=None): """Adds a new softmax and fully-connected layer for training. The set up for the softmax and fully-connected layers is based on: https://tensorflow.org/versions/master/tutorials/mnist/beginners/index.html This function can be customized to add arbitrary layers for application-specific requirements. Args: embeddings: The embedding (bottleneck) tensor. all_labels_count: The number of all labels including the default label. bottleneck_tensor_size: The number of embeddings. hidden_layer_size: The size of the hidden_layer. Roughtly, 1/4 of the bottleneck tensor size. dropout_keep_prob: the percentage of activation values that are retained. Returns: softmax: The softmax or tensor. It stores the final scores. logits: The logits tensor. """ with tf.name_scope('input'): bottleneck_input = tf.placeholder_with_default( embeddings, shape=[None, bottleneck_tensor_size], name='ReshapeSqueezed') bottleneck_with_no_gradient = tf.stop_gradient(bottleneck_input) with tf.name_scope('Wx_plus_b'): hidden = layers.fully_connected(bottleneck_with_no_gradient, hidden_layer_size) # We need a dropout when the size of the dataset is rather small. if dropout_keep_prob: hidden = tf.nn.dropout(hidden, dropout_keep_prob) logits = layers.fully_connected( hidden, all_labels_count, activation_fn=None) softmax = tf.nn.softmax(logits, name='softmax') return softmax, logits
python
def add_final_training_ops(self, embeddings, all_labels_count, bottleneck_tensor_size, hidden_layer_size=BOTTLENECK_TENSOR_SIZE / 4, dropout_keep_prob=None): """Adds a new softmax and fully-connected layer for training. The set up for the softmax and fully-connected layers is based on: https://tensorflow.org/versions/master/tutorials/mnist/beginners/index.html This function can be customized to add arbitrary layers for application-specific requirements. Args: embeddings: The embedding (bottleneck) tensor. all_labels_count: The number of all labels including the default label. bottleneck_tensor_size: The number of embeddings. hidden_layer_size: The size of the hidden_layer. Roughtly, 1/4 of the bottleneck tensor size. dropout_keep_prob: the percentage of activation values that are retained. Returns: softmax: The softmax or tensor. It stores the final scores. logits: The logits tensor. """ with tf.name_scope('input'): bottleneck_input = tf.placeholder_with_default( embeddings, shape=[None, bottleneck_tensor_size], name='ReshapeSqueezed') bottleneck_with_no_gradient = tf.stop_gradient(bottleneck_input) with tf.name_scope('Wx_plus_b'): hidden = layers.fully_connected(bottleneck_with_no_gradient, hidden_layer_size) # We need a dropout when the size of the dataset is rather small. if dropout_keep_prob: hidden = tf.nn.dropout(hidden, dropout_keep_prob) logits = layers.fully_connected( hidden, all_labels_count, activation_fn=None) softmax = tf.nn.softmax(logits, name='softmax') return softmax, logits
[ "def", "add_final_training_ops", "(", "self", ",", "embeddings", ",", "all_labels_count", ",", "bottleneck_tensor_size", ",", "hidden_layer_size", "=", "BOTTLENECK_TENSOR_SIZE", "/", "4", ",", "dropout_keep_prob", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "'input'", ")", ":", "bottleneck_input", "=", "tf", ".", "placeholder_with_default", "(", "embeddings", ",", "shape", "=", "[", "None", ",", "bottleneck_tensor_size", "]", ",", "name", "=", "'ReshapeSqueezed'", ")", "bottleneck_with_no_gradient", "=", "tf", ".", "stop_gradient", "(", "bottleneck_input", ")", "with", "tf", ".", "name_scope", "(", "'Wx_plus_b'", ")", ":", "hidden", "=", "layers", ".", "fully_connected", "(", "bottleneck_with_no_gradient", ",", "hidden_layer_size", ")", "# We need a dropout when the size of the dataset is rather small.", "if", "dropout_keep_prob", ":", "hidden", "=", "tf", ".", "nn", ".", "dropout", "(", "hidden", ",", "dropout_keep_prob", ")", "logits", "=", "layers", ".", "fully_connected", "(", "hidden", ",", "all_labels_count", ",", "activation_fn", "=", "None", ")", "softmax", "=", "tf", ".", "nn", ".", "softmax", "(", "logits", ",", "name", "=", "'softmax'", ")", "return", "softmax", ",", "logits" ]
Adds a new softmax and fully-connected layer for training. The set up for the softmax and fully-connected layers is based on: https://tensorflow.org/versions/master/tutorials/mnist/beginners/index.html This function can be customized to add arbitrary layers for application-specific requirements. Args: embeddings: The embedding (bottleneck) tensor. all_labels_count: The number of all labels including the default label. bottleneck_tensor_size: The number of embeddings. hidden_layer_size: The size of the hidden_layer. Roughtly, 1/4 of the bottleneck tensor size. dropout_keep_prob: the percentage of activation values that are retained. Returns: softmax: The softmax or tensor. It stores the final scores. logits: The logits tensor.
[ "Adds", "a", "new", "softmax", "and", "fully", "-", "connected", "layer", "for", "training", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_model.py#L71-L112
train
237,915
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_model.py
Model.build_inception_graph
def build_inception_graph(self): """Builds an inception graph and add the necessary input & output tensors. To use other Inception models modify this file. Also preprocessing must be modified accordingly. See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for details about InceptionV3. Returns: input_jpeg: A placeholder for jpeg string batch that allows feeding the Inception layer with image bytes for prediction. inception_embeddings: The embeddings tensor. """ image_str_tensor = tf.placeholder(tf.string, shape=[None]) # The CloudML Prediction API always "feeds" the Tensorflow graph with # dynamic batch sizes e.g. (?,). decode_jpeg only processes scalar # strings because it cannot guarantee a batch of images would have # the same output size. We use tf.map_fn to give decode_jpeg a scalar # string from dynamic batches. image = tf.map_fn( _util.decode_and_resize, image_str_tensor, back_prop=False, dtype=tf.uint8) # convert_image_dtype, also scales [0, uint8_max] -> [0 ,1). image = tf.image.convert_image_dtype(image, dtype=tf.float32) # Then shift images to [-1, 1) for Inception. image = tf.subtract(image, 0.5) image = tf.multiply(image, 2.0) # Build Inception layers, which expect A tensor of type float from [-1, 1) # and shape [batch_size, height, width, channels]. with slim.arg_scope(_inceptionlib.inception_v3_arg_scope()): _, end_points = _inceptionlib.inception_v3(image, is_training=False) inception_embeddings = end_points['PreLogits'] inception_embeddings = tf.squeeze( inception_embeddings, [1, 2], name='SpatialSqueeze') return image_str_tensor, inception_embeddings
python
def build_inception_graph(self): """Builds an inception graph and add the necessary input & output tensors. To use other Inception models modify this file. Also preprocessing must be modified accordingly. See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for details about InceptionV3. Returns: input_jpeg: A placeholder for jpeg string batch that allows feeding the Inception layer with image bytes for prediction. inception_embeddings: The embeddings tensor. """ image_str_tensor = tf.placeholder(tf.string, shape=[None]) # The CloudML Prediction API always "feeds" the Tensorflow graph with # dynamic batch sizes e.g. (?,). decode_jpeg only processes scalar # strings because it cannot guarantee a batch of images would have # the same output size. We use tf.map_fn to give decode_jpeg a scalar # string from dynamic batches. image = tf.map_fn( _util.decode_and_resize, image_str_tensor, back_prop=False, dtype=tf.uint8) # convert_image_dtype, also scales [0, uint8_max] -> [0 ,1). image = tf.image.convert_image_dtype(image, dtype=tf.float32) # Then shift images to [-1, 1) for Inception. image = tf.subtract(image, 0.5) image = tf.multiply(image, 2.0) # Build Inception layers, which expect A tensor of type float from [-1, 1) # and shape [batch_size, height, width, channels]. with slim.arg_scope(_inceptionlib.inception_v3_arg_scope()): _, end_points = _inceptionlib.inception_v3(image, is_training=False) inception_embeddings = end_points['PreLogits'] inception_embeddings = tf.squeeze( inception_embeddings, [1, 2], name='SpatialSqueeze') return image_str_tensor, inception_embeddings
[ "def", "build_inception_graph", "(", "self", ")", ":", "image_str_tensor", "=", "tf", ".", "placeholder", "(", "tf", ".", "string", ",", "shape", "=", "[", "None", "]", ")", "# The CloudML Prediction API always \"feeds\" the Tensorflow graph with", "# dynamic batch sizes e.g. (?,). decode_jpeg only processes scalar", "# strings because it cannot guarantee a batch of images would have", "# the same output size. We use tf.map_fn to give decode_jpeg a scalar", "# string from dynamic batches.", "image", "=", "tf", ".", "map_fn", "(", "_util", ".", "decode_and_resize", ",", "image_str_tensor", ",", "back_prop", "=", "False", ",", "dtype", "=", "tf", ".", "uint8", ")", "# convert_image_dtype, also scales [0, uint8_max] -> [0 ,1).", "image", "=", "tf", ".", "image", ".", "convert_image_dtype", "(", "image", ",", "dtype", "=", "tf", ".", "float32", ")", "# Then shift images to [-1, 1) for Inception.", "image", "=", "tf", ".", "subtract", "(", "image", ",", "0.5", ")", "image", "=", "tf", ".", "multiply", "(", "image", ",", "2.0", ")", "# Build Inception layers, which expect A tensor of type float from [-1, 1)", "# and shape [batch_size, height, width, channels].", "with", "slim", ".", "arg_scope", "(", "_inceptionlib", ".", "inception_v3_arg_scope", "(", ")", ")", ":", "_", ",", "end_points", "=", "_inceptionlib", ".", "inception_v3", "(", "image", ",", "is_training", "=", "False", ")", "inception_embeddings", "=", "end_points", "[", "'PreLogits'", "]", "inception_embeddings", "=", "tf", ".", "squeeze", "(", "inception_embeddings", ",", "[", "1", ",", "2", "]", ",", "name", "=", "'SpatialSqueeze'", ")", "return", "image_str_tensor", ",", "inception_embeddings" ]
Builds an inception graph and add the necessary input & output tensors. To use other Inception models modify this file. Also preprocessing must be modified accordingly. See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for details about InceptionV3. Returns: input_jpeg: A placeholder for jpeg string batch that allows feeding the Inception layer with image bytes for prediction. inception_embeddings: The embeddings tensor.
[ "Builds", "an", "inception", "graph", "and", "add", "the", "necessary", "input", "&", "output", "tensors", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_model.py#L114-L152
train
237,916
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_model.py
Model.build_graph
def build_graph(self, data_paths, batch_size, graph_mod): """Builds generic graph for training or eval.""" tensors = GraphReferences() is_training = graph_mod == GraphMod.TRAIN if data_paths: _, tensors.examples = _util.read_examples( data_paths, batch_size, shuffle=is_training, num_epochs=None if is_training else 2) else: tensors.examples = tf.placeholder(tf.string, name='input', shape=(None,)) if graph_mod == GraphMod.PREDICT: inception_input, inception_embeddings = self.build_inception_graph() # Build the Inception graph. We later add final training layers # to this graph. This is currently used only for prediction. # For training, we use pre-processed data, so it is not needed. embeddings = inception_embeddings tensors.input_jpeg = inception_input else: # For training and evaluation we assume data is preprocessed, so the # inputs are tf-examples. # Generate placeholders for examples. with tf.name_scope('inputs'): feature_map = { 'image_uri': tf.FixedLenFeature( shape=[], dtype=tf.string, default_value=['']), # Some images may have no labels. For those, we assume a default # label. So the number of labels is label_count+1 for the default # label. 'label': tf.FixedLenFeature( shape=[1], dtype=tf.int64, default_value=[len(self.labels)]), 'embedding': tf.FixedLenFeature( shape=[BOTTLENECK_TENSOR_SIZE], dtype=tf.float32) } parsed = tf.parse_example(tensors.examples, features=feature_map) labels = tf.squeeze(parsed['label']) uris = tf.squeeze(parsed['image_uri']) embeddings = parsed['embedding'] # We assume a default label, so the total number of labels is equal to # label_count+1. all_labels_count = len(self.labels) + 1 with tf.name_scope('final_ops'): softmax, logits = self.add_final_training_ops( embeddings, all_labels_count, BOTTLENECK_TENSOR_SIZE, dropout_keep_prob=self.dropout if is_training else None) # Prediction is the index of the label with the highest score. We are # interested only in the top score. prediction = tf.argmax(softmax, 1) tensors.predictions = [prediction, softmax, embeddings] if graph_mod == GraphMod.PREDICT: return tensors with tf.name_scope('evaluate'): loss_value = loss(logits, labels) # Add to the Graph the Ops that calculate and apply gradients. if is_training: tensors.train, tensors.global_step = training(loss_value) else: tensors.global_step = tf.Variable(0, name='global_step', trainable=False) tensors.uris = uris # Add means across all batches. loss_updates, loss_op = _util.loss(loss_value) accuracy_updates, accuracy_op = _util.accuracy(logits, labels) if not is_training: tf.summary.scalar('accuracy', accuracy_op) tf.summary.scalar('loss', loss_op) tensors.metric_updates = loss_updates + accuracy_updates tensors.metric_values = [loss_op, accuracy_op] return tensors
python
def build_graph(self, data_paths, batch_size, graph_mod): """Builds generic graph for training or eval.""" tensors = GraphReferences() is_training = graph_mod == GraphMod.TRAIN if data_paths: _, tensors.examples = _util.read_examples( data_paths, batch_size, shuffle=is_training, num_epochs=None if is_training else 2) else: tensors.examples = tf.placeholder(tf.string, name='input', shape=(None,)) if graph_mod == GraphMod.PREDICT: inception_input, inception_embeddings = self.build_inception_graph() # Build the Inception graph. We later add final training layers # to this graph. This is currently used only for prediction. # For training, we use pre-processed data, so it is not needed. embeddings = inception_embeddings tensors.input_jpeg = inception_input else: # For training and evaluation we assume data is preprocessed, so the # inputs are tf-examples. # Generate placeholders for examples. with tf.name_scope('inputs'): feature_map = { 'image_uri': tf.FixedLenFeature( shape=[], dtype=tf.string, default_value=['']), # Some images may have no labels. For those, we assume a default # label. So the number of labels is label_count+1 for the default # label. 'label': tf.FixedLenFeature( shape=[1], dtype=tf.int64, default_value=[len(self.labels)]), 'embedding': tf.FixedLenFeature( shape=[BOTTLENECK_TENSOR_SIZE], dtype=tf.float32) } parsed = tf.parse_example(tensors.examples, features=feature_map) labels = tf.squeeze(parsed['label']) uris = tf.squeeze(parsed['image_uri']) embeddings = parsed['embedding'] # We assume a default label, so the total number of labels is equal to # label_count+1. all_labels_count = len(self.labels) + 1 with tf.name_scope('final_ops'): softmax, logits = self.add_final_training_ops( embeddings, all_labels_count, BOTTLENECK_TENSOR_SIZE, dropout_keep_prob=self.dropout if is_training else None) # Prediction is the index of the label with the highest score. We are # interested only in the top score. prediction = tf.argmax(softmax, 1) tensors.predictions = [prediction, softmax, embeddings] if graph_mod == GraphMod.PREDICT: return tensors with tf.name_scope('evaluate'): loss_value = loss(logits, labels) # Add to the Graph the Ops that calculate and apply gradients. if is_training: tensors.train, tensors.global_step = training(loss_value) else: tensors.global_step = tf.Variable(0, name='global_step', trainable=False) tensors.uris = uris # Add means across all batches. loss_updates, loss_op = _util.loss(loss_value) accuracy_updates, accuracy_op = _util.accuracy(logits, labels) if not is_training: tf.summary.scalar('accuracy', accuracy_op) tf.summary.scalar('loss', loss_op) tensors.metric_updates = loss_updates + accuracy_updates tensors.metric_values = [loss_op, accuracy_op] return tensors
[ "def", "build_graph", "(", "self", ",", "data_paths", ",", "batch_size", ",", "graph_mod", ")", ":", "tensors", "=", "GraphReferences", "(", ")", "is_training", "=", "graph_mod", "==", "GraphMod", ".", "TRAIN", "if", "data_paths", ":", "_", ",", "tensors", ".", "examples", "=", "_util", ".", "read_examples", "(", "data_paths", ",", "batch_size", ",", "shuffle", "=", "is_training", ",", "num_epochs", "=", "None", "if", "is_training", "else", "2", ")", "else", ":", "tensors", ".", "examples", "=", "tf", ".", "placeholder", "(", "tf", ".", "string", ",", "name", "=", "'input'", ",", "shape", "=", "(", "None", ",", ")", ")", "if", "graph_mod", "==", "GraphMod", ".", "PREDICT", ":", "inception_input", ",", "inception_embeddings", "=", "self", ".", "build_inception_graph", "(", ")", "# Build the Inception graph. We later add final training layers", "# to this graph. This is currently used only for prediction.", "# For training, we use pre-processed data, so it is not needed.", "embeddings", "=", "inception_embeddings", "tensors", ".", "input_jpeg", "=", "inception_input", "else", ":", "# For training and evaluation we assume data is preprocessed, so the", "# inputs are tf-examples.", "# Generate placeholders for examples.", "with", "tf", ".", "name_scope", "(", "'inputs'", ")", ":", "feature_map", "=", "{", "'image_uri'", ":", "tf", ".", "FixedLenFeature", "(", "shape", "=", "[", "]", ",", "dtype", "=", "tf", ".", "string", ",", "default_value", "=", "[", "''", "]", ")", ",", "# Some images may have no labels. For those, we assume a default", "# label. So the number of labels is label_count+1 for the default", "# label.", "'label'", ":", "tf", ".", "FixedLenFeature", "(", "shape", "=", "[", "1", "]", ",", "dtype", "=", "tf", ".", "int64", ",", "default_value", "=", "[", "len", "(", "self", ".", "labels", ")", "]", ")", ",", "'embedding'", ":", "tf", ".", "FixedLenFeature", "(", "shape", "=", "[", "BOTTLENECK_TENSOR_SIZE", "]", ",", "dtype", "=", "tf", ".", "float32", ")", "}", "parsed", "=", "tf", ".", "parse_example", "(", "tensors", ".", "examples", ",", "features", "=", "feature_map", ")", "labels", "=", "tf", ".", "squeeze", "(", "parsed", "[", "'label'", "]", ")", "uris", "=", "tf", ".", "squeeze", "(", "parsed", "[", "'image_uri'", "]", ")", "embeddings", "=", "parsed", "[", "'embedding'", "]", "# We assume a default label, so the total number of labels is equal to", "# label_count+1.", "all_labels_count", "=", "len", "(", "self", ".", "labels", ")", "+", "1", "with", "tf", ".", "name_scope", "(", "'final_ops'", ")", ":", "softmax", ",", "logits", "=", "self", ".", "add_final_training_ops", "(", "embeddings", ",", "all_labels_count", ",", "BOTTLENECK_TENSOR_SIZE", ",", "dropout_keep_prob", "=", "self", ".", "dropout", "if", "is_training", "else", "None", ")", "# Prediction is the index of the label with the highest score. We are", "# interested only in the top score.", "prediction", "=", "tf", ".", "argmax", "(", "softmax", ",", "1", ")", "tensors", ".", "predictions", "=", "[", "prediction", ",", "softmax", ",", "embeddings", "]", "if", "graph_mod", "==", "GraphMod", ".", "PREDICT", ":", "return", "tensors", "with", "tf", ".", "name_scope", "(", "'evaluate'", ")", ":", "loss_value", "=", "loss", "(", "logits", ",", "labels", ")", "# Add to the Graph the Ops that calculate and apply gradients.", "if", "is_training", ":", "tensors", ".", "train", ",", "tensors", ".", "global_step", "=", "training", "(", "loss_value", ")", "else", ":", "tensors", ".", "global_step", "=", "tf", ".", "Variable", "(", "0", ",", "name", "=", "'global_step'", ",", "trainable", "=", "False", ")", "tensors", ".", "uris", "=", "uris", "# Add means across all batches.", "loss_updates", ",", "loss_op", "=", "_util", ".", "loss", "(", "loss_value", ")", "accuracy_updates", ",", "accuracy_op", "=", "_util", ".", "accuracy", "(", "logits", ",", "labels", ")", "if", "not", "is_training", ":", "tf", ".", "summary", ".", "scalar", "(", "'accuracy'", ",", "accuracy_op", ")", "tf", ".", "summary", ".", "scalar", "(", "'loss'", ",", "loss_op", ")", "tensors", ".", "metric_updates", "=", "loss_updates", "+", "accuracy_updates", "tensors", ".", "metric_values", "=", "[", "loss_op", ",", "accuracy_op", "]", "return", "tensors" ]
Builds generic graph for training or eval.
[ "Builds", "generic", "graph", "for", "training", "or", "eval", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_model.py#L154-L237
train
237,917
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_model.py
Model.restore_from_checkpoint
def restore_from_checkpoint(self, session, inception_checkpoint_file, trained_checkpoint_file): """To restore model variables from the checkpoint file. The graph is assumed to consist of an inception model and other layers including a softmax and a fully connected layer. The former is pre-trained and the latter is trained using the pre-processed data. So we restore this from two checkpoint files. Args: session: The session to be used for restoring from checkpoint. inception_checkpoint_file: Path to the checkpoint file for the Inception graph. trained_checkpoint_file: path to the trained checkpoint for the other layers. """ inception_exclude_scopes = [ 'InceptionV3/AuxLogits', 'InceptionV3/Logits', 'global_step', 'final_ops' ] reader = tf.train.NewCheckpointReader(inception_checkpoint_file) var_to_shape_map = reader.get_variable_to_shape_map() # Get all variables to restore. Exclude Logits and AuxLogits because they # depend on the input data and we do not need to intialize them. all_vars = tf.contrib.slim.get_variables_to_restore( exclude=inception_exclude_scopes) # Remove variables that do not exist in the inception checkpoint (for # example the final softmax and fully-connected layers). inception_vars = { var.op.name: var for var in all_vars if var.op.name in var_to_shape_map } inception_saver = tf.train.Saver(inception_vars) inception_saver.restore(session, inception_checkpoint_file) # Restore the rest of the variables from the trained checkpoint. trained_vars = tf.contrib.slim.get_variables_to_restore( exclude=inception_exclude_scopes + inception_vars.keys()) trained_saver = tf.train.Saver(trained_vars) trained_saver.restore(session, trained_checkpoint_file)
python
def restore_from_checkpoint(self, session, inception_checkpoint_file, trained_checkpoint_file): """To restore model variables from the checkpoint file. The graph is assumed to consist of an inception model and other layers including a softmax and a fully connected layer. The former is pre-trained and the latter is trained using the pre-processed data. So we restore this from two checkpoint files. Args: session: The session to be used for restoring from checkpoint. inception_checkpoint_file: Path to the checkpoint file for the Inception graph. trained_checkpoint_file: path to the trained checkpoint for the other layers. """ inception_exclude_scopes = [ 'InceptionV3/AuxLogits', 'InceptionV3/Logits', 'global_step', 'final_ops' ] reader = tf.train.NewCheckpointReader(inception_checkpoint_file) var_to_shape_map = reader.get_variable_to_shape_map() # Get all variables to restore. Exclude Logits and AuxLogits because they # depend on the input data and we do not need to intialize them. all_vars = tf.contrib.slim.get_variables_to_restore( exclude=inception_exclude_scopes) # Remove variables that do not exist in the inception checkpoint (for # example the final softmax and fully-connected layers). inception_vars = { var.op.name: var for var in all_vars if var.op.name in var_to_shape_map } inception_saver = tf.train.Saver(inception_vars) inception_saver.restore(session, inception_checkpoint_file) # Restore the rest of the variables from the trained checkpoint. trained_vars = tf.contrib.slim.get_variables_to_restore( exclude=inception_exclude_scopes + inception_vars.keys()) trained_saver = tf.train.Saver(trained_vars) trained_saver.restore(session, trained_checkpoint_file)
[ "def", "restore_from_checkpoint", "(", "self", ",", "session", ",", "inception_checkpoint_file", ",", "trained_checkpoint_file", ")", ":", "inception_exclude_scopes", "=", "[", "'InceptionV3/AuxLogits'", ",", "'InceptionV3/Logits'", ",", "'global_step'", ",", "'final_ops'", "]", "reader", "=", "tf", ".", "train", ".", "NewCheckpointReader", "(", "inception_checkpoint_file", ")", "var_to_shape_map", "=", "reader", ".", "get_variable_to_shape_map", "(", ")", "# Get all variables to restore. Exclude Logits and AuxLogits because they", "# depend on the input data and we do not need to intialize them.", "all_vars", "=", "tf", ".", "contrib", ".", "slim", ".", "get_variables_to_restore", "(", "exclude", "=", "inception_exclude_scopes", ")", "# Remove variables that do not exist in the inception checkpoint (for", "# example the final softmax and fully-connected layers).", "inception_vars", "=", "{", "var", ".", "op", ".", "name", ":", "var", "for", "var", "in", "all_vars", "if", "var", ".", "op", ".", "name", "in", "var_to_shape_map", "}", "inception_saver", "=", "tf", ".", "train", ".", "Saver", "(", "inception_vars", ")", "inception_saver", ".", "restore", "(", "session", ",", "inception_checkpoint_file", ")", "# Restore the rest of the variables from the trained checkpoint.", "trained_vars", "=", "tf", ".", "contrib", ".", "slim", ".", "get_variables_to_restore", "(", "exclude", "=", "inception_exclude_scopes", "+", "inception_vars", ".", "keys", "(", ")", ")", "trained_saver", "=", "tf", ".", "train", ".", "Saver", "(", "trained_vars", ")", "trained_saver", ".", "restore", "(", "session", ",", "trained_checkpoint_file", ")" ]
To restore model variables from the checkpoint file. The graph is assumed to consist of an inception model and other layers including a softmax and a fully connected layer. The former is pre-trained and the latter is trained using the pre-processed data. So we restore this from two checkpoint files. Args: session: The session to be used for restoring from checkpoint. inception_checkpoint_file: Path to the checkpoint file for the Inception graph. trained_checkpoint_file: path to the trained checkpoint for the other layers.
[ "To", "restore", "model", "variables", "from", "the", "checkpoint", "file", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_model.py#L245-L284
train
237,918
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_model.py
Model.build_prediction_graph
def build_prediction_graph(self): """Builds prediction graph and registers appropriate endpoints.""" tensors = self.build_graph(None, 1, GraphMod.PREDICT) keys_placeholder = tf.placeholder(tf.string, shape=[None]) inputs = { 'key': keys_placeholder, 'image_bytes': tensors.input_jpeg } # To extract the id, we need to add the identity function. keys = tf.identity(keys_placeholder) labels = self.labels + ['UNKNOWN'] labels_tensor = tf.constant(labels) labels_table = tf.contrib.lookup.index_to_string_table_from_tensor(mapping=labels_tensor) predicted_label = labels_table.lookup(tensors.predictions[0]) # Need to duplicate the labels by num_of_instances so the output is one batch # (all output members share the same outer dimension). # The labels are needed for client to match class scores list. labels_tensor = tf.expand_dims(tf.constant(labels), 0) num_instance = tf.shape(keys) labels_tensors_n = tf.tile(labels_tensor, tf.concat(axis=0, values=[num_instance, [1]])) outputs = { 'key': keys, 'prediction': predicted_label, 'labels': labels_tensors_n, 'scores': tensors.predictions[1], } return inputs, outputs
python
def build_prediction_graph(self): """Builds prediction graph and registers appropriate endpoints.""" tensors = self.build_graph(None, 1, GraphMod.PREDICT) keys_placeholder = tf.placeholder(tf.string, shape=[None]) inputs = { 'key': keys_placeholder, 'image_bytes': tensors.input_jpeg } # To extract the id, we need to add the identity function. keys = tf.identity(keys_placeholder) labels = self.labels + ['UNKNOWN'] labels_tensor = tf.constant(labels) labels_table = tf.contrib.lookup.index_to_string_table_from_tensor(mapping=labels_tensor) predicted_label = labels_table.lookup(tensors.predictions[0]) # Need to duplicate the labels by num_of_instances so the output is one batch # (all output members share the same outer dimension). # The labels are needed for client to match class scores list. labels_tensor = tf.expand_dims(tf.constant(labels), 0) num_instance = tf.shape(keys) labels_tensors_n = tf.tile(labels_tensor, tf.concat(axis=0, values=[num_instance, [1]])) outputs = { 'key': keys, 'prediction': predicted_label, 'labels': labels_tensors_n, 'scores': tensors.predictions[1], } return inputs, outputs
[ "def", "build_prediction_graph", "(", "self", ")", ":", "tensors", "=", "self", ".", "build_graph", "(", "None", ",", "1", ",", "GraphMod", ".", "PREDICT", ")", "keys_placeholder", "=", "tf", ".", "placeholder", "(", "tf", ".", "string", ",", "shape", "=", "[", "None", "]", ")", "inputs", "=", "{", "'key'", ":", "keys_placeholder", ",", "'image_bytes'", ":", "tensors", ".", "input_jpeg", "}", "# To extract the id, we need to add the identity function.", "keys", "=", "tf", ".", "identity", "(", "keys_placeholder", ")", "labels", "=", "self", ".", "labels", "+", "[", "'UNKNOWN'", "]", "labels_tensor", "=", "tf", ".", "constant", "(", "labels", ")", "labels_table", "=", "tf", ".", "contrib", ".", "lookup", ".", "index_to_string_table_from_tensor", "(", "mapping", "=", "labels_tensor", ")", "predicted_label", "=", "labels_table", ".", "lookup", "(", "tensors", ".", "predictions", "[", "0", "]", ")", "# Need to duplicate the labels by num_of_instances so the output is one batch", "# (all output members share the same outer dimension).", "# The labels are needed for client to match class scores list.", "labels_tensor", "=", "tf", ".", "expand_dims", "(", "tf", ".", "constant", "(", "labels", ")", ",", "0", ")", "num_instance", "=", "tf", ".", "shape", "(", "keys", ")", "labels_tensors_n", "=", "tf", ".", "tile", "(", "labels_tensor", ",", "tf", ".", "concat", "(", "axis", "=", "0", ",", "values", "=", "[", "num_instance", ",", "[", "1", "]", "]", ")", ")", "outputs", "=", "{", "'key'", ":", "keys", ",", "'prediction'", ":", "predicted_label", ",", "'labels'", ":", "labels_tensors_n", ",", "'scores'", ":", "tensors", ".", "predictions", "[", "1", "]", ",", "}", "return", "inputs", ",", "outputs" ]
Builds prediction graph and registers appropriate endpoints.
[ "Builds", "prediction", "graph", "and", "registers", "appropriate", "endpoints", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_model.py#L286-L317
train
237,919
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_model.py
Model.export
def export(self, last_checkpoint, output_dir): """Builds a prediction graph and xports the model. Args: last_checkpoint: Path to the latest checkpoint file from training. output_dir: Path to the folder to be used to output the model. """ logging.info('Exporting prediction graph to %s', output_dir) with tf.Session(graph=tf.Graph()) as sess: # Build and save prediction meta graph and trained variable values. inputs, outputs = self.build_prediction_graph() signature_def_map = { 'serving_default': signature_def_utils.predict_signature_def(inputs, outputs) } init_op = tf.global_variables_initializer() sess.run(init_op) self.restore_from_checkpoint(sess, self.inception_checkpoint_file, last_checkpoint) init_op_serving = control_flow_ops.group( variables.local_variables_initializer(), tf.tables_initializer()) builder = saved_model_builder.SavedModelBuilder(output_dir) builder.add_meta_graph_and_variables( sess, [tag_constants.SERVING], signature_def_map=signature_def_map, legacy_init_op=init_op_serving) builder.save(False)
python
def export(self, last_checkpoint, output_dir): """Builds a prediction graph and xports the model. Args: last_checkpoint: Path to the latest checkpoint file from training. output_dir: Path to the folder to be used to output the model. """ logging.info('Exporting prediction graph to %s', output_dir) with tf.Session(graph=tf.Graph()) as sess: # Build and save prediction meta graph and trained variable values. inputs, outputs = self.build_prediction_graph() signature_def_map = { 'serving_default': signature_def_utils.predict_signature_def(inputs, outputs) } init_op = tf.global_variables_initializer() sess.run(init_op) self.restore_from_checkpoint(sess, self.inception_checkpoint_file, last_checkpoint) init_op_serving = control_flow_ops.group( variables.local_variables_initializer(), tf.tables_initializer()) builder = saved_model_builder.SavedModelBuilder(output_dir) builder.add_meta_graph_and_variables( sess, [tag_constants.SERVING], signature_def_map=signature_def_map, legacy_init_op=init_op_serving) builder.save(False)
[ "def", "export", "(", "self", ",", "last_checkpoint", ",", "output_dir", ")", ":", "logging", ".", "info", "(", "'Exporting prediction graph to %s'", ",", "output_dir", ")", "with", "tf", ".", "Session", "(", "graph", "=", "tf", ".", "Graph", "(", ")", ")", "as", "sess", ":", "# Build and save prediction meta graph and trained variable values.", "inputs", ",", "outputs", "=", "self", ".", "build_prediction_graph", "(", ")", "signature_def_map", "=", "{", "'serving_default'", ":", "signature_def_utils", ".", "predict_signature_def", "(", "inputs", ",", "outputs", ")", "}", "init_op", "=", "tf", ".", "global_variables_initializer", "(", ")", "sess", ".", "run", "(", "init_op", ")", "self", ".", "restore_from_checkpoint", "(", "sess", ",", "self", ".", "inception_checkpoint_file", ",", "last_checkpoint", ")", "init_op_serving", "=", "control_flow_ops", ".", "group", "(", "variables", ".", "local_variables_initializer", "(", ")", ",", "tf", ".", "tables_initializer", "(", ")", ")", "builder", "=", "saved_model_builder", ".", "SavedModelBuilder", "(", "output_dir", ")", "builder", ".", "add_meta_graph_and_variables", "(", "sess", ",", "[", "tag_constants", ".", "SERVING", "]", ",", "signature_def_map", "=", "signature_def_map", ",", "legacy_init_op", "=", "init_op_serving", ")", "builder", ".", "save", "(", "False", ")" ]
Builds a prediction graph and xports the model. Args: last_checkpoint: Path to the latest checkpoint file from training. output_dir: Path to the folder to be used to output the model.
[ "Builds", "a", "prediction", "graph", "and", "xports", "the", "model", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_model.py#L319-L346
train
237,920
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_model.py
Model.format_metric_values
def format_metric_values(self, metric_values): """Formats metric values - used for logging purpose.""" # Early in training, metric_values may actually be None. loss_str = 'N/A' accuracy_str = 'N/A' try: loss_str = 'loss: %.3f' % metric_values[0] accuracy_str = 'accuracy: %.3f' % metric_values[1] except (TypeError, IndexError): pass return '%s, %s' % (loss_str, accuracy_str)
python
def format_metric_values(self, metric_values): """Formats metric values - used for logging purpose.""" # Early in training, metric_values may actually be None. loss_str = 'N/A' accuracy_str = 'N/A' try: loss_str = 'loss: %.3f' % metric_values[0] accuracy_str = 'accuracy: %.3f' % metric_values[1] except (TypeError, IndexError): pass return '%s, %s' % (loss_str, accuracy_str)
[ "def", "format_metric_values", "(", "self", ",", "metric_values", ")", ":", "# Early in training, metric_values may actually be None.", "loss_str", "=", "'N/A'", "accuracy_str", "=", "'N/A'", "try", ":", "loss_str", "=", "'loss: %.3f'", "%", "metric_values", "[", "0", "]", "accuracy_str", "=", "'accuracy: %.3f'", "%", "metric_values", "[", "1", "]", "except", "(", "TypeError", ",", "IndexError", ")", ":", "pass", "return", "'%s, %s'", "%", "(", "loss_str", ",", "accuracy_str", ")" ]
Formats metric values - used for logging purpose.
[ "Formats", "metric", "values", "-", "used", "for", "logging", "purpose", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_model.py#L348-L360
train
237,921
googledatalab/pydatalab
google/datalab/ml/_util.py
package_and_copy
def package_and_copy(package_root_dir, setup_py, output_tar_path): """Repackage an CloudML package and copy it to a staging dir. Args: package_root_dir: the root dir to install package from. Usually you can get the path from inside your module using a relative path to __file__. setup_py: the path to setup.py. output_tar_path: the GCS path of the output tarball package. Raises: ValueError if output_tar_path is not a GCS path, or setup_py does not exist. """ if not output_tar_path.startswith('gs://'): raise ValueError('output_tar_path needs to be a GCS path.') if not os.path.isfile(setup_py): raise ValueError('Supplied file "%s" does not exist.' % setup_py) dest_setup_py = os.path.join(package_root_dir, 'setup.py') if dest_setup_py != setup_py: # setuptools requires a "setup.py" in the current dir, so copy setup.py there. # Also check if there is an existing setup.py. If so, back it up. if os.path.isfile(dest_setup_py): os.rename(dest_setup_py, dest_setup_py + '._bak_') shutil.copyfile(setup_py, dest_setup_py) tempdir = tempfile.mkdtemp() previous_cwd = os.getcwd() os.chdir(package_root_dir) try: # Repackage. sdist = ['python', dest_setup_py, 'sdist', '--format=gztar', '-d', tempdir] subprocess.check_call(sdist) # Copy to GCS. source = os.path.join(tempdir, '*.tar.gz') gscopy = ['gsutil', 'cp', source, output_tar_path] subprocess.check_call(gscopy) return finally: os.chdir(previous_cwd) if dest_setup_py != setup_py: os.remove(dest_setup_py) if os.path.isfile(dest_setup_py + '._bak_'): os.rename(dest_setup_py + '._bak_', dest_setup_py) shutil.rmtree(tempdir)
python
def package_and_copy(package_root_dir, setup_py, output_tar_path): """Repackage an CloudML package and copy it to a staging dir. Args: package_root_dir: the root dir to install package from. Usually you can get the path from inside your module using a relative path to __file__. setup_py: the path to setup.py. output_tar_path: the GCS path of the output tarball package. Raises: ValueError if output_tar_path is not a GCS path, or setup_py does not exist. """ if not output_tar_path.startswith('gs://'): raise ValueError('output_tar_path needs to be a GCS path.') if not os.path.isfile(setup_py): raise ValueError('Supplied file "%s" does not exist.' % setup_py) dest_setup_py = os.path.join(package_root_dir, 'setup.py') if dest_setup_py != setup_py: # setuptools requires a "setup.py" in the current dir, so copy setup.py there. # Also check if there is an existing setup.py. If so, back it up. if os.path.isfile(dest_setup_py): os.rename(dest_setup_py, dest_setup_py + '._bak_') shutil.copyfile(setup_py, dest_setup_py) tempdir = tempfile.mkdtemp() previous_cwd = os.getcwd() os.chdir(package_root_dir) try: # Repackage. sdist = ['python', dest_setup_py, 'sdist', '--format=gztar', '-d', tempdir] subprocess.check_call(sdist) # Copy to GCS. source = os.path.join(tempdir, '*.tar.gz') gscopy = ['gsutil', 'cp', source, output_tar_path] subprocess.check_call(gscopy) return finally: os.chdir(previous_cwd) if dest_setup_py != setup_py: os.remove(dest_setup_py) if os.path.isfile(dest_setup_py + '._bak_'): os.rename(dest_setup_py + '._bak_', dest_setup_py) shutil.rmtree(tempdir)
[ "def", "package_and_copy", "(", "package_root_dir", ",", "setup_py", ",", "output_tar_path", ")", ":", "if", "not", "output_tar_path", ".", "startswith", "(", "'gs://'", ")", ":", "raise", "ValueError", "(", "'output_tar_path needs to be a GCS path.'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "setup_py", ")", ":", "raise", "ValueError", "(", "'Supplied file \"%s\" does not exist.'", "%", "setup_py", ")", "dest_setup_py", "=", "os", ".", "path", ".", "join", "(", "package_root_dir", ",", "'setup.py'", ")", "if", "dest_setup_py", "!=", "setup_py", ":", "# setuptools requires a \"setup.py\" in the current dir, so copy setup.py there.", "# Also check if there is an existing setup.py. If so, back it up.", "if", "os", ".", "path", ".", "isfile", "(", "dest_setup_py", ")", ":", "os", ".", "rename", "(", "dest_setup_py", ",", "dest_setup_py", "+", "'._bak_'", ")", "shutil", ".", "copyfile", "(", "setup_py", ",", "dest_setup_py", ")", "tempdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "previous_cwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "package_root_dir", ")", "try", ":", "# Repackage.", "sdist", "=", "[", "'python'", ",", "dest_setup_py", ",", "'sdist'", ",", "'--format=gztar'", ",", "'-d'", ",", "tempdir", "]", "subprocess", ".", "check_call", "(", "sdist", ")", "# Copy to GCS.", "source", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "'*.tar.gz'", ")", "gscopy", "=", "[", "'gsutil'", ",", "'cp'", ",", "source", ",", "output_tar_path", "]", "subprocess", ".", "check_call", "(", "gscopy", ")", "return", "finally", ":", "os", ".", "chdir", "(", "previous_cwd", ")", "if", "dest_setup_py", "!=", "setup_py", ":", "os", ".", "remove", "(", "dest_setup_py", ")", "if", "os", ".", "path", ".", "isfile", "(", "dest_setup_py", "+", "'._bak_'", ")", ":", "os", ".", "rename", "(", "dest_setup_py", "+", "'._bak_'", ",", "dest_setup_py", ")", "shutil", ".", "rmtree", "(", "tempdir", ")" ]
Repackage an CloudML package and copy it to a staging dir. Args: package_root_dir: the root dir to install package from. Usually you can get the path from inside your module using a relative path to __file__. setup_py: the path to setup.py. output_tar_path: the GCS path of the output tarball package. Raises: ValueError if output_tar_path is not a GCS path, or setup_py does not exist.
[ "Repackage", "an", "CloudML", "package", "and", "copy", "it", "to", "a", "staging", "dir", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_util.py#L45-L88
train
237,922
googledatalab/pydatalab
google/datalab/ml/_util.py
read_file_to_string
def read_file_to_string(path): """Read a file into a string.""" bytes_string = tf.gfile.Open(path, 'r').read() return dlutils.python_portable_string(bytes_string)
python
def read_file_to_string(path): """Read a file into a string.""" bytes_string = tf.gfile.Open(path, 'r').read() return dlutils.python_portable_string(bytes_string)
[ "def", "read_file_to_string", "(", "path", ")", ":", "bytes_string", "=", "tf", ".", "gfile", ".", "Open", "(", "path", ",", "'r'", ")", ".", "read", "(", ")", "return", "dlutils", ".", "python_portable_string", "(", "bytes_string", ")" ]
Read a file into a string.
[ "Read", "a", "file", "into", "a", "string", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_util.py#L91-L94
train
237,923
googledatalab/pydatalab
datalab/data/commands/_sql.py
_date
def _date(val, offset=None): """ A special pseudo-type for pipeline arguments. This allows us to parse dates as Python datetimes, including special values like 'now' and 'today', as well as apply offsets to the datetime. Args: val: a string containing the value for the datetime. This can be 'now', 'today' (midnight at start of day), 'yesterday' (midnight at start of yesterday), or a formatted date that will be passed to the datetime constructor. Note that 'now' etc are assumed to be in UTC. offset: for date arguments a string containing a comma-separated list of relative offsets to apply of the form <n><u> where <n> is an integer and <u> is a single character unit (d=day, m=month, y=year, h=hour, m=minute). Returns: A Python datetime resulting from starting at <val> and applying the sequence of deltas specified in <offset>. """ if val is None: return val if val == '' or val == 'now': when = datetime.datetime.utcnow() elif val == 'today': dt = datetime.datetime.utcnow() when = datetime.datetime(dt.year, dt.month, dt.day) elif val == 'yesterday': dt = datetime.datetime.utcnow() - datetime.timedelta(1) when = datetime.datetime(dt.year, dt.month, dt.day) else: when = datetime.datetime.strptime(val, "%Y%m%d") if offset is not None: for part in offset.split(','): unit = part[-1] quantity = int(part[:-1]) # We can use timedelta for days and under, but not for years and months if unit == 'y': when = datetime.datetime(year=when.year + quantity, month=when.month, day=when.day, hour=when.hour, minute=when.minute) elif unit == 'm': new_year = when.year new_month = when.month + quantity if new_month < 1: new_month = -new_month new_year += 1 + (new_month // 12) new_month = 12 - new_month % 12 elif new_month > 12: new_year += (new_month - 1) // 12 new_month = 1 + (new_month - 1) % 12 when = datetime.datetime(year=new_year, month=new_month, day=when.day, hour=when.hour, minute=when.minute) elif unit == 'd': when += datetime.timedelta(days=quantity) elif unit == 'h': when += datetime.timedelta(hours=quantity) elif unit == 'M': when += datetime.timedelta(minutes=quantity) return when
python
def _date(val, offset=None): """ A special pseudo-type for pipeline arguments. This allows us to parse dates as Python datetimes, including special values like 'now' and 'today', as well as apply offsets to the datetime. Args: val: a string containing the value for the datetime. This can be 'now', 'today' (midnight at start of day), 'yesterday' (midnight at start of yesterday), or a formatted date that will be passed to the datetime constructor. Note that 'now' etc are assumed to be in UTC. offset: for date arguments a string containing a comma-separated list of relative offsets to apply of the form <n><u> where <n> is an integer and <u> is a single character unit (d=day, m=month, y=year, h=hour, m=minute). Returns: A Python datetime resulting from starting at <val> and applying the sequence of deltas specified in <offset>. """ if val is None: return val if val == '' or val == 'now': when = datetime.datetime.utcnow() elif val == 'today': dt = datetime.datetime.utcnow() when = datetime.datetime(dt.year, dt.month, dt.day) elif val == 'yesterday': dt = datetime.datetime.utcnow() - datetime.timedelta(1) when = datetime.datetime(dt.year, dt.month, dt.day) else: when = datetime.datetime.strptime(val, "%Y%m%d") if offset is not None: for part in offset.split(','): unit = part[-1] quantity = int(part[:-1]) # We can use timedelta for days and under, but not for years and months if unit == 'y': when = datetime.datetime(year=when.year + quantity, month=when.month, day=when.day, hour=when.hour, minute=when.minute) elif unit == 'm': new_year = when.year new_month = when.month + quantity if new_month < 1: new_month = -new_month new_year += 1 + (new_month // 12) new_month = 12 - new_month % 12 elif new_month > 12: new_year += (new_month - 1) // 12 new_month = 1 + (new_month - 1) % 12 when = datetime.datetime(year=new_year, month=new_month, day=when.day, hour=when.hour, minute=when.minute) elif unit == 'd': when += datetime.timedelta(days=quantity) elif unit == 'h': when += datetime.timedelta(hours=quantity) elif unit == 'M': when += datetime.timedelta(minutes=quantity) return when
[ "def", "_date", "(", "val", ",", "offset", "=", "None", ")", ":", "if", "val", "is", "None", ":", "return", "val", "if", "val", "==", "''", "or", "val", "==", "'now'", ":", "when", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "elif", "val", "==", "'today'", ":", "dt", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "when", "=", "datetime", ".", "datetime", "(", "dt", ".", "year", ",", "dt", ".", "month", ",", "dt", ".", "day", ")", "elif", "val", "==", "'yesterday'", ":", "dt", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "datetime", ".", "timedelta", "(", "1", ")", "when", "=", "datetime", ".", "datetime", "(", "dt", ".", "year", ",", "dt", ".", "month", ",", "dt", ".", "day", ")", "else", ":", "when", "=", "datetime", ".", "datetime", ".", "strptime", "(", "val", ",", "\"%Y%m%d\"", ")", "if", "offset", "is", "not", "None", ":", "for", "part", "in", "offset", ".", "split", "(", "','", ")", ":", "unit", "=", "part", "[", "-", "1", "]", "quantity", "=", "int", "(", "part", "[", ":", "-", "1", "]", ")", "# We can use timedelta for days and under, but not for years and months", "if", "unit", "==", "'y'", ":", "when", "=", "datetime", ".", "datetime", "(", "year", "=", "when", ".", "year", "+", "quantity", ",", "month", "=", "when", ".", "month", ",", "day", "=", "when", ".", "day", ",", "hour", "=", "when", ".", "hour", ",", "minute", "=", "when", ".", "minute", ")", "elif", "unit", "==", "'m'", ":", "new_year", "=", "when", ".", "year", "new_month", "=", "when", ".", "month", "+", "quantity", "if", "new_month", "<", "1", ":", "new_month", "=", "-", "new_month", "new_year", "+=", "1", "+", "(", "new_month", "//", "12", ")", "new_month", "=", "12", "-", "new_month", "%", "12", "elif", "new_month", ">", "12", ":", "new_year", "+=", "(", "new_month", "-", "1", ")", "//", "12", "new_month", "=", "1", "+", "(", "new_month", "-", "1", ")", "%", "12", "when", "=", "datetime", ".", "datetime", "(", "year", "=", "new_year", ",", "month", "=", "new_month", ",", "day", "=", "when", ".", "day", ",", "hour", "=", "when", ".", "hour", ",", "minute", "=", "when", ".", "minute", ")", "elif", "unit", "==", "'d'", ":", "when", "+=", "datetime", ".", "timedelta", "(", "days", "=", "quantity", ")", "elif", "unit", "==", "'h'", ":", "when", "+=", "datetime", ".", "timedelta", "(", "hours", "=", "quantity", ")", "elif", "unit", "==", "'M'", ":", "when", "+=", "datetime", ".", "timedelta", "(", "minutes", "=", "quantity", ")", "return", "when" ]
A special pseudo-type for pipeline arguments. This allows us to parse dates as Python datetimes, including special values like 'now' and 'today', as well as apply offsets to the datetime. Args: val: a string containing the value for the datetime. This can be 'now', 'today' (midnight at start of day), 'yesterday' (midnight at start of yesterday), or a formatted date that will be passed to the datetime constructor. Note that 'now' etc are assumed to be in UTC. offset: for date arguments a string containing a comma-separated list of relative offsets to apply of the form <n><u> where <n> is an integer and <u> is a single character unit (d=day, m=month, y=year, h=hour, m=minute). Returns: A Python datetime resulting from starting at <val> and applying the sequence of deltas specified in <offset>.
[ "A", "special", "pseudo", "-", "type", "for", "pipeline", "arguments", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L119-L177
train
237,924
googledatalab/pydatalab
datalab/data/commands/_sql.py
_make_string_formatter
def _make_string_formatter(f, offset=None): """ A closure-izer for string arguments that include a format and possibly an offset. """ format = f delta = offset return lambda v: time.strftime(format, (_date(v, delta)).timetuple())
python
def _make_string_formatter(f, offset=None): """ A closure-izer for string arguments that include a format and possibly an offset. """ format = f delta = offset return lambda v: time.strftime(format, (_date(v, delta)).timetuple())
[ "def", "_make_string_formatter", "(", "f", ",", "offset", "=", "None", ")", ":", "format", "=", "f", "delta", "=", "offset", "return", "lambda", "v", ":", "time", ".", "strftime", "(", "format", ",", "(", "_date", "(", "v", ",", "delta", ")", ")", ".", "timetuple", "(", ")", ")" ]
A closure-izer for string arguments that include a format and possibly an offset.
[ "A", "closure", "-", "izer", "for", "string", "arguments", "that", "include", "a", "format", "and", "possibly", "an", "offset", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L189-L193
train
237,925
googledatalab/pydatalab
datalab/data/commands/_sql.py
_make_table_formatter
def _make_table_formatter(f, offset=None): """ A closure-izer for table arguments that include a format and possibly an offset. """ format = f delta = offset return lambda v: _resolve_table(v, format, delta)
python
def _make_table_formatter(f, offset=None): """ A closure-izer for table arguments that include a format and possibly an offset. """ format = f delta = offset return lambda v: _resolve_table(v, format, delta)
[ "def", "_make_table_formatter", "(", "f", ",", "offset", "=", "None", ")", ":", "format", "=", "f", "delta", "=", "offset", "return", "lambda", "v", ":", "_resolve_table", "(", "v", ",", "format", ",", "delta", ")" ]
A closure-izer for table arguments that include a format and possibly an offset.
[ "A", "closure", "-", "izer", "for", "table", "arguments", "that", "include", "a", "format", "and", "possibly", "an", "offset", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L196-L200
train
237,926
googledatalab/pydatalab
datalab/data/commands/_sql.py
_arguments
def _arguments(code, module): """Define pipeline arguments. Args: code: the Python code to execute that defines the arguments. """ arg_parser = CommandParser.create('') try: # Define our special argument 'types' and add them to the environment. builtins = {'source': _table, 'datestring': _datestring} env = {} env.update(builtins) # Execute the cell which should be one or more calls to arg(). exec(code, env) # Iterate through the module dictionary. For any newly defined objects, # add args to the parser. for key in env: # Skip internal/private stuff. if key in builtins or key[0] == '_': continue # If we want to support importing query modules into other query modules, uncomment next 4 # Skip imports but add them to the module # if isinstance(env[key], types.ModuleType): # module.__dict__[key] = env[key] # continue val = env[key] key = '--%s' % key if isinstance(val, bool): if val: arg_parser.add_argument(key, default=val, action='store_true') else: arg_parser.add_argument(key, default=val, action='store_false') elif isinstance(val, basestring) or isinstance(val, int) or isinstance(val, float) \ or isinstance(val, int): arg_parser.add_argument(key, default=val) elif isinstance(val, list): arg_parser.add_argument(key, default=val, nargs='+') elif isinstance(val, tuple): arg_parser.add_argument(key, default=list(val), nargs='+') # Is this one of our pseudo-types for dates/tables? elif isinstance(val, dict) and 'type' in val: if val['type'] == 'datestring': arg_parser.add_argument(key, default='', type=_make_string_formatter(val['format'], offset=val['offset'])) elif val['type'] == 'table': if val['format'] is not None: arg_parser.add_argument(key, default='', type=_make_table_formatter(val['format'], offset=val['offset'])) else: arg_parser.add_argument(key, default=val['name'], type=_make_table) else: raise Exception('Cannot generate argument for %s of type %s' % (key, type(val))) else: raise Exception('Cannot generate argument for %s of type %s' % (key, type(val))) except Exception as e: print("%%sql arguments: %s from code '%s'" % (str(e), str(code))) return arg_parser
python
def _arguments(code, module): """Define pipeline arguments. Args: code: the Python code to execute that defines the arguments. """ arg_parser = CommandParser.create('') try: # Define our special argument 'types' and add them to the environment. builtins = {'source': _table, 'datestring': _datestring} env = {} env.update(builtins) # Execute the cell which should be one or more calls to arg(). exec(code, env) # Iterate through the module dictionary. For any newly defined objects, # add args to the parser. for key in env: # Skip internal/private stuff. if key in builtins or key[0] == '_': continue # If we want to support importing query modules into other query modules, uncomment next 4 # Skip imports but add them to the module # if isinstance(env[key], types.ModuleType): # module.__dict__[key] = env[key] # continue val = env[key] key = '--%s' % key if isinstance(val, bool): if val: arg_parser.add_argument(key, default=val, action='store_true') else: arg_parser.add_argument(key, default=val, action='store_false') elif isinstance(val, basestring) or isinstance(val, int) or isinstance(val, float) \ or isinstance(val, int): arg_parser.add_argument(key, default=val) elif isinstance(val, list): arg_parser.add_argument(key, default=val, nargs='+') elif isinstance(val, tuple): arg_parser.add_argument(key, default=list(val), nargs='+') # Is this one of our pseudo-types for dates/tables? elif isinstance(val, dict) and 'type' in val: if val['type'] == 'datestring': arg_parser.add_argument(key, default='', type=_make_string_formatter(val['format'], offset=val['offset'])) elif val['type'] == 'table': if val['format'] is not None: arg_parser.add_argument(key, default='', type=_make_table_formatter(val['format'], offset=val['offset'])) else: arg_parser.add_argument(key, default=val['name'], type=_make_table) else: raise Exception('Cannot generate argument for %s of type %s' % (key, type(val))) else: raise Exception('Cannot generate argument for %s of type %s' % (key, type(val))) except Exception as e: print("%%sql arguments: %s from code '%s'" % (str(e), str(code))) return arg_parser
[ "def", "_arguments", "(", "code", ",", "module", ")", ":", "arg_parser", "=", "CommandParser", ".", "create", "(", "''", ")", "try", ":", "# Define our special argument 'types' and add them to the environment.", "builtins", "=", "{", "'source'", ":", "_table", ",", "'datestring'", ":", "_datestring", "}", "env", "=", "{", "}", "env", ".", "update", "(", "builtins", ")", "# Execute the cell which should be one or more calls to arg().", "exec", "(", "code", ",", "env", ")", "# Iterate through the module dictionary. For any newly defined objects,", "# add args to the parser.", "for", "key", "in", "env", ":", "# Skip internal/private stuff.", "if", "key", "in", "builtins", "or", "key", "[", "0", "]", "==", "'_'", ":", "continue", "# If we want to support importing query modules into other query modules, uncomment next 4", "# Skip imports but add them to the module", "# if isinstance(env[key], types.ModuleType):", "# module.__dict__[key] = env[key]", "# continue", "val", "=", "env", "[", "key", "]", "key", "=", "'--%s'", "%", "key", "if", "isinstance", "(", "val", ",", "bool", ")", ":", "if", "val", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "val", ",", "action", "=", "'store_true'", ")", "else", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "val", ",", "action", "=", "'store_false'", ")", "elif", "isinstance", "(", "val", ",", "basestring", ")", "or", "isinstance", "(", "val", ",", "int", ")", "or", "isinstance", "(", "val", ",", "float", ")", "or", "isinstance", "(", "val", ",", "int", ")", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "val", ")", "elif", "isinstance", "(", "val", ",", "list", ")", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "val", ",", "nargs", "=", "'+'", ")", "elif", "isinstance", "(", "val", ",", "tuple", ")", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "list", "(", "val", ")", ",", "nargs", "=", "'+'", ")", "# Is this one of our pseudo-types for dates/tables?", "elif", "isinstance", "(", "val", ",", "dict", ")", "and", "'type'", "in", "val", ":", "if", "val", "[", "'type'", "]", "==", "'datestring'", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "''", ",", "type", "=", "_make_string_formatter", "(", "val", "[", "'format'", "]", ",", "offset", "=", "val", "[", "'offset'", "]", ")", ")", "elif", "val", "[", "'type'", "]", "==", "'table'", ":", "if", "val", "[", "'format'", "]", "is", "not", "None", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "''", ",", "type", "=", "_make_table_formatter", "(", "val", "[", "'format'", "]", ",", "offset", "=", "val", "[", "'offset'", "]", ")", ")", "else", ":", "arg_parser", ".", "add_argument", "(", "key", ",", "default", "=", "val", "[", "'name'", "]", ",", "type", "=", "_make_table", ")", "else", ":", "raise", "Exception", "(", "'Cannot generate argument for %s of type %s'", "%", "(", "key", ",", "type", "(", "val", ")", ")", ")", "else", ":", "raise", "Exception", "(", "'Cannot generate argument for %s of type %s'", "%", "(", "key", ",", "type", "(", "val", ")", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"%%sql arguments: %s from code '%s'\"", "%", "(", "str", "(", "e", ")", ",", "str", "(", "code", ")", ")", ")", "return", "arg_parser" ]
Define pipeline arguments. Args: code: the Python code to execute that defines the arguments.
[ "Define", "pipeline", "arguments", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L215-L281
train
237,927
googledatalab/pydatalab
datalab/data/commands/_sql.py
_split_cell
def _split_cell(cell, module): """ Split a hybrid %%sql cell into the Python code and the queries. Populates a module with the queries. Args: cell: the contents of the %%sql cell. module: the module that the contents will populate. Returns: The default (last) query for the module. """ lines = cell.split('\n') code = None last_def = -1 name = None define_wild_re = re.compile('^DEFINE\s+.*$', re.IGNORECASE) define_re = re.compile('^DEFINE\s+QUERY\s+([A-Z]\w*)\s*?(.*)$', re.IGNORECASE) select_re = re.compile('^SELECT\s*.*$', re.IGNORECASE) standard_sql_re = re.compile('^(CREATE|WITH|INSERT|DELETE|UPDATE)\s*.*$', re.IGNORECASE) # TODO(gram): a potential issue with this code is if we have leading Python code followed # by a SQL-style comment before we see SELECT/DEFINE. When switching to the tokenizer see # if we can address this. for i, line in enumerate(lines): define_match = define_re.match(line) select_match = select_re.match(line) standard_sql_match = standard_sql_re.match(line) if i: prior_content = ''.join(lines[:i]).strip() if select_match: # Avoid matching if previous token was '(' or if Standard SQL is found # TODO: handle the possibility of comments immediately preceding SELECT select_match = len(prior_content) == 0 or \ (prior_content[-1] != '(' and not standard_sql_re.match(prior_content)) if standard_sql_match: standard_sql_match = len(prior_content) == 0 or not standard_sql_re.match(prior_content) if define_match or select_match or standard_sql_match: # If this is the first query, get the preceding Python code. if code is None: code = ('\n'.join(lines[:i])).strip() if len(code): code += '\n' elif last_def >= 0: # This is not the first query, so gather the previous query text. query = '\n'.join([line for line in lines[last_def:i] if len(line)]).strip() if select_match and name != datalab.data._utils._SQL_MODULE_MAIN and len(query) == 0: # Avoid DEFINE query name\nSELECT ... being seen as an empty DEFINE followed by SELECT continue # Save the query statement = datalab.data.SqlStatement(query, module) module.__dict__[name] = statement # And set the 'last' query to be this too module.__dict__[datalab.data._utils._SQL_MODULE_LAST] = statement # Get the query name and strip off our syntactic sugar if appropriate. if define_match: name = define_match.group(1) lines[i] = define_match.group(2) else: name = datalab.data._utils._SQL_MODULE_MAIN # Save the starting line index of the new query last_def = i else: define_wild_match = define_wild_re.match(line) if define_wild_match: raise Exception('Expected "DEFINE QUERY <name>"') if last_def >= 0: # We were in a query so save this tail query. query = '\n'.join([line for line in lines[last_def:] if len(line)]).strip() statement = datalab.data.SqlStatement(query, module) module.__dict__[name] = statement module.__dict__[datalab.data._utils._SQL_MODULE_LAST] = statement if code is None: code = '' module.__dict__[datalab.data._utils._SQL_MODULE_ARGPARSE] = _arguments(code, module) return module.__dict__.get(datalab.data._utils._SQL_MODULE_LAST, None)
python
def _split_cell(cell, module): """ Split a hybrid %%sql cell into the Python code and the queries. Populates a module with the queries. Args: cell: the contents of the %%sql cell. module: the module that the contents will populate. Returns: The default (last) query for the module. """ lines = cell.split('\n') code = None last_def = -1 name = None define_wild_re = re.compile('^DEFINE\s+.*$', re.IGNORECASE) define_re = re.compile('^DEFINE\s+QUERY\s+([A-Z]\w*)\s*?(.*)$', re.IGNORECASE) select_re = re.compile('^SELECT\s*.*$', re.IGNORECASE) standard_sql_re = re.compile('^(CREATE|WITH|INSERT|DELETE|UPDATE)\s*.*$', re.IGNORECASE) # TODO(gram): a potential issue with this code is if we have leading Python code followed # by a SQL-style comment before we see SELECT/DEFINE. When switching to the tokenizer see # if we can address this. for i, line in enumerate(lines): define_match = define_re.match(line) select_match = select_re.match(line) standard_sql_match = standard_sql_re.match(line) if i: prior_content = ''.join(lines[:i]).strip() if select_match: # Avoid matching if previous token was '(' or if Standard SQL is found # TODO: handle the possibility of comments immediately preceding SELECT select_match = len(prior_content) == 0 or \ (prior_content[-1] != '(' and not standard_sql_re.match(prior_content)) if standard_sql_match: standard_sql_match = len(prior_content) == 0 or not standard_sql_re.match(prior_content) if define_match or select_match or standard_sql_match: # If this is the first query, get the preceding Python code. if code is None: code = ('\n'.join(lines[:i])).strip() if len(code): code += '\n' elif last_def >= 0: # This is not the first query, so gather the previous query text. query = '\n'.join([line for line in lines[last_def:i] if len(line)]).strip() if select_match and name != datalab.data._utils._SQL_MODULE_MAIN and len(query) == 0: # Avoid DEFINE query name\nSELECT ... being seen as an empty DEFINE followed by SELECT continue # Save the query statement = datalab.data.SqlStatement(query, module) module.__dict__[name] = statement # And set the 'last' query to be this too module.__dict__[datalab.data._utils._SQL_MODULE_LAST] = statement # Get the query name and strip off our syntactic sugar if appropriate. if define_match: name = define_match.group(1) lines[i] = define_match.group(2) else: name = datalab.data._utils._SQL_MODULE_MAIN # Save the starting line index of the new query last_def = i else: define_wild_match = define_wild_re.match(line) if define_wild_match: raise Exception('Expected "DEFINE QUERY <name>"') if last_def >= 0: # We were in a query so save this tail query. query = '\n'.join([line for line in lines[last_def:] if len(line)]).strip() statement = datalab.data.SqlStatement(query, module) module.__dict__[name] = statement module.__dict__[datalab.data._utils._SQL_MODULE_LAST] = statement if code is None: code = '' module.__dict__[datalab.data._utils._SQL_MODULE_ARGPARSE] = _arguments(code, module) return module.__dict__.get(datalab.data._utils._SQL_MODULE_LAST, None)
[ "def", "_split_cell", "(", "cell", ",", "module", ")", ":", "lines", "=", "cell", ".", "split", "(", "'\\n'", ")", "code", "=", "None", "last_def", "=", "-", "1", "name", "=", "None", "define_wild_re", "=", "re", ".", "compile", "(", "'^DEFINE\\s+.*$'", ",", "re", ".", "IGNORECASE", ")", "define_re", "=", "re", ".", "compile", "(", "'^DEFINE\\s+QUERY\\s+([A-Z]\\w*)\\s*?(.*)$'", ",", "re", ".", "IGNORECASE", ")", "select_re", "=", "re", ".", "compile", "(", "'^SELECT\\s*.*$'", ",", "re", ".", "IGNORECASE", ")", "standard_sql_re", "=", "re", ".", "compile", "(", "'^(CREATE|WITH|INSERT|DELETE|UPDATE)\\s*.*$'", ",", "re", ".", "IGNORECASE", ")", "# TODO(gram): a potential issue with this code is if we have leading Python code followed", "# by a SQL-style comment before we see SELECT/DEFINE. When switching to the tokenizer see", "# if we can address this.", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "define_match", "=", "define_re", ".", "match", "(", "line", ")", "select_match", "=", "select_re", ".", "match", "(", "line", ")", "standard_sql_match", "=", "standard_sql_re", ".", "match", "(", "line", ")", "if", "i", ":", "prior_content", "=", "''", ".", "join", "(", "lines", "[", ":", "i", "]", ")", ".", "strip", "(", ")", "if", "select_match", ":", "# Avoid matching if previous token was '(' or if Standard SQL is found", "# TODO: handle the possibility of comments immediately preceding SELECT", "select_match", "=", "len", "(", "prior_content", ")", "==", "0", "or", "(", "prior_content", "[", "-", "1", "]", "!=", "'('", "and", "not", "standard_sql_re", ".", "match", "(", "prior_content", ")", ")", "if", "standard_sql_match", ":", "standard_sql_match", "=", "len", "(", "prior_content", ")", "==", "0", "or", "not", "standard_sql_re", ".", "match", "(", "prior_content", ")", "if", "define_match", "or", "select_match", "or", "standard_sql_match", ":", "# If this is the first query, get the preceding Python code.", "if", "code", "is", "None", ":", "code", "=", "(", "'\\n'", ".", "join", "(", "lines", "[", ":", "i", "]", ")", ")", ".", "strip", "(", ")", "if", "len", "(", "code", ")", ":", "code", "+=", "'\\n'", "elif", "last_def", ">=", "0", ":", "# This is not the first query, so gather the previous query text.", "query", "=", "'\\n'", ".", "join", "(", "[", "line", "for", "line", "in", "lines", "[", "last_def", ":", "i", "]", "if", "len", "(", "line", ")", "]", ")", ".", "strip", "(", ")", "if", "select_match", "and", "name", "!=", "datalab", ".", "data", ".", "_utils", ".", "_SQL_MODULE_MAIN", "and", "len", "(", "query", ")", "==", "0", ":", "# Avoid DEFINE query name\\nSELECT ... being seen as an empty DEFINE followed by SELECT", "continue", "# Save the query", "statement", "=", "datalab", ".", "data", ".", "SqlStatement", "(", "query", ",", "module", ")", "module", ".", "__dict__", "[", "name", "]", "=", "statement", "# And set the 'last' query to be this too", "module", ".", "__dict__", "[", "datalab", ".", "data", ".", "_utils", ".", "_SQL_MODULE_LAST", "]", "=", "statement", "# Get the query name and strip off our syntactic sugar if appropriate.", "if", "define_match", ":", "name", "=", "define_match", ".", "group", "(", "1", ")", "lines", "[", "i", "]", "=", "define_match", ".", "group", "(", "2", ")", "else", ":", "name", "=", "datalab", ".", "data", ".", "_utils", ".", "_SQL_MODULE_MAIN", "# Save the starting line index of the new query", "last_def", "=", "i", "else", ":", "define_wild_match", "=", "define_wild_re", ".", "match", "(", "line", ")", "if", "define_wild_match", ":", "raise", "Exception", "(", "'Expected \"DEFINE QUERY <name>\"'", ")", "if", "last_def", ">=", "0", ":", "# We were in a query so save this tail query.", "query", "=", "'\\n'", ".", "join", "(", "[", "line", "for", "line", "in", "lines", "[", "last_def", ":", "]", "if", "len", "(", "line", ")", "]", ")", ".", "strip", "(", ")", "statement", "=", "datalab", ".", "data", ".", "SqlStatement", "(", "query", ",", "module", ")", "module", ".", "__dict__", "[", "name", "]", "=", "statement", "module", ".", "__dict__", "[", "datalab", ".", "data", ".", "_utils", ".", "_SQL_MODULE_LAST", "]", "=", "statement", "if", "code", "is", "None", ":", "code", "=", "''", "module", ".", "__dict__", "[", "datalab", ".", "data", ".", "_utils", ".", "_SQL_MODULE_ARGPARSE", "]", "=", "_arguments", "(", "code", ",", "module", ")", "return", "module", ".", "__dict__", ".", "get", "(", "datalab", ".", "data", ".", "_utils", ".", "_SQL_MODULE_LAST", ",", "None", ")" ]
Split a hybrid %%sql cell into the Python code and the queries. Populates a module with the queries. Args: cell: the contents of the %%sql cell. module: the module that the contents will populate. Returns: The default (last) query for the module.
[ "Split", "a", "hybrid", "%%sql", "cell", "into", "the", "Python", "code", "and", "the", "queries", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L284-L367
train
237,928
googledatalab/pydatalab
datalab/data/commands/_sql.py
sql_cell
def sql_cell(args, cell): """Implements the SQL cell magic for ipython notebooks. The supported syntax is: %%sql [--module <modulename>] [<optional Python code for default argument values>] [<optional named queries>] [<optional unnamed query>] At least one query should be present. Named queries should start with: DEFINE QUERY <name> on a line by itself. Args: args: the optional arguments following '%%sql'. cell: the contents of the cell; Python code for arguments followed by SQL queries. """ name = args['module'] if args['module'] else '_sql_cell' module = imp.new_module(name) query = _split_cell(cell, module) ipy = IPython.get_ipython() if not args['module']: # Execute now if query: return datalab.bigquery.Query(query, values=ipy.user_ns) \ .execute(dialect=args['dialect'], billing_tier=args['billing']).results else: # Add it as a module sys.modules[name] = module exec('import %s' % name, ipy.user_ns)
python
def sql_cell(args, cell): """Implements the SQL cell magic for ipython notebooks. The supported syntax is: %%sql [--module <modulename>] [<optional Python code for default argument values>] [<optional named queries>] [<optional unnamed query>] At least one query should be present. Named queries should start with: DEFINE QUERY <name> on a line by itself. Args: args: the optional arguments following '%%sql'. cell: the contents of the cell; Python code for arguments followed by SQL queries. """ name = args['module'] if args['module'] else '_sql_cell' module = imp.new_module(name) query = _split_cell(cell, module) ipy = IPython.get_ipython() if not args['module']: # Execute now if query: return datalab.bigquery.Query(query, values=ipy.user_ns) \ .execute(dialect=args['dialect'], billing_tier=args['billing']).results else: # Add it as a module sys.modules[name] = module exec('import %s' % name, ipy.user_ns)
[ "def", "sql_cell", "(", "args", ",", "cell", ")", ":", "name", "=", "args", "[", "'module'", "]", "if", "args", "[", "'module'", "]", "else", "'_sql_cell'", "module", "=", "imp", ".", "new_module", "(", "name", ")", "query", "=", "_split_cell", "(", "cell", ",", "module", ")", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "if", "not", "args", "[", "'module'", "]", ":", "# Execute now", "if", "query", ":", "return", "datalab", ".", "bigquery", ".", "Query", "(", "query", ",", "values", "=", "ipy", ".", "user_ns", ")", ".", "execute", "(", "dialect", "=", "args", "[", "'dialect'", "]", ",", "billing_tier", "=", "args", "[", "'billing'", "]", ")", ".", "results", "else", ":", "# Add it as a module", "sys", ".", "modules", "[", "name", "]", "=", "module", "exec", "(", "'import %s'", "%", "name", ",", "ipy", ".", "user_ns", ")" ]
Implements the SQL cell magic for ipython notebooks. The supported syntax is: %%sql [--module <modulename>] [<optional Python code for default argument values>] [<optional named queries>] [<optional unnamed query>] At least one query should be present. Named queries should start with: DEFINE QUERY <name> on a line by itself. Args: args: the optional arguments following '%%sql'. cell: the contents of the cell; Python code for arguments followed by SQL queries.
[ "Implements", "the", "SQL", "cell", "magic", "for", "ipython", "notebooks", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L370-L402
train
237,929
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/task.py
get_reader_input_fn
def get_reader_input_fn(train_config, preprocess_output_dir, model_type, data_paths, batch_size, shuffle, num_epochs=None): """Builds input layer for training.""" def get_input_features(): """Read the input features from the given data paths.""" _, examples = util.read_examples( input_files=data_paths, batch_size=batch_size, shuffle=shuffle, num_epochs=num_epochs) features = util.parse_example_tensor(examples=examples, train_config=train_config, keep_target=True) target_name = train_config['target_column'] target = features.pop(target_name) features, target = util.preprocess_input( features=features, target=target, train_config=train_config, preprocess_output_dir=preprocess_output_dir, model_type=model_type) return features, target # Return a function to input the feaures into the model from a data path. return get_input_features
python
def get_reader_input_fn(train_config, preprocess_output_dir, model_type, data_paths, batch_size, shuffle, num_epochs=None): """Builds input layer for training.""" def get_input_features(): """Read the input features from the given data paths.""" _, examples = util.read_examples( input_files=data_paths, batch_size=batch_size, shuffle=shuffle, num_epochs=num_epochs) features = util.parse_example_tensor(examples=examples, train_config=train_config, keep_target=True) target_name = train_config['target_column'] target = features.pop(target_name) features, target = util.preprocess_input( features=features, target=target, train_config=train_config, preprocess_output_dir=preprocess_output_dir, model_type=model_type) return features, target # Return a function to input the feaures into the model from a data path. return get_input_features
[ "def", "get_reader_input_fn", "(", "train_config", ",", "preprocess_output_dir", ",", "model_type", ",", "data_paths", ",", "batch_size", ",", "shuffle", ",", "num_epochs", "=", "None", ")", ":", "def", "get_input_features", "(", ")", ":", "\"\"\"Read the input features from the given data paths.\"\"\"", "_", ",", "examples", "=", "util", ".", "read_examples", "(", "input_files", "=", "data_paths", ",", "batch_size", "=", "batch_size", ",", "shuffle", "=", "shuffle", ",", "num_epochs", "=", "num_epochs", ")", "features", "=", "util", ".", "parse_example_tensor", "(", "examples", "=", "examples", ",", "train_config", "=", "train_config", ",", "keep_target", "=", "True", ")", "target_name", "=", "train_config", "[", "'target_column'", "]", "target", "=", "features", ".", "pop", "(", "target_name", ")", "features", ",", "target", "=", "util", ".", "preprocess_input", "(", "features", "=", "features", ",", "target", "=", "target", ",", "train_config", "=", "train_config", ",", "preprocess_output_dir", "=", "preprocess_output_dir", ",", "model_type", "=", "model_type", ")", "return", "features", ",", "target", "# Return a function to input the feaures into the model from a data path.", "return", "get_input_features" ]
Builds input layer for training.
[ "Builds", "input", "layer", "for", "training", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/task.py#L30-L57
train
237,930
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/task.py
main
def main(argv=None): """Run a Tensorflow model on the Iris dataset.""" args = parse_arguments(sys.argv if argv is None else argv) tf.logging.set_verbosity(tf.logging.INFO) learn_runner.run( experiment_fn=get_experiment_fn(args), output_dir=args.job_dir)
python
def main(argv=None): """Run a Tensorflow model on the Iris dataset.""" args = parse_arguments(sys.argv if argv is None else argv) tf.logging.set_verbosity(tf.logging.INFO) learn_runner.run( experiment_fn=get_experiment_fn(args), output_dir=args.job_dir)
[ "def", "main", "(", "argv", "=", "None", ")", ":", "args", "=", "parse_arguments", "(", "sys", ".", "argv", "if", "argv", "is", "None", "else", "argv", ")", "tf", ".", "logging", ".", "set_verbosity", "(", "tf", ".", "logging", ".", "INFO", ")", "learn_runner", ".", "run", "(", "experiment_fn", "=", "get_experiment_fn", "(", "args", ")", ",", "output_dir", "=", "args", ".", "job_dir", ")" ]
Run a Tensorflow model on the Iris dataset.
[ "Run", "a", "Tensorflow", "model", "on", "the", "Iris", "dataset", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/task.py#L231-L238
train
237,931
googledatalab/pydatalab
google/datalab/stackdriver/commands/_monitoring.py
sd
def sd(line, cell=None): """Implements the stackdriver cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser(prog='%sd', description=( 'Execute various Stackdriver related operations. Use "%sd ' '<stackdriver_product> -h" for help on a specific Stackdriver product.')) # %%sd monitoring _create_monitoring_subparser(parser) return google.datalab.utils.commands.handle_magic_line(line, cell, parser)
python
def sd(line, cell=None): """Implements the stackdriver cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser(prog='%sd', description=( 'Execute various Stackdriver related operations. Use "%sd ' '<stackdriver_product> -h" for help on a specific Stackdriver product.')) # %%sd monitoring _create_monitoring_subparser(parser) return google.datalab.utils.commands.handle_magic_line(line, cell, parser)
[ "def", "sd", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'%sd'", ",", "description", "=", "(", "'Execute various Stackdriver related operations. Use \"%sd '", "'<stackdriver_product> -h\" for help on a specific Stackdriver product.'", ")", ")", "# %%sd monitoring", "_create_monitoring_subparser", "(", "parser", ")", "return", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "handle_magic_line", "(", "line", ",", "cell", ",", "parser", ")" ]
Implements the stackdriver cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
[ "Implements", "the", "stackdriver", "cell", "magic", "for", "ipython", "notebooks", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/commands/_monitoring.py#L28-L42
train
237,932
googledatalab/pydatalab
solutionbox/ml_workbench/xgboost/trainer/task.py
make_prediction_output_tensors
def make_prediction_output_tensors(args, features, input_ops, model_fn_ops, keep_target): """Makes the final prediction output layer.""" target_name = feature_transforms.get_target_name(features) key_names = get_key_names(features) outputs = {} outputs.update({key_name: tf.squeeze(input_ops.features[key_name]) for key_name in key_names}) if is_classification_model(args.model): # build maps from ints to the origional categorical strings. class_names = read_vocab(args, target_name) table = tf.contrib.lookup.index_to_string_table_from_tensor( mapping=class_names, default_value='UNKNOWN') # Get the label of the input target. if keep_target: input_target_label = table.lookup(input_ops.features[target_name]) outputs[PG_TARGET] = tf.squeeze(input_target_label) # TODO(brandondutra): get the score of the target label too. probabilities = model_fn_ops.predictions['probabilities'] # if top_n == 0, this means use all the classes. We will use class names as # probabilities labels. if args.top_n == 0: predicted_index = tf.argmax(probabilities, axis=1) predicted = table.lookup(predicted_index) outputs.update({PG_CLASSIFICATION_FIRST_LABEL: predicted}) probabilities_list = tf.unstack(probabilities, axis=1) for class_name, p in zip(class_names, probabilities_list): outputs[class_name] = p else: top_n = args.top_n # get top k labels and their scores. (top_k_values, top_k_indices) = tf.nn.top_k(probabilities, k=top_n) top_k_labels = table.lookup(tf.to_int64(top_k_indices)) # Write the top_k values using 2*top_n columns. num_digits = int(math.ceil(math.log(top_n, 10))) if num_digits == 0: num_digits = 1 for i in range(0, top_n): # Pad i based on the size of k. So if k = 100, i = 23 -> i = '023'. This # makes sorting the columns easy. padded_i = str(i + 1).zfill(num_digits) if i == 0: label_alias = PG_CLASSIFICATION_FIRST_LABEL else: label_alias = PG_CLASSIFICATION_LABEL_TEMPLATE % padded_i label_tensor_name = (tf.squeeze( tf.slice(top_k_labels, [0, i], [tf.shape(top_k_labels)[0], 1]))) if i == 0: score_alias = PG_CLASSIFICATION_FIRST_SCORE else: score_alias = PG_CLASSIFICATION_SCORE_TEMPLATE % padded_i score_tensor_name = (tf.squeeze( tf.slice(top_k_values, [0, i], [tf.shape(top_k_values)[0], 1]))) outputs.update({label_alias: label_tensor_name, score_alias: score_tensor_name}) else: if keep_target: outputs[PG_TARGET] = tf.squeeze(input_ops.features[target_name]) scores = model_fn_ops.predictions['scores'] outputs[PG_REGRESSION_PREDICTED_TARGET] = tf.squeeze(scores) return outputs
python
def make_prediction_output_tensors(args, features, input_ops, model_fn_ops, keep_target): """Makes the final prediction output layer.""" target_name = feature_transforms.get_target_name(features) key_names = get_key_names(features) outputs = {} outputs.update({key_name: tf.squeeze(input_ops.features[key_name]) for key_name in key_names}) if is_classification_model(args.model): # build maps from ints to the origional categorical strings. class_names = read_vocab(args, target_name) table = tf.contrib.lookup.index_to_string_table_from_tensor( mapping=class_names, default_value='UNKNOWN') # Get the label of the input target. if keep_target: input_target_label = table.lookup(input_ops.features[target_name]) outputs[PG_TARGET] = tf.squeeze(input_target_label) # TODO(brandondutra): get the score of the target label too. probabilities = model_fn_ops.predictions['probabilities'] # if top_n == 0, this means use all the classes. We will use class names as # probabilities labels. if args.top_n == 0: predicted_index = tf.argmax(probabilities, axis=1) predicted = table.lookup(predicted_index) outputs.update({PG_CLASSIFICATION_FIRST_LABEL: predicted}) probabilities_list = tf.unstack(probabilities, axis=1) for class_name, p in zip(class_names, probabilities_list): outputs[class_name] = p else: top_n = args.top_n # get top k labels and their scores. (top_k_values, top_k_indices) = tf.nn.top_k(probabilities, k=top_n) top_k_labels = table.lookup(tf.to_int64(top_k_indices)) # Write the top_k values using 2*top_n columns. num_digits = int(math.ceil(math.log(top_n, 10))) if num_digits == 0: num_digits = 1 for i in range(0, top_n): # Pad i based on the size of k. So if k = 100, i = 23 -> i = '023'. This # makes sorting the columns easy. padded_i = str(i + 1).zfill(num_digits) if i == 0: label_alias = PG_CLASSIFICATION_FIRST_LABEL else: label_alias = PG_CLASSIFICATION_LABEL_TEMPLATE % padded_i label_tensor_name = (tf.squeeze( tf.slice(top_k_labels, [0, i], [tf.shape(top_k_labels)[0], 1]))) if i == 0: score_alias = PG_CLASSIFICATION_FIRST_SCORE else: score_alias = PG_CLASSIFICATION_SCORE_TEMPLATE % padded_i score_tensor_name = (tf.squeeze( tf.slice(top_k_values, [0, i], [tf.shape(top_k_values)[0], 1]))) outputs.update({label_alias: label_tensor_name, score_alias: score_tensor_name}) else: if keep_target: outputs[PG_TARGET] = tf.squeeze(input_ops.features[target_name]) scores = model_fn_ops.predictions['scores'] outputs[PG_REGRESSION_PREDICTED_TARGET] = tf.squeeze(scores) return outputs
[ "def", "make_prediction_output_tensors", "(", "args", ",", "features", ",", "input_ops", ",", "model_fn_ops", ",", "keep_target", ")", ":", "target_name", "=", "feature_transforms", ".", "get_target_name", "(", "features", ")", "key_names", "=", "get_key_names", "(", "features", ")", "outputs", "=", "{", "}", "outputs", ".", "update", "(", "{", "key_name", ":", "tf", ".", "squeeze", "(", "input_ops", ".", "features", "[", "key_name", "]", ")", "for", "key_name", "in", "key_names", "}", ")", "if", "is_classification_model", "(", "args", ".", "model", ")", ":", "# build maps from ints to the origional categorical strings.", "class_names", "=", "read_vocab", "(", "args", ",", "target_name", ")", "table", "=", "tf", ".", "contrib", ".", "lookup", ".", "index_to_string_table_from_tensor", "(", "mapping", "=", "class_names", ",", "default_value", "=", "'UNKNOWN'", ")", "# Get the label of the input target.", "if", "keep_target", ":", "input_target_label", "=", "table", ".", "lookup", "(", "input_ops", ".", "features", "[", "target_name", "]", ")", "outputs", "[", "PG_TARGET", "]", "=", "tf", ".", "squeeze", "(", "input_target_label", ")", "# TODO(brandondutra): get the score of the target label too.", "probabilities", "=", "model_fn_ops", ".", "predictions", "[", "'probabilities'", "]", "# if top_n == 0, this means use all the classes. We will use class names as", "# probabilities labels.", "if", "args", ".", "top_n", "==", "0", ":", "predicted_index", "=", "tf", ".", "argmax", "(", "probabilities", ",", "axis", "=", "1", ")", "predicted", "=", "table", ".", "lookup", "(", "predicted_index", ")", "outputs", ".", "update", "(", "{", "PG_CLASSIFICATION_FIRST_LABEL", ":", "predicted", "}", ")", "probabilities_list", "=", "tf", ".", "unstack", "(", "probabilities", ",", "axis", "=", "1", ")", "for", "class_name", ",", "p", "in", "zip", "(", "class_names", ",", "probabilities_list", ")", ":", "outputs", "[", "class_name", "]", "=", "p", "else", ":", "top_n", "=", "args", ".", "top_n", "# get top k labels and their scores.", "(", "top_k_values", ",", "top_k_indices", ")", "=", "tf", ".", "nn", ".", "top_k", "(", "probabilities", ",", "k", "=", "top_n", ")", "top_k_labels", "=", "table", ".", "lookup", "(", "tf", ".", "to_int64", "(", "top_k_indices", ")", ")", "# Write the top_k values using 2*top_n columns.", "num_digits", "=", "int", "(", "math", ".", "ceil", "(", "math", ".", "log", "(", "top_n", ",", "10", ")", ")", ")", "if", "num_digits", "==", "0", ":", "num_digits", "=", "1", "for", "i", "in", "range", "(", "0", ",", "top_n", ")", ":", "# Pad i based on the size of k. So if k = 100, i = 23 -> i = '023'. This", "# makes sorting the columns easy.", "padded_i", "=", "str", "(", "i", "+", "1", ")", ".", "zfill", "(", "num_digits", ")", "if", "i", "==", "0", ":", "label_alias", "=", "PG_CLASSIFICATION_FIRST_LABEL", "else", ":", "label_alias", "=", "PG_CLASSIFICATION_LABEL_TEMPLATE", "%", "padded_i", "label_tensor_name", "=", "(", "tf", ".", "squeeze", "(", "tf", ".", "slice", "(", "top_k_labels", ",", "[", "0", ",", "i", "]", ",", "[", "tf", ".", "shape", "(", "top_k_labels", ")", "[", "0", "]", ",", "1", "]", ")", ")", ")", "if", "i", "==", "0", ":", "score_alias", "=", "PG_CLASSIFICATION_FIRST_SCORE", "else", ":", "score_alias", "=", "PG_CLASSIFICATION_SCORE_TEMPLATE", "%", "padded_i", "score_tensor_name", "=", "(", "tf", ".", "squeeze", "(", "tf", ".", "slice", "(", "top_k_values", ",", "[", "0", ",", "i", "]", ",", "[", "tf", ".", "shape", "(", "top_k_values", ")", "[", "0", "]", ",", "1", "]", ")", ")", ")", "outputs", ".", "update", "(", "{", "label_alias", ":", "label_tensor_name", ",", "score_alias", ":", "score_tensor_name", "}", ")", "else", ":", "if", "keep_target", ":", "outputs", "[", "PG_TARGET", "]", "=", "tf", ".", "squeeze", "(", "input_ops", ".", "features", "[", "target_name", "]", ")", "scores", "=", "model_fn_ops", ".", "predictions", "[", "'scores'", "]", "outputs", "[", "PG_REGRESSION_PREDICTED_TARGET", "]", "=", "tf", ".", "squeeze", "(", "scores", ")", "return", "outputs" ]
Makes the final prediction output layer.
[ "Makes", "the", "final", "prediction", "output", "layer", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/trainer/task.py#L377-L456
train
237,933
googledatalab/pydatalab
solutionbox/ml_workbench/xgboost/trainer/task.py
read_vocab
def read_vocab(args, column_name): """Reads a vocab file if it exists. Args: args: command line flags column_name: name of column to that has a vocab file. Returns: List of vocab words or [] if the vocab file is not found. """ vocab_path = os.path.join(args.analysis, feature_transforms.VOCAB_ANALYSIS_FILE % column_name) if not file_io.file_exists(vocab_path): return [] vocab, _ = feature_transforms.read_vocab_file(vocab_path) return vocab
python
def read_vocab(args, column_name): """Reads a vocab file if it exists. Args: args: command line flags column_name: name of column to that has a vocab file. Returns: List of vocab words or [] if the vocab file is not found. """ vocab_path = os.path.join(args.analysis, feature_transforms.VOCAB_ANALYSIS_FILE % column_name) if not file_io.file_exists(vocab_path): return [] vocab, _ = feature_transforms.read_vocab_file(vocab_path) return vocab
[ "def", "read_vocab", "(", "args", ",", "column_name", ")", ":", "vocab_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "analysis", ",", "feature_transforms", ".", "VOCAB_ANALYSIS_FILE", "%", "column_name", ")", "if", "not", "file_io", ".", "file_exists", "(", "vocab_path", ")", ":", "return", "[", "]", "vocab", ",", "_", "=", "feature_transforms", ".", "read_vocab_file", "(", "vocab_path", ")", "return", "vocab" ]
Reads a vocab file if it exists. Args: args: command line flags column_name: name of column to that has a vocab file. Returns: List of vocab words or [] if the vocab file is not found.
[ "Reads", "a", "vocab", "file", "if", "it", "exists", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/trainer/task.py#L642-L659
train
237,934
googledatalab/pydatalab
datalab/utils/_utils.py
get_item
def get_item(env, name, default=None): """ Get an item from a dictionary, handling nested lookups with dotted notation. Args: env: the environment (dictionary) to use to look up the name. name: the name to look up, in dotted notation. default: the value to return if the name if not found. Returns: The result of looking up the name, if found; else the default. """ # TODO: handle attributes for key in name.split('.'): if isinstance(env, dict) and key in env: env = env[key] elif isinstance(env, types.ModuleType) and key in env.__dict__: env = env.__dict__[key] else: return default return env
python
def get_item(env, name, default=None): """ Get an item from a dictionary, handling nested lookups with dotted notation. Args: env: the environment (dictionary) to use to look up the name. name: the name to look up, in dotted notation. default: the value to return if the name if not found. Returns: The result of looking up the name, if found; else the default. """ # TODO: handle attributes for key in name.split('.'): if isinstance(env, dict) and key in env: env = env[key] elif isinstance(env, types.ModuleType) and key in env.__dict__: env = env.__dict__[key] else: return default return env
[ "def", "get_item", "(", "env", ",", "name", ",", "default", "=", "None", ")", ":", "# TODO: handle attributes", "for", "key", "in", "name", ".", "split", "(", "'.'", ")", ":", "if", "isinstance", "(", "env", ",", "dict", ")", "and", "key", "in", "env", ":", "env", "=", "env", "[", "key", "]", "elif", "isinstance", "(", "env", ",", "types", ".", "ModuleType", ")", "and", "key", "in", "env", ".", "__dict__", ":", "env", "=", "env", ".", "__dict__", "[", "key", "]", "else", ":", "return", "default", "return", "env" ]
Get an item from a dictionary, handling nested lookups with dotted notation. Args: env: the environment (dictionary) to use to look up the name. name: the name to look up, in dotted notation. default: the value to return if the name if not found. Returns: The result of looking up the name, if found; else the default.
[ "Get", "an", "item", "from", "a", "dictionary", "handling", "nested", "lookups", "with", "dotted", "notation", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_utils.py#L41-L60
train
237,935
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_predictor.py
predict
def predict(model_dir, images): """Local instant prediction.""" results = _tf_predict(model_dir, images) predicted_and_scores = [(predicted, label_scores[list(labels).index(predicted)]) for predicted, labels, label_scores in results] return predicted_and_scores
python
def predict(model_dir, images): """Local instant prediction.""" results = _tf_predict(model_dir, images) predicted_and_scores = [(predicted, label_scores[list(labels).index(predicted)]) for predicted, labels, label_scores in results] return predicted_and_scores
[ "def", "predict", "(", "model_dir", ",", "images", ")", ":", "results", "=", "_tf_predict", "(", "model_dir", ",", "images", ")", "predicted_and_scores", "=", "[", "(", "predicted", ",", "label_scores", "[", "list", "(", "labels", ")", ".", "index", "(", "predicted", ")", "]", ")", "for", "predicted", ",", "labels", ",", "label_scores", "in", "results", "]", "return", "predicted_and_scores" ]
Local instant prediction.
[ "Local", "instant", "prediction", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_predictor.py#L58-L64
train
237,936
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_predictor.py
configure_pipeline
def configure_pipeline(p, dataset, model_dir, output_csv, output_bq_table): """Configures a dataflow pipeline for batch prediction.""" data = _util.get_sources_from_dataset(p, dataset, 'predict') if len(dataset.schema) == 2: output_schema = [ {'name': 'image_url', 'type': 'STRING'}, {'name': 'target', 'type': 'STRING'}, {'name': 'predicted', 'type': 'STRING'}, {'name': 'target_prob', 'type': 'FLOAT'}, {'name': 'predicted_prob', 'type': 'FLOAT'}, ] else: output_schema = [ {'name': 'image_url', 'type': 'STRING'}, {'name': 'predicted', 'type': 'STRING'}, {'name': 'predicted_prob', 'type': 'FLOAT'}, ] results = (data | 'Load Images' >> beam.ParDo(LoadImagesDoFn()) | 'Batch Inputs' >> beam.ParDo(EmitAsBatchDoFn(20)) | 'Batch Predict' >> beam.ParDo(PredictBatchDoFn(model_dir)) | 'Unbatch' >> beam.ParDo(UnbatchDoFn()) | 'Process Results' >> beam.ParDo(ProcessResultsDoFn())) if output_csv is not None: schema_file = output_csv + '.schema.json' results_save = (results | 'Prepare For Output' >> beam.ParDo(MakeCsvLineDoFn()) | 'Write Csv Results' >> beam.io.textio.WriteToText(output_csv, shard_name_template='')) (results_save | 'Sample One' >> beam.transforms.combiners.Sample.FixedSizeGlobally(1) | 'Serialize Schema' >> beam.Map(lambda path: json.dumps(output_schema)) | 'Write Schema' >> beam.io.textio.WriteToText(schema_file, shard_name_template='')) if output_bq_table is not None: # BigQuery sink takes schema in the form of 'field1:type1,field2:type2...' bq_schema_string = ','.join(x['name'] + ':' + x['type'] for x in output_schema) sink = beam.io.BigQuerySink(output_bq_table, schema=bq_schema_string, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE) results | 'Write BQ Results' >> beam.io.Write(sink)
python
def configure_pipeline(p, dataset, model_dir, output_csv, output_bq_table): """Configures a dataflow pipeline for batch prediction.""" data = _util.get_sources_from_dataset(p, dataset, 'predict') if len(dataset.schema) == 2: output_schema = [ {'name': 'image_url', 'type': 'STRING'}, {'name': 'target', 'type': 'STRING'}, {'name': 'predicted', 'type': 'STRING'}, {'name': 'target_prob', 'type': 'FLOAT'}, {'name': 'predicted_prob', 'type': 'FLOAT'}, ] else: output_schema = [ {'name': 'image_url', 'type': 'STRING'}, {'name': 'predicted', 'type': 'STRING'}, {'name': 'predicted_prob', 'type': 'FLOAT'}, ] results = (data | 'Load Images' >> beam.ParDo(LoadImagesDoFn()) | 'Batch Inputs' >> beam.ParDo(EmitAsBatchDoFn(20)) | 'Batch Predict' >> beam.ParDo(PredictBatchDoFn(model_dir)) | 'Unbatch' >> beam.ParDo(UnbatchDoFn()) | 'Process Results' >> beam.ParDo(ProcessResultsDoFn())) if output_csv is not None: schema_file = output_csv + '.schema.json' results_save = (results | 'Prepare For Output' >> beam.ParDo(MakeCsvLineDoFn()) | 'Write Csv Results' >> beam.io.textio.WriteToText(output_csv, shard_name_template='')) (results_save | 'Sample One' >> beam.transforms.combiners.Sample.FixedSizeGlobally(1) | 'Serialize Schema' >> beam.Map(lambda path: json.dumps(output_schema)) | 'Write Schema' >> beam.io.textio.WriteToText(schema_file, shard_name_template='')) if output_bq_table is not None: # BigQuery sink takes schema in the form of 'field1:type1,field2:type2...' bq_schema_string = ','.join(x['name'] + ':' + x['type'] for x in output_schema) sink = beam.io.BigQuerySink(output_bq_table, schema=bq_schema_string, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE) results | 'Write BQ Results' >> beam.io.Write(sink)
[ "def", "configure_pipeline", "(", "p", ",", "dataset", ",", "model_dir", ",", "output_csv", ",", "output_bq_table", ")", ":", "data", "=", "_util", ".", "get_sources_from_dataset", "(", "p", ",", "dataset", ",", "'predict'", ")", "if", "len", "(", "dataset", ".", "schema", ")", "==", "2", ":", "output_schema", "=", "[", "{", "'name'", ":", "'image_url'", ",", "'type'", ":", "'STRING'", "}", ",", "{", "'name'", ":", "'target'", ",", "'type'", ":", "'STRING'", "}", ",", "{", "'name'", ":", "'predicted'", ",", "'type'", ":", "'STRING'", "}", ",", "{", "'name'", ":", "'target_prob'", ",", "'type'", ":", "'FLOAT'", "}", ",", "{", "'name'", ":", "'predicted_prob'", ",", "'type'", ":", "'FLOAT'", "}", ",", "]", "else", ":", "output_schema", "=", "[", "{", "'name'", ":", "'image_url'", ",", "'type'", ":", "'STRING'", "}", ",", "{", "'name'", ":", "'predicted'", ",", "'type'", ":", "'STRING'", "}", ",", "{", "'name'", ":", "'predicted_prob'", ",", "'type'", ":", "'FLOAT'", "}", ",", "]", "results", "=", "(", "data", "|", "'Load Images'", ">>", "beam", ".", "ParDo", "(", "LoadImagesDoFn", "(", ")", ")", "|", "'Batch Inputs'", ">>", "beam", ".", "ParDo", "(", "EmitAsBatchDoFn", "(", "20", ")", ")", "|", "'Batch Predict'", ">>", "beam", ".", "ParDo", "(", "PredictBatchDoFn", "(", "model_dir", ")", ")", "|", "'Unbatch'", ">>", "beam", ".", "ParDo", "(", "UnbatchDoFn", "(", ")", ")", "|", "'Process Results'", ">>", "beam", ".", "ParDo", "(", "ProcessResultsDoFn", "(", ")", ")", ")", "if", "output_csv", "is", "not", "None", ":", "schema_file", "=", "output_csv", "+", "'.schema.json'", "results_save", "=", "(", "results", "|", "'Prepare For Output'", ">>", "beam", ".", "ParDo", "(", "MakeCsvLineDoFn", "(", ")", ")", "|", "'Write Csv Results'", ">>", "beam", ".", "io", ".", "textio", ".", "WriteToText", "(", "output_csv", ",", "shard_name_template", "=", "''", ")", ")", "(", "results_save", "|", "'Sample One'", ">>", "beam", ".", "transforms", ".", "combiners", ".", "Sample", ".", "FixedSizeGlobally", "(", "1", ")", "|", "'Serialize Schema'", ">>", "beam", ".", "Map", "(", "lambda", "path", ":", "json", ".", "dumps", "(", "output_schema", ")", ")", "|", "'Write Schema'", ">>", "beam", ".", "io", ".", "textio", ".", "WriteToText", "(", "schema_file", ",", "shard_name_template", "=", "''", ")", ")", "if", "output_bq_table", "is", "not", "None", ":", "# BigQuery sink takes schema in the form of 'field1:type1,field2:type2...'", "bq_schema_string", "=", "','", ".", "join", "(", "x", "[", "'name'", "]", "+", "':'", "+", "x", "[", "'type'", "]", "for", "x", "in", "output_schema", ")", "sink", "=", "beam", ".", "io", ".", "BigQuerySink", "(", "output_bq_table", ",", "schema", "=", "bq_schema_string", ",", "write_disposition", "=", "beam", ".", "io", ".", "BigQueryDisposition", ".", "WRITE_TRUNCATE", ")", "results", "|", "'Write BQ Results'", ">>", "beam", ".", "io", ".", "Write", "(", "sink", ")" ]
Configures a dataflow pipeline for batch prediction.
[ "Configures", "a", "dataflow", "pipeline", "for", "batch", "prediction", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_predictor.py#L187-L228
train
237,937
googledatalab/pydatalab
datalab/bigquery/_query.py
Query.sampling_query
def sampling_query(sql, context, fields=None, count=5, sampling=None, udfs=None, data_sources=None): """Returns a sampling Query for the SQL object. Args: sql: the SQL statement (string) or Query object to sample. context: a Context object providing project_id and credentials. fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. udfs: array of UDFs referenced in the SQL. data_sources: dictionary of federated (external) tables referenced in the SQL. Returns: A Query object for sampling the table. """ return Query(_sampling.Sampling.sampling_query(sql, fields, count, sampling), context=context, udfs=udfs, data_sources=data_sources)
python
def sampling_query(sql, context, fields=None, count=5, sampling=None, udfs=None, data_sources=None): """Returns a sampling Query for the SQL object. Args: sql: the SQL statement (string) or Query object to sample. context: a Context object providing project_id and credentials. fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. udfs: array of UDFs referenced in the SQL. data_sources: dictionary of federated (external) tables referenced in the SQL. Returns: A Query object for sampling the table. """ return Query(_sampling.Sampling.sampling_query(sql, fields, count, sampling), context=context, udfs=udfs, data_sources=data_sources)
[ "def", "sampling_query", "(", "sql", ",", "context", ",", "fields", "=", "None", ",", "count", "=", "5", ",", "sampling", "=", "None", ",", "udfs", "=", "None", ",", "data_sources", "=", "None", ")", ":", "return", "Query", "(", "_sampling", ".", "Sampling", ".", "sampling_query", "(", "sql", ",", "fields", ",", "count", ",", "sampling", ")", ",", "context", "=", "context", ",", "udfs", "=", "udfs", ",", "data_sources", "=", "data_sources", ")" ]
Returns a sampling Query for the SQL object. Args: sql: the SQL statement (string) or Query object to sample. context: a Context object providing project_id and credentials. fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. udfs: array of UDFs referenced in the SQL. data_sources: dictionary of federated (external) tables referenced in the SQL. Returns: A Query object for sampling the table.
[ "Returns", "a", "sampling", "Query", "for", "the", "SQL", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L37-L54
train
237,938
googledatalab/pydatalab
datalab/bigquery/_query.py
Query.results
def results(self, use_cache=True, dialect=None, billing_tier=None): """Retrieves table of results for the query. May block if the query must be executed first. Args: use_cache: whether to use cached results or not. Ignored if append is specified. dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A QueryResultsTable containing the result set. Raises: Exception if the query could not be executed or query response was malformed. """ if not use_cache or (self._results is None): self.execute(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier) return self._results.results
python
def results(self, use_cache=True, dialect=None, billing_tier=None): """Retrieves table of results for the query. May block if the query must be executed first. Args: use_cache: whether to use cached results or not. Ignored if append is specified. dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A QueryResultsTable containing the result set. Raises: Exception if the query could not be executed or query response was malformed. """ if not use_cache or (self._results is None): self.execute(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier) return self._results.results
[ "def", "results", "(", "self", ",", "use_cache", "=", "True", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "if", "not", "use_cache", "or", "(", "self", ".", "_results", "is", "None", ")", ":", "self", ".", "execute", "(", "use_cache", "=", "use_cache", ",", "dialect", "=", "dialect", ",", "billing_tier", "=", "billing_tier", ")", "return", "self", ".", "_results", ".", "results" ]
Retrieves table of results for the query. May block if the query must be executed first. Args: use_cache: whether to use cached results or not. Ignored if append is specified. dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A QueryResultsTable containing the result set. Raises: Exception if the query could not be executed or query response was malformed.
[ "Retrieves", "table", "of", "results", "for", "the", "query", ".", "May", "block", "if", "the", "query", "must", "be", "executed", "first", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L209-L229
train
237,939
googledatalab/pydatalab
datalab/bigquery/_query.py
Query.extract
def extract(self, storage_uris, format='csv', csv_delimiter=',', csv_header=True, compress=False, use_cache=True, dialect=None, billing_tier=None): """Exports the query results to GCS. Args: storage_uris: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for csv exports, the field delimiter to use (default ','). csv_header: for csv exports, whether to include an initial header line (default True). compress: whether to compress the data on export. Compression is not supported for AVRO format (default False). use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A Job object for the export Job if it was completed successfully; else None. Raises: An Exception if the query or extract failed. """ return self.results(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier).extract(storage_uris, format=format, csv_delimiter=csv_delimiter, csv_header=csv_header, compress=compress)
python
def extract(self, storage_uris, format='csv', csv_delimiter=',', csv_header=True, compress=False, use_cache=True, dialect=None, billing_tier=None): """Exports the query results to GCS. Args: storage_uris: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for csv exports, the field delimiter to use (default ','). csv_header: for csv exports, whether to include an initial header line (default True). compress: whether to compress the data on export. Compression is not supported for AVRO format (default False). use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A Job object for the export Job if it was completed successfully; else None. Raises: An Exception if the query or extract failed. """ return self.results(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier).extract(storage_uris, format=format, csv_delimiter=csv_delimiter, csv_header=csv_header, compress=compress)
[ "def", "extract", "(", "self", ",", "storage_uris", ",", "format", "=", "'csv'", ",", "csv_delimiter", "=", "','", ",", "csv_header", "=", "True", ",", "compress", "=", "False", ",", "use_cache", "=", "True", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "return", "self", ".", "results", "(", "use_cache", "=", "use_cache", ",", "dialect", "=", "dialect", ",", "billing_tier", "=", "billing_tier", ")", ".", "extract", "(", "storage_uris", ",", "format", "=", "format", ",", "csv_delimiter", "=", "csv_delimiter", ",", "csv_header", "=", "csv_header", ",", "compress", "=", "compress", ")" ]
Exports the query results to GCS. Args: storage_uris: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for csv exports, the field delimiter to use (default ','). csv_header: for csv exports, whether to include an initial header line (default True). compress: whether to compress the data on export. Compression is not supported for AVRO format (default False). use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A Job object for the export Job if it was completed successfully; else None. Raises: An Exception if the query or extract failed.
[ "Exports", "the", "query", "results", "to", "GCS", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L231-L261
train
237,940
googledatalab/pydatalab
datalab/bigquery/_query.py
Query.to_dataframe
def to_dataframe(self, start_row=0, max_rows=None, use_cache=True, dialect=None, billing_tier=None): """ Exports the query results 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). use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A Pandas dataframe containing the table data. """ return self.results(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier) \ .to_dataframe(start_row=start_row, max_rows=max_rows)
python
def to_dataframe(self, start_row=0, max_rows=None, use_cache=True, dialect=None, billing_tier=None): """ Exports the query results 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). use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A Pandas dataframe containing the table data. """ return self.results(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier) \ .to_dataframe(start_row=start_row, max_rows=max_rows)
[ "def", "to_dataframe", "(", "self", ",", "start_row", "=", "0", ",", "max_rows", "=", "None", ",", "use_cache", "=", "True", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "return", "self", ".", "results", "(", "use_cache", "=", "use_cache", ",", "dialect", "=", "dialect", ",", "billing_tier", "=", "billing_tier", ")", ".", "to_dataframe", "(", "start_row", "=", "start_row", ",", "max_rows", "=", "max_rows", ")" ]
Exports the query results 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). use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A Pandas dataframe containing the table data.
[ "Exports", "the", "query", "results", "to", "a", "Pandas", "dataframe", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L303-L323
train
237,941
googledatalab/pydatalab
datalab/bigquery/_query.py
Query.sample
def sample(self, count=5, fields=None, sampling=None, use_cache=True, dialect=None, billing_tier=None): """Retrieves a sampling of rows for the query. Args: count: an optional count of rows to retrieve which is used if a specific sampling is not specified (default 5). fields: the list of fields to sample (default None implies all). sampling: an optional sampling strategy to apply to the table. use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A QueryResultsTable containing a sampling of the result set. Raises: Exception if the query could not be executed or query response was malformed. """ return Query.sampling_query(self._sql, self._context, count=count, fields=fields, sampling=sampling, udfs=self._udfs, data_sources=self._data_sources).results(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier)
python
def sample(self, count=5, fields=None, sampling=None, use_cache=True, dialect=None, billing_tier=None): """Retrieves a sampling of rows for the query. Args: count: an optional count of rows to retrieve which is used if a specific sampling is not specified (default 5). fields: the list of fields to sample (default None implies all). sampling: an optional sampling strategy to apply to the table. use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A QueryResultsTable containing a sampling of the result set. Raises: Exception if the query could not be executed or query response was malformed. """ return Query.sampling_query(self._sql, self._context, count=count, fields=fields, sampling=sampling, udfs=self._udfs, data_sources=self._data_sources).results(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier)
[ "def", "sample", "(", "self", ",", "count", "=", "5", ",", "fields", "=", "None", ",", "sampling", "=", "None", ",", "use_cache", "=", "True", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "return", "Query", ".", "sampling_query", "(", "self", ".", "_sql", ",", "self", ".", "_context", ",", "count", "=", "count", ",", "fields", "=", "fields", ",", "sampling", "=", "sampling", ",", "udfs", "=", "self", ".", "_udfs", ",", "data_sources", "=", "self", ".", "_data_sources", ")", ".", "results", "(", "use_cache", "=", "use_cache", ",", "dialect", "=", "dialect", ",", "billing_tier", "=", "billing_tier", ")" ]
Retrieves a sampling of rows for the query. Args: count: an optional count of rows to retrieve which is used if a specific sampling is not specified (default 5). fields: the list of fields to sample (default None implies all). sampling: an optional sampling strategy to apply to the table. use_cache: whether to use cached results or not (default True). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A QueryResultsTable containing a sampling of the result set. Raises: Exception if the query could not be executed or query response was malformed.
[ "Retrieves", "a", "sampling", "of", "rows", "for", "the", "query", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L379-L406
train
237,942
googledatalab/pydatalab
datalab/bigquery/_query.py
Query.execute
def execute(self, table_name=None, table_mode='create', use_cache=True, priority='interactive', allow_large_results=False, dialect=None, billing_tier=None): """ Initiate the query, blocking until complete and then return the results. Args: table_name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query results or ignore cache. Has no effect if destination is specified (default True). priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much as three hours but are not rate-limited. allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is slower and requires a table_name to be specified) (default False). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: The QueryResultsTable for the query. Raises: Exception if query could not be executed. """ job = self.execute_async(table_name=table_name, table_mode=table_mode, use_cache=use_cache, priority=priority, allow_large_results=allow_large_results, dialect=dialect, billing_tier=billing_tier) self._results = job.wait() return self._results
python
def execute(self, table_name=None, table_mode='create', use_cache=True, priority='interactive', allow_large_results=False, dialect=None, billing_tier=None): """ Initiate the query, blocking until complete and then return the results. Args: table_name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query results or ignore cache. Has no effect if destination is specified (default True). priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much as three hours but are not rate-limited. allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is slower and requires a table_name to be specified) (default False). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: The QueryResultsTable for the query. Raises: Exception if query could not be executed. """ job = self.execute_async(table_name=table_name, table_mode=table_mode, use_cache=use_cache, priority=priority, allow_large_results=allow_large_results, dialect=dialect, billing_tier=billing_tier) self._results = job.wait() return self._results
[ "def", "execute", "(", "self", ",", "table_name", "=", "None", ",", "table_mode", "=", "'create'", ",", "use_cache", "=", "True", ",", "priority", "=", "'interactive'", ",", "allow_large_results", "=", "False", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "job", "=", "self", ".", "execute_async", "(", "table_name", "=", "table_name", ",", "table_mode", "=", "table_mode", ",", "use_cache", "=", "use_cache", ",", "priority", "=", "priority", ",", "allow_large_results", "=", "allow_large_results", ",", "dialect", "=", "dialect", ",", "billing_tier", "=", "billing_tier", ")", "self", ".", "_results", "=", "job", ".", "wait", "(", ")", "return", "self", ".", "_results" ]
Initiate the query, blocking until complete and then return the results. Args: table_name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query results or ignore cache. Has no effect if destination is specified (default True). priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much as three hours but are not rate-limited. allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is slower and requires a table_name to be specified) (default False). dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a charge). If unspecified, this will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: The QueryResultsTable for the query. Raises: Exception if query could not be executed.
[ "Initiate", "the", "query", "blocking", "until", "complete", "and", "then", "return", "the", "results", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L496-L529
train
237,943
googledatalab/pydatalab
datalab/bigquery/_query.py
Query.to_view
def to_view(self, view_name): """ Create a View from this Query. Args: view_name: the name of the View either as a string or a 3-part tuple (projectid, datasetid, name). Returns: A View for the Query. """ # Do the import here to avoid circular dependencies at top-level. from . import _view return _view.View(view_name, self._context).create(self._sql)
python
def to_view(self, view_name): """ Create a View from this Query. Args: view_name: the name of the View either as a string or a 3-part tuple (projectid, datasetid, name). Returns: A View for the Query. """ # Do the import here to avoid circular dependencies at top-level. from . import _view return _view.View(view_name, self._context).create(self._sql)
[ "def", "to_view", "(", "self", ",", "view_name", ")", ":", "# Do the import here to avoid circular dependencies at top-level.", "from", ".", "import", "_view", "return", "_view", ".", "View", "(", "view_name", ",", "self", ".", "_context", ")", ".", "create", "(", "self", ".", "_sql", ")" ]
Create a View from this Query. Args: view_name: the name of the View either as a string or a 3-part tuple (projectid, datasetid, name). Returns: A View for the Query.
[ "Create", "a", "View", "from", "this", "Query", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L531-L543
train
237,944
googledatalab/pydatalab
google/datalab/utils/commands/_commands.py
CommandParser.format_help
def format_help(self): """Override help doc to add cell args. """ if not self._cell_args: return super(CommandParser, self).format_help() else: # Print the standard argparse info, the cell arg block, and then the epilog # If we don't remove epilog before calling the super, then epilog will # be printed before the 'Cell args' block. epilog = self.epilog self.epilog = None orig_help = super(CommandParser, self).format_help() cell_args_help = '\nCell args:\n\n' for cell_arg, v in six.iteritems(self._cell_args): required = 'Required' if v['required'] else 'Optional' cell_args_help += '%s: %s. %s.\n\n' % (cell_arg, required, v['help']) orig_help += cell_args_help if epilog: orig_help += epilog + '\n\n' return orig_help
python
def format_help(self): """Override help doc to add cell args. """ if not self._cell_args: return super(CommandParser, self).format_help() else: # Print the standard argparse info, the cell arg block, and then the epilog # If we don't remove epilog before calling the super, then epilog will # be printed before the 'Cell args' block. epilog = self.epilog self.epilog = None orig_help = super(CommandParser, self).format_help() cell_args_help = '\nCell args:\n\n' for cell_arg, v in six.iteritems(self._cell_args): required = 'Required' if v['required'] else 'Optional' cell_args_help += '%s: %s. %s.\n\n' % (cell_arg, required, v['help']) orig_help += cell_args_help if epilog: orig_help += epilog + '\n\n' return orig_help
[ "def", "format_help", "(", "self", ")", ":", "if", "not", "self", ".", "_cell_args", ":", "return", "super", "(", "CommandParser", ",", "self", ")", ".", "format_help", "(", ")", "else", ":", "# Print the standard argparse info, the cell arg block, and then the epilog", "# If we don't remove epilog before calling the super, then epilog will", "# be printed before the 'Cell args' block.", "epilog", "=", "self", ".", "epilog", "self", ".", "epilog", "=", "None", "orig_help", "=", "super", "(", "CommandParser", ",", "self", ")", ".", "format_help", "(", ")", "cell_args_help", "=", "'\\nCell args:\\n\\n'", "for", "cell_arg", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "_cell_args", ")", ":", "required", "=", "'Required'", "if", "v", "[", "'required'", "]", "else", "'Optional'", "cell_args_help", "+=", "'%s: %s. %s.\\n\\n'", "%", "(", "cell_arg", ",", "required", ",", "v", "[", "'help'", "]", ")", "orig_help", "+=", "cell_args_help", "if", "epilog", ":", "orig_help", "+=", "epilog", "+", "'\\n\\n'", "return", "orig_help" ]
Override help doc to add cell args.
[ "Override", "help", "doc", "to", "add", "cell", "args", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L56-L77
train
237,945
googledatalab/pydatalab
google/datalab/utils/commands/_commands.py
CommandParser._get_subparsers
def _get_subparsers(self): """Recursively get subparsers.""" subparsers = [] for action in self._actions: if isinstance(action, argparse._SubParsersAction): for _, subparser in action.choices.items(): subparsers.append(subparser) ret = subparsers for sp in subparsers: ret += sp._get_subparsers() return ret
python
def _get_subparsers(self): """Recursively get subparsers.""" subparsers = [] for action in self._actions: if isinstance(action, argparse._SubParsersAction): for _, subparser in action.choices.items(): subparsers.append(subparser) ret = subparsers for sp in subparsers: ret += sp._get_subparsers() return ret
[ "def", "_get_subparsers", "(", "self", ")", ":", "subparsers", "=", "[", "]", "for", "action", "in", "self", ".", "_actions", ":", "if", "isinstance", "(", "action", ",", "argparse", ".", "_SubParsersAction", ")", ":", "for", "_", ",", "subparser", "in", "action", ".", "choices", ".", "items", "(", ")", ":", "subparsers", ".", "append", "(", "subparser", ")", "ret", "=", "subparsers", "for", "sp", "in", "subparsers", ":", "ret", "+=", "sp", ".", "_get_subparsers", "(", ")", "return", "ret" ]
Recursively get subparsers.
[ "Recursively", "get", "subparsers", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L101-L113
train
237,946
googledatalab/pydatalab
google/datalab/utils/commands/_commands.py
CommandParser._get_subparser_line_args
def _get_subparser_line_args(self, subparser_prog): """ Get line args of a specified subparser by its prog.""" subparsers = self._get_subparsers() for subparser in subparsers: if subparser_prog == subparser.prog: # Found the subparser. args_to_parse = [] for action in subparser._actions: if action.option_strings: for argname in action.option_strings: if argname.startswith('--'): args_to_parse.append(argname[2:]) return args_to_parse return None
python
def _get_subparser_line_args(self, subparser_prog): """ Get line args of a specified subparser by its prog.""" subparsers = self._get_subparsers() for subparser in subparsers: if subparser_prog == subparser.prog: # Found the subparser. args_to_parse = [] for action in subparser._actions: if action.option_strings: for argname in action.option_strings: if argname.startswith('--'): args_to_parse.append(argname[2:]) return args_to_parse return None
[ "def", "_get_subparser_line_args", "(", "self", ",", "subparser_prog", ")", ":", "subparsers", "=", "self", ".", "_get_subparsers", "(", ")", "for", "subparser", "in", "subparsers", ":", "if", "subparser_prog", "==", "subparser", ".", "prog", ":", "# Found the subparser.", "args_to_parse", "=", "[", "]", "for", "action", "in", "subparser", ".", "_actions", ":", "if", "action", ".", "option_strings", ":", "for", "argname", "in", "action", ".", "option_strings", ":", "if", "argname", ".", "startswith", "(", "'--'", ")", ":", "args_to_parse", ".", "append", "(", "argname", "[", "2", ":", "]", ")", "return", "args_to_parse", "return", "None" ]
Get line args of a specified subparser by its prog.
[ "Get", "line", "args", "of", "a", "specified", "subparser", "by", "its", "prog", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L115-L130
train
237,947
googledatalab/pydatalab
google/datalab/utils/commands/_commands.py
CommandParser._get_subparser_cell_args
def _get_subparser_cell_args(self, subparser_prog): """ Get cell args of a specified subparser by its prog.""" subparsers = self._get_subparsers() for subparser in subparsers: if subparser_prog == subparser.prog: return subparser._cell_args return None
python
def _get_subparser_cell_args(self, subparser_prog): """ Get cell args of a specified subparser by its prog.""" subparsers = self._get_subparsers() for subparser in subparsers: if subparser_prog == subparser.prog: return subparser._cell_args return None
[ "def", "_get_subparser_cell_args", "(", "self", ",", "subparser_prog", ")", ":", "subparsers", "=", "self", ".", "_get_subparsers", "(", ")", "for", "subparser", "in", "subparsers", ":", "if", "subparser_prog", "==", "subparser", ".", "prog", ":", "return", "subparser", ".", "_cell_args", "return", "None" ]
Get cell args of a specified subparser by its prog.
[ "Get", "cell", "args", "of", "a", "specified", "subparser", "by", "its", "prog", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L132-L140
train
237,948
googledatalab/pydatalab
google/datalab/utils/commands/_commands.py
CommandParser.add_cell_argument
def add_cell_argument(self, name, help, required=False): """ Add a cell only argument. Args: name: name of the argument. No need to start with "-" or "--". help: the help string of the argument. required: Whether it is required in cell content. """ for action in self._actions: if action.dest == name: raise ValueError('Arg "%s" was added by add_argument already.' % name) self._cell_args[name] = {'required': required, 'help': help}
python
def add_cell_argument(self, name, help, required=False): """ Add a cell only argument. Args: name: name of the argument. No need to start with "-" or "--". help: the help string of the argument. required: Whether it is required in cell content. """ for action in self._actions: if action.dest == name: raise ValueError('Arg "%s" was added by add_argument already.' % name) self._cell_args[name] = {'required': required, 'help': help}
[ "def", "add_cell_argument", "(", "self", ",", "name", ",", "help", ",", "required", "=", "False", ")", ":", "for", "action", "in", "self", ".", "_actions", ":", "if", "action", ".", "dest", "==", "name", ":", "raise", "ValueError", "(", "'Arg \"%s\" was added by add_argument already.'", "%", "name", ")", "self", ".", "_cell_args", "[", "name", "]", "=", "{", "'required'", ":", "required", ",", "'help'", ":", "help", "}" ]
Add a cell only argument. Args: name: name of the argument. No need to start with "-" or "--". help: the help string of the argument. required: Whether it is required in cell content.
[ "Add", "a", "cell", "only", "argument", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L142-L155
train
237,949
googledatalab/pydatalab
google/datalab/utils/commands/_commands.py
CommandParser.parse
def parse(self, line, cell, namespace=None): """Parses a line and cell into a dictionary of arguments, expanding variables from a namespace. For each line parameters beginning with --, it also checks the cell content and see if it exists there. For example, if "--config1" is a line parameter, it checks to see if cell dict contains "config1" item, and if so, use the cell value. The "config1" item will also be removed from cell content. Args: line: line content. cell: cell content. namespace: user namespace. If None, IPython's user namespace is used. Returns: A tuple of: 1. parsed config dict. 2. remaining cell after line parameters are extracted. """ if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns # Find which subcommand in the line by comparing line with subcommand progs. # For example, assuming there are 3 subcommands with their progs # %bq tables # %bq tables list # %bq datasets # and the line is "tables list --dataset proj.myds" # it will find the second one --- "tables list" because it matches the prog and # it is the longest. args = CommandParser.create_args(line, namespace) # "prog" is a ArgumentParser's path splitted by namspace, such as '%bq tables list'. sub_parsers_progs = [x.prog for x in self._get_subparsers()] matched_progs = [] for prog in sub_parsers_progs: # Remove the leading magic such as "%bq". match = prog.split()[1:] for i in range(len(args)): if args[i:i + len(match)] == match: matched_progs.append(prog) break matched_prog = None if matched_progs: # Get the longest match. matched_prog = max(matched_progs, key=lambda x: len(x.split())) # Line args can be provided in cell too. If they are in cell, move them to line # so we can parse them all together. line_args = self._get_subparser_line_args(matched_prog) if line_args: cell_config = None try: cell_config, cell = google.datalab.utils.commands.parse_config_for_selected_keys( cell, line_args) except: # It is okay --- probably because cell is not in yaml or json format. pass if cell_config: google.datalab.utils.commands.replace_vars(cell_config, namespace) for arg_name in cell_config: arg_value = cell_config[arg_name] if arg_value is None: continue if '--' + arg_name in args: raise ValueError('config item "%s" is specified in both cell and line.' % arg_name) if isinstance(arg_value, bool): if arg_value: line += ' --%s' % arg_name else: line += ' --%s %s' % (arg_name, str(cell_config[arg_name])) # Parse args again with the new line. args = CommandParser.create_args(line, namespace) args = vars(self.parse_args(args)) # Parse cell args. cell_config = None cell_args = self._get_subparser_cell_args(matched_prog) if cell_args: try: cell_config, _ = google.datalab.utils.commands.parse_config_for_selected_keys( cell, cell_args) except: # It is okay --- probably because cell is not in yaml or json format. pass if cell_config: google.datalab.utils.commands.replace_vars(cell_config, namespace) for arg in cell_args: if (cell_args[arg]['required'] and (cell_config is None or cell_config.get(arg, None) is None)): raise ValueError('Cell config "%s" is required.' % arg) if cell_config: args.update(cell_config) return args, cell
python
def parse(self, line, cell, namespace=None): """Parses a line and cell into a dictionary of arguments, expanding variables from a namespace. For each line parameters beginning with --, it also checks the cell content and see if it exists there. For example, if "--config1" is a line parameter, it checks to see if cell dict contains "config1" item, and if so, use the cell value. The "config1" item will also be removed from cell content. Args: line: line content. cell: cell content. namespace: user namespace. If None, IPython's user namespace is used. Returns: A tuple of: 1. parsed config dict. 2. remaining cell after line parameters are extracted. """ if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns # Find which subcommand in the line by comparing line with subcommand progs. # For example, assuming there are 3 subcommands with their progs # %bq tables # %bq tables list # %bq datasets # and the line is "tables list --dataset proj.myds" # it will find the second one --- "tables list" because it matches the prog and # it is the longest. args = CommandParser.create_args(line, namespace) # "prog" is a ArgumentParser's path splitted by namspace, such as '%bq tables list'. sub_parsers_progs = [x.prog for x in self._get_subparsers()] matched_progs = [] for prog in sub_parsers_progs: # Remove the leading magic such as "%bq". match = prog.split()[1:] for i in range(len(args)): if args[i:i + len(match)] == match: matched_progs.append(prog) break matched_prog = None if matched_progs: # Get the longest match. matched_prog = max(matched_progs, key=lambda x: len(x.split())) # Line args can be provided in cell too. If they are in cell, move them to line # so we can parse them all together. line_args = self._get_subparser_line_args(matched_prog) if line_args: cell_config = None try: cell_config, cell = google.datalab.utils.commands.parse_config_for_selected_keys( cell, line_args) except: # It is okay --- probably because cell is not in yaml or json format. pass if cell_config: google.datalab.utils.commands.replace_vars(cell_config, namespace) for arg_name in cell_config: arg_value = cell_config[arg_name] if arg_value is None: continue if '--' + arg_name in args: raise ValueError('config item "%s" is specified in both cell and line.' % arg_name) if isinstance(arg_value, bool): if arg_value: line += ' --%s' % arg_name else: line += ' --%s %s' % (arg_name, str(cell_config[arg_name])) # Parse args again with the new line. args = CommandParser.create_args(line, namespace) args = vars(self.parse_args(args)) # Parse cell args. cell_config = None cell_args = self._get_subparser_cell_args(matched_prog) if cell_args: try: cell_config, _ = google.datalab.utils.commands.parse_config_for_selected_keys( cell, cell_args) except: # It is okay --- probably because cell is not in yaml or json format. pass if cell_config: google.datalab.utils.commands.replace_vars(cell_config, namespace) for arg in cell_args: if (cell_args[arg]['required'] and (cell_config is None or cell_config.get(arg, None) is None)): raise ValueError('Cell config "%s" is required.' % arg) if cell_config: args.update(cell_config) return args, cell
[ "def", "parse", "(", "self", ",", "line", ",", "cell", ",", "namespace", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "namespace", "=", "ipy", ".", "user_ns", "# Find which subcommand in the line by comparing line with subcommand progs.", "# For example, assuming there are 3 subcommands with their progs", "# %bq tables", "# %bq tables list", "# %bq datasets", "# and the line is \"tables list --dataset proj.myds\"", "# it will find the second one --- \"tables list\" because it matches the prog and", "# it is the longest.", "args", "=", "CommandParser", ".", "create_args", "(", "line", ",", "namespace", ")", "# \"prog\" is a ArgumentParser's path splitted by namspace, such as '%bq tables list'.", "sub_parsers_progs", "=", "[", "x", ".", "prog", "for", "x", "in", "self", ".", "_get_subparsers", "(", ")", "]", "matched_progs", "=", "[", "]", "for", "prog", "in", "sub_parsers_progs", ":", "# Remove the leading magic such as \"%bq\".", "match", "=", "prog", ".", "split", "(", ")", "[", "1", ":", "]", "for", "i", "in", "range", "(", "len", "(", "args", ")", ")", ":", "if", "args", "[", "i", ":", "i", "+", "len", "(", "match", ")", "]", "==", "match", ":", "matched_progs", ".", "append", "(", "prog", ")", "break", "matched_prog", "=", "None", "if", "matched_progs", ":", "# Get the longest match.", "matched_prog", "=", "max", "(", "matched_progs", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", ".", "split", "(", ")", ")", ")", "# Line args can be provided in cell too. If they are in cell, move them to line", "# so we can parse them all together.", "line_args", "=", "self", ".", "_get_subparser_line_args", "(", "matched_prog", ")", "if", "line_args", ":", "cell_config", "=", "None", "try", ":", "cell_config", ",", "cell", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "parse_config_for_selected_keys", "(", "cell", ",", "line_args", ")", "except", ":", "# It is okay --- probably because cell is not in yaml or json format.", "pass", "if", "cell_config", ":", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "replace_vars", "(", "cell_config", ",", "namespace", ")", "for", "arg_name", "in", "cell_config", ":", "arg_value", "=", "cell_config", "[", "arg_name", "]", "if", "arg_value", "is", "None", ":", "continue", "if", "'--'", "+", "arg_name", "in", "args", ":", "raise", "ValueError", "(", "'config item \"%s\" is specified in both cell and line.'", "%", "arg_name", ")", "if", "isinstance", "(", "arg_value", ",", "bool", ")", ":", "if", "arg_value", ":", "line", "+=", "' --%s'", "%", "arg_name", "else", ":", "line", "+=", "' --%s %s'", "%", "(", "arg_name", ",", "str", "(", "cell_config", "[", "arg_name", "]", ")", ")", "# Parse args again with the new line.", "args", "=", "CommandParser", ".", "create_args", "(", "line", ",", "namespace", ")", "args", "=", "vars", "(", "self", ".", "parse_args", "(", "args", ")", ")", "# Parse cell args.", "cell_config", "=", "None", "cell_args", "=", "self", ".", "_get_subparser_cell_args", "(", "matched_prog", ")", "if", "cell_args", ":", "try", ":", "cell_config", ",", "_", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "parse_config_for_selected_keys", "(", "cell", ",", "cell_args", ")", "except", ":", "# It is okay --- probably because cell is not in yaml or json format.", "pass", "if", "cell_config", ":", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "replace_vars", "(", "cell_config", ",", "namespace", ")", "for", "arg", "in", "cell_args", ":", "if", "(", "cell_args", "[", "arg", "]", "[", "'required'", "]", "and", "(", "cell_config", "is", "None", "or", "cell_config", ".", "get", "(", "arg", ",", "None", ")", "is", "None", ")", ")", ":", "raise", "ValueError", "(", "'Cell config \"%s\" is required.'", "%", "arg", ")", "if", "cell_config", ":", "args", ".", "update", "(", "cell_config", ")", "return", "args", ",", "cell" ]
Parses a line and cell into a dictionary of arguments, expanding variables from a namespace. For each line parameters beginning with --, it also checks the cell content and see if it exists there. For example, if "--config1" is a line parameter, it checks to see if cell dict contains "config1" item, and if so, use the cell value. The "config1" item will also be removed from cell content. Args: line: line content. cell: cell content. namespace: user namespace. If None, IPython's user namespace is used. Returns: A tuple of: 1. parsed config dict. 2. remaining cell after line parameters are extracted.
[ "Parses", "a", "line", "and", "cell", "into", "a", "dictionary", "of", "arguments", "expanding", "variables", "from", "a", "namespace", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L157-L257
train
237,950
googledatalab/pydatalab
google/datalab/ml/_summary.py
Summary._glob_events_files
def _glob_events_files(self, paths, recursive): """Find all tf events files under a list of paths recursively. """ event_files = [] for path in paths: dirs = tf.gfile.Glob(path) dirs = filter(lambda x: tf.gfile.IsDirectory(x), dirs) for dir in dirs: if recursive: dir_files_pair = [(root, filenames) for root, _, filenames in tf.gfile.Walk(dir)] else: dir_files_pair = [(dir, tf.gfile.ListDirectory(dir))] for root, filenames in dir_files_pair: file_names = fnmatch.filter(filenames, '*.tfevents.*') file_paths = [os.path.join(root, x) for x in file_names] file_paths = filter(lambda x: not tf.gfile.IsDirectory(x), file_paths) event_files += file_paths return event_files
python
def _glob_events_files(self, paths, recursive): """Find all tf events files under a list of paths recursively. """ event_files = [] for path in paths: dirs = tf.gfile.Glob(path) dirs = filter(lambda x: tf.gfile.IsDirectory(x), dirs) for dir in dirs: if recursive: dir_files_pair = [(root, filenames) for root, _, filenames in tf.gfile.Walk(dir)] else: dir_files_pair = [(dir, tf.gfile.ListDirectory(dir))] for root, filenames in dir_files_pair: file_names = fnmatch.filter(filenames, '*.tfevents.*') file_paths = [os.path.join(root, x) for x in file_names] file_paths = filter(lambda x: not tf.gfile.IsDirectory(x), file_paths) event_files += file_paths return event_files
[ "def", "_glob_events_files", "(", "self", ",", "paths", ",", "recursive", ")", ":", "event_files", "=", "[", "]", "for", "path", "in", "paths", ":", "dirs", "=", "tf", ".", "gfile", ".", "Glob", "(", "path", ")", "dirs", "=", "filter", "(", "lambda", "x", ":", "tf", ".", "gfile", ".", "IsDirectory", "(", "x", ")", ",", "dirs", ")", "for", "dir", "in", "dirs", ":", "if", "recursive", ":", "dir_files_pair", "=", "[", "(", "root", ",", "filenames", ")", "for", "root", ",", "_", ",", "filenames", "in", "tf", ".", "gfile", ".", "Walk", "(", "dir", ")", "]", "else", ":", "dir_files_pair", "=", "[", "(", "dir", ",", "tf", ".", "gfile", ".", "ListDirectory", "(", "dir", ")", ")", "]", "for", "root", ",", "filenames", "in", "dir_files_pair", ":", "file_names", "=", "fnmatch", ".", "filter", "(", "filenames", ",", "'*.tfevents.*'", ")", "file_paths", "=", "[", "os", ".", "path", ".", "join", "(", "root", ",", "x", ")", "for", "x", "in", "file_names", "]", "file_paths", "=", "filter", "(", "lambda", "x", ":", "not", "tf", ".", "gfile", ".", "IsDirectory", "(", "x", ")", ",", "file_paths", ")", "event_files", "+=", "file_paths", "return", "event_files" ]
Find all tf events files under a list of paths recursively.
[ "Find", "all", "tf", "events", "files", "under", "a", "list", "of", "paths", "recursively", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_summary.py#L44-L62
train
237,951
googledatalab/pydatalab
google/datalab/ml/_summary.py
Summary.list_events
def list_events(self): """List all scalar events in the directory. Returns: A dictionary. Key is the name of a event. Value is a set of dirs that contain that event. """ event_dir_dict = collections.defaultdict(set) for event_file in self._glob_events_files(self._paths, recursive=True): dir = os.path.dirname(event_file) try: for record in tf_record.tf_record_iterator(event_file): event = event_pb2.Event.FromString(record) if event.summary is None or event.summary.value is None: continue for value in event.summary.value: if value.simple_value is None or value.tag is None: continue event_dir_dict[value.tag].add(dir) except tf.errors.DataLossError: # DataLossError seems to happen sometimes for small logs. # We want to show good records regardless. continue return dict(event_dir_dict)
python
def list_events(self): """List all scalar events in the directory. Returns: A dictionary. Key is the name of a event. Value is a set of dirs that contain that event. """ event_dir_dict = collections.defaultdict(set) for event_file in self._glob_events_files(self._paths, recursive=True): dir = os.path.dirname(event_file) try: for record in tf_record.tf_record_iterator(event_file): event = event_pb2.Event.FromString(record) if event.summary is None or event.summary.value is None: continue for value in event.summary.value: if value.simple_value is None or value.tag is None: continue event_dir_dict[value.tag].add(dir) except tf.errors.DataLossError: # DataLossError seems to happen sometimes for small logs. # We want to show good records regardless. continue return dict(event_dir_dict)
[ "def", "list_events", "(", "self", ")", ":", "event_dir_dict", "=", "collections", ".", "defaultdict", "(", "set", ")", "for", "event_file", "in", "self", ".", "_glob_events_files", "(", "self", ".", "_paths", ",", "recursive", "=", "True", ")", ":", "dir", "=", "os", ".", "path", ".", "dirname", "(", "event_file", ")", "try", ":", "for", "record", "in", "tf_record", ".", "tf_record_iterator", "(", "event_file", ")", ":", "event", "=", "event_pb2", ".", "Event", ".", "FromString", "(", "record", ")", "if", "event", ".", "summary", "is", "None", "or", "event", ".", "summary", ".", "value", "is", "None", ":", "continue", "for", "value", "in", "event", ".", "summary", ".", "value", ":", "if", "value", ".", "simple_value", "is", "None", "or", "value", ".", "tag", "is", "None", ":", "continue", "event_dir_dict", "[", "value", ".", "tag", "]", ".", "add", "(", "dir", ")", "except", "tf", ".", "errors", ".", "DataLossError", ":", "# DataLossError seems to happen sometimes for small logs.", "# We want to show good records regardless.", "continue", "return", "dict", "(", "event_dir_dict", ")" ]
List all scalar events in the directory. Returns: A dictionary. Key is the name of a event. Value is a set of dirs that contain that event.
[ "List", "all", "scalar", "events", "in", "the", "directory", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_summary.py#L64-L87
train
237,952
googledatalab/pydatalab
datalab/bigquery/_federated_table.py
FederatedTable.from_storage
def from_storage(source, source_format='csv', csv_options=None, ignore_unknown_values=False, max_bad_records=0, compressed=False, schema=None): """ Create an external table for a GCS object. Args: source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item name. Can be a single source or a list. source_format: the format of the data, 'csv' or 'json'; default 'csv'. csv_options: For CSV files, the options such as quote character and delimiter. ignore_unknown_values: If True, accept rows that contain values that do not match the schema; the unknown values are ignored (default False). max_bad_records: The maximum number of bad records that are allowed (and ignored) before returning an 'invalid' error in the Job result (default 0). compressed: whether the data is GZ compressed or not (default False). Note that compressed data can be used as a federated table but cannot be loaded into a BQ Table. schema: the schema of the data. This is required for this table to be used as a federated table or to be loaded using a Table object that itself has no schema (default None). """ result = FederatedTable() # Do some sanity checking and concert some params from friendly form to form used by BQ. if source_format == 'csv': result._bq_source_format = 'CSV' if csv_options is None: csv_options = _csv_options.CSVOptions() # use defaults elif source_format == 'json': if csv_options: raise Exception('CSV options are not support for JSON tables') result._bq_source_format = 'NEWLINE_DELIMITED_JSON' else: raise Exception("Invalid source format %s" % source_format) result._source = source if isinstance(source, list) else [source] result._source_format = source_format result._csv_options = csv_options result._ignore_unknown_values = ignore_unknown_values result._max_bad_records = max_bad_records result._compressed = compressed result._schema = schema return result
python
def from_storage(source, source_format='csv', csv_options=None, ignore_unknown_values=False, max_bad_records=0, compressed=False, schema=None): """ Create an external table for a GCS object. Args: source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item name. Can be a single source or a list. source_format: the format of the data, 'csv' or 'json'; default 'csv'. csv_options: For CSV files, the options such as quote character and delimiter. ignore_unknown_values: If True, accept rows that contain values that do not match the schema; the unknown values are ignored (default False). max_bad_records: The maximum number of bad records that are allowed (and ignored) before returning an 'invalid' error in the Job result (default 0). compressed: whether the data is GZ compressed or not (default False). Note that compressed data can be used as a federated table but cannot be loaded into a BQ Table. schema: the schema of the data. This is required for this table to be used as a federated table or to be loaded using a Table object that itself has no schema (default None). """ result = FederatedTable() # Do some sanity checking and concert some params from friendly form to form used by BQ. if source_format == 'csv': result._bq_source_format = 'CSV' if csv_options is None: csv_options = _csv_options.CSVOptions() # use defaults elif source_format == 'json': if csv_options: raise Exception('CSV options are not support for JSON tables') result._bq_source_format = 'NEWLINE_DELIMITED_JSON' else: raise Exception("Invalid source format %s" % source_format) result._source = source if isinstance(source, list) else [source] result._source_format = source_format result._csv_options = csv_options result._ignore_unknown_values = ignore_unknown_values result._max_bad_records = max_bad_records result._compressed = compressed result._schema = schema return result
[ "def", "from_storage", "(", "source", ",", "source_format", "=", "'csv'", ",", "csv_options", "=", "None", ",", "ignore_unknown_values", "=", "False", ",", "max_bad_records", "=", "0", ",", "compressed", "=", "False", ",", "schema", "=", "None", ")", ":", "result", "=", "FederatedTable", "(", ")", "# Do some sanity checking and concert some params from friendly form to form used by BQ.", "if", "source_format", "==", "'csv'", ":", "result", ".", "_bq_source_format", "=", "'CSV'", "if", "csv_options", "is", "None", ":", "csv_options", "=", "_csv_options", ".", "CSVOptions", "(", ")", "# use defaults", "elif", "source_format", "==", "'json'", ":", "if", "csv_options", ":", "raise", "Exception", "(", "'CSV options are not support for JSON tables'", ")", "result", ".", "_bq_source_format", "=", "'NEWLINE_DELIMITED_JSON'", "else", ":", "raise", "Exception", "(", "\"Invalid source format %s\"", "%", "source_format", ")", "result", ".", "_source", "=", "source", "if", "isinstance", "(", "source", ",", "list", ")", "else", "[", "source", "]", "result", ".", "_source_format", "=", "source_format", "result", ".", "_csv_options", "=", "csv_options", "result", ".", "_ignore_unknown_values", "=", "ignore_unknown_values", "result", ".", "_max_bad_records", "=", "max_bad_records", "result", ".", "_compressed", "=", "compressed", "result", ".", "_schema", "=", "schema", "return", "result" ]
Create an external table for a GCS object. Args: source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item name. Can be a single source or a list. source_format: the format of the data, 'csv' or 'json'; default 'csv'. csv_options: For CSV files, the options such as quote character and delimiter. ignore_unknown_values: If True, accept rows that contain values that do not match the schema; the unknown values are ignored (default False). max_bad_records: The maximum number of bad records that are allowed (and ignored) before returning an 'invalid' error in the Job result (default 0). compressed: whether the data is GZ compressed or not (default False). Note that compressed data can be used as a federated table but cannot be loaded into a BQ Table. schema: the schema of the data. This is required for this table to be used as a federated table or to be loaded using a Table object that itself has no schema (default None).
[ "Create", "an", "external", "table", "for", "a", "GCS", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_federated_table.py#L24-L64
train
237,953
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
get_query_parameters
def get_query_parameters(args, cell_body, date_time=datetime.datetime.now()): """Extract query parameters from cell body if provided Also validates the cell body schema using jsonschema to catch errors before sending the http request. This validation isn't complete, however; it does not validate recursive schemas, but it acts as a good filter against most simple schemas Args: args: arguments passed to the magic cell cell_body: body of the magic cell date_time: The timestamp at which the date-time related parameters need to be resolved. Returns: Validated object containing query parameters """ env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env=env, as_dict=False) sql = args['query'] if sql is None: raise Exception('Cannot extract query parameters in non-query cell') # Validate query_params if config: jsonschema.validate(config, BigQuerySchema.QUERY_PARAMS_SCHEMA) config = config or {} config_parameters = config.get('parameters', []) return bigquery.Query.get_query_parameters(config_parameters, date_time=date_time)
python
def get_query_parameters(args, cell_body, date_time=datetime.datetime.now()): """Extract query parameters from cell body if provided Also validates the cell body schema using jsonschema to catch errors before sending the http request. This validation isn't complete, however; it does not validate recursive schemas, but it acts as a good filter against most simple schemas Args: args: arguments passed to the magic cell cell_body: body of the magic cell date_time: The timestamp at which the date-time related parameters need to be resolved. Returns: Validated object containing query parameters """ env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env=env, as_dict=False) sql = args['query'] if sql is None: raise Exception('Cannot extract query parameters in non-query cell') # Validate query_params if config: jsonschema.validate(config, BigQuerySchema.QUERY_PARAMS_SCHEMA) config = config or {} config_parameters = config.get('parameters', []) return bigquery.Query.get_query_parameters(config_parameters, date_time=date_time)
[ "def", "get_query_parameters", "(", "args", ",", "cell_body", ",", "date_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", ":", "env", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "config", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "parse_config", "(", "cell_body", ",", "env", "=", "env", ",", "as_dict", "=", "False", ")", "sql", "=", "args", "[", "'query'", "]", "if", "sql", "is", "None", ":", "raise", "Exception", "(", "'Cannot extract query parameters in non-query cell'", ")", "# Validate query_params", "if", "config", ":", "jsonschema", ".", "validate", "(", "config", ",", "BigQuerySchema", ".", "QUERY_PARAMS_SCHEMA", ")", "config", "=", "config", "or", "{", "}", "config_parameters", "=", "config", ".", "get", "(", "'parameters'", ",", "[", "]", ")", "return", "bigquery", ".", "Query", ".", "get_query_parameters", "(", "config_parameters", ",", "date_time", "=", "date_time", ")" ]
Extract query parameters from cell body if provided Also validates the cell body schema using jsonschema to catch errors before sending the http request. This validation isn't complete, however; it does not validate recursive schemas, but it acts as a good filter against most simple schemas Args: args: arguments passed to the magic cell cell_body: body of the magic cell date_time: The timestamp at which the date-time related parameters need to be resolved. Returns: Validated object containing query parameters
[ "Extract", "query", "parameters", "from", "cell", "body", "if", "provided", "Also", "validates", "the", "cell", "body", "schema", "using", "jsonschema", "to", "catch", "errors", "before", "sending", "the", "http", "request", ".", "This", "validation", "isn", "t", "complete", "however", ";", "it", "does", "not", "validate", "recursive", "schemas", "but", "it", "acts", "as", "a", "good", "filter", "against", "most", "simple", "schemas" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L355-L382
train
237,954
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_udf_cell
def _udf_cell(args, cell_body): """Implements the Bigquery udf cell magic for ipython notebooks. The supported syntax is: %%bq udf --name <var> --language <lang> // @param <name> <type> // @returns <type> // @import <gcs_path> <js function> Args: args: the optional arguments following '%%bq udf'. cell_body: the UDF declaration (inputs and outputs) and implementation in javascript. """ udf_name = args['name'] if not udf_name: raise Exception('Declaration must be of the form %%bq udf --name <variable name>') # Parse out parameters, return type, and imports param_pattern = r'^\s*\/\/\s*@param\s+([<>\w]+)\s+([<>\w,\s]+)\s*$' returns_pattern = r'^\s*\/\/\s*@returns\s+([<>\w,\s]+)\s*$' import_pattern = r'^\s*\/\/\s*@import\s+(\S+)\s*$' params = re.findall(param_pattern, cell_body, re.MULTILINE) return_type = re.findall(returns_pattern, cell_body, re.MULTILINE) imports = re.findall(import_pattern, cell_body, re.MULTILINE) if len(return_type) < 1: raise Exception('UDF return type must be defined using // @returns <type>') if len(return_type) > 1: raise Exception('Found more than one return type definition') return_type = return_type[0] # Finally build the UDF object udf = bigquery.UDF(udf_name, cell_body, return_type, params, args['language'], imports) google.datalab.utils.commands.notebook_environment()[udf_name] = udf
python
def _udf_cell(args, cell_body): """Implements the Bigquery udf cell magic for ipython notebooks. The supported syntax is: %%bq udf --name <var> --language <lang> // @param <name> <type> // @returns <type> // @import <gcs_path> <js function> Args: args: the optional arguments following '%%bq udf'. cell_body: the UDF declaration (inputs and outputs) and implementation in javascript. """ udf_name = args['name'] if not udf_name: raise Exception('Declaration must be of the form %%bq udf --name <variable name>') # Parse out parameters, return type, and imports param_pattern = r'^\s*\/\/\s*@param\s+([<>\w]+)\s+([<>\w,\s]+)\s*$' returns_pattern = r'^\s*\/\/\s*@returns\s+([<>\w,\s]+)\s*$' import_pattern = r'^\s*\/\/\s*@import\s+(\S+)\s*$' params = re.findall(param_pattern, cell_body, re.MULTILINE) return_type = re.findall(returns_pattern, cell_body, re.MULTILINE) imports = re.findall(import_pattern, cell_body, re.MULTILINE) if len(return_type) < 1: raise Exception('UDF return type must be defined using // @returns <type>') if len(return_type) > 1: raise Exception('Found more than one return type definition') return_type = return_type[0] # Finally build the UDF object udf = bigquery.UDF(udf_name, cell_body, return_type, params, args['language'], imports) google.datalab.utils.commands.notebook_environment()[udf_name] = udf
[ "def", "_udf_cell", "(", "args", ",", "cell_body", ")", ":", "udf_name", "=", "args", "[", "'name'", "]", "if", "not", "udf_name", ":", "raise", "Exception", "(", "'Declaration must be of the form %%bq udf --name <variable name>'", ")", "# Parse out parameters, return type, and imports", "param_pattern", "=", "r'^\\s*\\/\\/\\s*@param\\s+([<>\\w]+)\\s+([<>\\w,\\s]+)\\s*$'", "returns_pattern", "=", "r'^\\s*\\/\\/\\s*@returns\\s+([<>\\w,\\s]+)\\s*$'", "import_pattern", "=", "r'^\\s*\\/\\/\\s*@import\\s+(\\S+)\\s*$'", "params", "=", "re", ".", "findall", "(", "param_pattern", ",", "cell_body", ",", "re", ".", "MULTILINE", ")", "return_type", "=", "re", ".", "findall", "(", "returns_pattern", ",", "cell_body", ",", "re", ".", "MULTILINE", ")", "imports", "=", "re", ".", "findall", "(", "import_pattern", ",", "cell_body", ",", "re", ".", "MULTILINE", ")", "if", "len", "(", "return_type", ")", "<", "1", ":", "raise", "Exception", "(", "'UDF return type must be defined using // @returns <type>'", ")", "if", "len", "(", "return_type", ")", ">", "1", ":", "raise", "Exception", "(", "'Found more than one return type definition'", ")", "return_type", "=", "return_type", "[", "0", "]", "# Finally build the UDF object", "udf", "=", "bigquery", ".", "UDF", "(", "udf_name", ",", "cell_body", ",", "return_type", ",", "params", ",", "args", "[", "'language'", "]", ",", "imports", ")", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "[", "udf_name", "]", "=", "udf" ]
Implements the Bigquery udf cell magic for ipython notebooks. The supported syntax is: %%bq udf --name <var> --language <lang> // @param <name> <type> // @returns <type> // @import <gcs_path> <js function> Args: args: the optional arguments following '%%bq udf'. cell_body: the UDF declaration (inputs and outputs) and implementation in javascript.
[ "Implements", "the", "Bigquery", "udf", "cell", "magic", "for", "ipython", "notebooks", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L480-L516
train
237,955
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_datasource_cell
def _datasource_cell(args, cell_body): """Implements the BigQuery datasource cell magic for ipython notebooks. The supported syntax is %%bq datasource --name <var> --paths <url> [--format <CSV|JSON>] <schema> Args: args: the optional arguments following '%%bq datasource' cell_body: the datasource's schema in json/yaml """ name = args['name'] paths = args['paths'] data_format = (args['format'] or 'CSV').lower() compressed = args['compressed'] or False # Get the source schema from the cell body record = google.datalab.utils.commands.parse_config( cell_body, google.datalab.utils.commands.notebook_environment(), as_dict=False) jsonschema.validate(record, BigQuerySchema.TABLE_SCHEMA_SCHEMA) schema = bigquery.Schema(record['schema']) # Finally build the datasource object datasource = bigquery.ExternalDataSource(source=paths, source_format=data_format, compressed=compressed, schema=schema) google.datalab.utils.commands.notebook_environment()[name] = datasource
python
def _datasource_cell(args, cell_body): """Implements the BigQuery datasource cell magic for ipython notebooks. The supported syntax is %%bq datasource --name <var> --paths <url> [--format <CSV|JSON>] <schema> Args: args: the optional arguments following '%%bq datasource' cell_body: the datasource's schema in json/yaml """ name = args['name'] paths = args['paths'] data_format = (args['format'] or 'CSV').lower() compressed = args['compressed'] or False # Get the source schema from the cell body record = google.datalab.utils.commands.parse_config( cell_body, google.datalab.utils.commands.notebook_environment(), as_dict=False) jsonschema.validate(record, BigQuerySchema.TABLE_SCHEMA_SCHEMA) schema = bigquery.Schema(record['schema']) # Finally build the datasource object datasource = bigquery.ExternalDataSource(source=paths, source_format=data_format, compressed=compressed, schema=schema) google.datalab.utils.commands.notebook_environment()[name] = datasource
[ "def", "_datasource_cell", "(", "args", ",", "cell_body", ")", ":", "name", "=", "args", "[", "'name'", "]", "paths", "=", "args", "[", "'paths'", "]", "data_format", "=", "(", "args", "[", "'format'", "]", "or", "'CSV'", ")", ".", "lower", "(", ")", "compressed", "=", "args", "[", "'compressed'", "]", "or", "False", "# Get the source schema from the cell body", "record", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "parse_config", "(", "cell_body", ",", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", ",", "as_dict", "=", "False", ")", "jsonschema", ".", "validate", "(", "record", ",", "BigQuerySchema", ".", "TABLE_SCHEMA_SCHEMA", ")", "schema", "=", "bigquery", ".", "Schema", "(", "record", "[", "'schema'", "]", ")", "# Finally build the datasource object", "datasource", "=", "bigquery", ".", "ExternalDataSource", "(", "source", "=", "paths", ",", "source_format", "=", "data_format", ",", "compressed", "=", "compressed", ",", "schema", "=", "schema", ")", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "[", "name", "]", "=", "datasource" ]
Implements the BigQuery datasource cell magic for ipython notebooks. The supported syntax is %%bq datasource --name <var> --paths <url> [--format <CSV|JSON>] <schema> Args: args: the optional arguments following '%%bq datasource' cell_body: the datasource's schema in json/yaml
[ "Implements", "the", "BigQuery", "datasource", "cell", "magic", "for", "ipython", "notebooks", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L519-L545
train
237,956
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_query_cell
def _query_cell(args, cell_body): """Implements the BigQuery cell magic for used to build SQL objects. The supported syntax is: %%bq query <args> [<inline SQL>] Args: args: the optional arguments following '%%bql query'. cell_body: the contents of the cell """ name = args['name'] udfs = args['udfs'] datasources = args['datasources'] subqueries = args['subqueries'] # Finally build the query object query = bigquery.Query(cell_body, env=IPython.get_ipython().user_ns, udfs=udfs, data_sources=datasources, subqueries=subqueries) # if no name is specified, execute this query instead of defining it if name is None: return query.execute().result() else: google.datalab.utils.commands.notebook_environment()[name] = query
python
def _query_cell(args, cell_body): """Implements the BigQuery cell magic for used to build SQL objects. The supported syntax is: %%bq query <args> [<inline SQL>] Args: args: the optional arguments following '%%bql query'. cell_body: the contents of the cell """ name = args['name'] udfs = args['udfs'] datasources = args['datasources'] subqueries = args['subqueries'] # Finally build the query object query = bigquery.Query(cell_body, env=IPython.get_ipython().user_ns, udfs=udfs, data_sources=datasources, subqueries=subqueries) # if no name is specified, execute this query instead of defining it if name is None: return query.execute().result() else: google.datalab.utils.commands.notebook_environment()[name] = query
[ "def", "_query_cell", "(", "args", ",", "cell_body", ")", ":", "name", "=", "args", "[", "'name'", "]", "udfs", "=", "args", "[", "'udfs'", "]", "datasources", "=", "args", "[", "'datasources'", "]", "subqueries", "=", "args", "[", "'subqueries'", "]", "# Finally build the query object", "query", "=", "bigquery", ".", "Query", "(", "cell_body", ",", "env", "=", "IPython", ".", "get_ipython", "(", ")", ".", "user_ns", ",", "udfs", "=", "udfs", ",", "data_sources", "=", "datasources", ",", "subqueries", "=", "subqueries", ")", "# if no name is specified, execute this query instead of defining it", "if", "name", "is", "None", ":", "return", "query", ".", "execute", "(", ")", ".", "result", "(", ")", "else", ":", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "[", "name", "]", "=", "query" ]
Implements the BigQuery cell magic for used to build SQL objects. The supported syntax is: %%bq query <args> [<inline SQL>] Args: args: the optional arguments following '%%bql query'. cell_body: the contents of the cell
[ "Implements", "the", "BigQuery", "cell", "magic", "for", "used", "to", "build", "SQL", "objects", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L548-L573
train
237,957
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_get_table
def _get_table(name): """ Given a variable or table name, get a Table if it exists. Args: name: the name of the Table or a variable referencing the Table. Returns: The Table, if found. """ # If name is a variable referencing a table, use that. item = google.datalab.utils.commands.get_notebook_item(name) if isinstance(item, bigquery.Table): return item # Else treat this as a BQ table name and return the (cached) table if it exists. try: return _existing_table_cache[name] except KeyError: table = bigquery.Table(name) if table.exists(): _existing_table_cache[name] = table return table return None
python
def _get_table(name): """ Given a variable or table name, get a Table if it exists. Args: name: the name of the Table or a variable referencing the Table. Returns: The Table, if found. """ # If name is a variable referencing a table, use that. item = google.datalab.utils.commands.get_notebook_item(name) if isinstance(item, bigquery.Table): return item # Else treat this as a BQ table name and return the (cached) table if it exists. try: return _existing_table_cache[name] except KeyError: table = bigquery.Table(name) if table.exists(): _existing_table_cache[name] = table return table return None
[ "def", "_get_table", "(", "name", ")", ":", "# If name is a variable referencing a table, use that.", "item", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "get_notebook_item", "(", "name", ")", "if", "isinstance", "(", "item", ",", "bigquery", ".", "Table", ")", ":", "return", "item", "# Else treat this as a BQ table name and return the (cached) table if it exists.", "try", ":", "return", "_existing_table_cache", "[", "name", "]", "except", "KeyError", ":", "table", "=", "bigquery", ".", "Table", "(", "name", ")", "if", "table", ".", "exists", "(", ")", ":", "_existing_table_cache", "[", "name", "]", "=", "table", "return", "table", "return", "None" ]
Given a variable or table name, get a Table if it exists. Args: name: the name of the Table or a variable referencing the Table. Returns: The Table, if found.
[ "Given", "a", "variable", "or", "table", "name", "get", "a", "Table", "if", "it", "exists", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L622-L642
train
237,958
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_render_list
def _render_list(data): """ Helper to render a list of objects as an HTML list object. """ return IPython.core.display.HTML(google.datalab.utils.commands.HtmlBuilder.render_list(data))
python
def _render_list(data): """ Helper to render a list of objects as an HTML list object. """ return IPython.core.display.HTML(google.datalab.utils.commands.HtmlBuilder.render_list(data))
[ "def", "_render_list", "(", "data", ")", ":", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "HtmlBuilder", ".", "render_list", "(", "data", ")", ")" ]
Helper to render a list of objects as an HTML list object.
[ "Helper", "to", "render", "a", "list", "of", "objects", "as", "an", "HTML", "list", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L645-L647
train
237,959
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_dataset_line
def _dataset_line(args): """Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'. """ if args['command'] == 'list': filter_ = args['filter'] if args['filter'] else '*' context = google.datalab.Context.default() if args['project']: context = google.datalab.Context(args['project'], context.credentials) return _render_list([str(dataset) for dataset in bigquery.Datasets(context) if fnmatch.fnmatch(str(dataset), filter_)]) elif args['command'] == 'create': try: bigquery.Dataset(args['name']).create(friendly_name=args['friendly']) except Exception as e: print('Failed to create dataset %s: %s' % (args['name'], e)) elif args['command'] == 'delete': try: bigquery.Dataset(args['name']).delete() except Exception as e: print('Failed to delete dataset %s: %s' % (args['name'], e))
python
def _dataset_line(args): """Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'. """ if args['command'] == 'list': filter_ = args['filter'] if args['filter'] else '*' context = google.datalab.Context.default() if args['project']: context = google.datalab.Context(args['project'], context.credentials) return _render_list([str(dataset) for dataset in bigquery.Datasets(context) if fnmatch.fnmatch(str(dataset), filter_)]) elif args['command'] == 'create': try: bigquery.Dataset(args['name']).create(friendly_name=args['friendly']) except Exception as e: print('Failed to create dataset %s: %s' % (args['name'], e)) elif args['command'] == 'delete': try: bigquery.Dataset(args['name']).delete() except Exception as e: print('Failed to delete dataset %s: %s' % (args['name'], e))
[ "def", "_dataset_line", "(", "args", ")", ":", "if", "args", "[", "'command'", "]", "==", "'list'", ":", "filter_", "=", "args", "[", "'filter'", "]", "if", "args", "[", "'filter'", "]", "else", "'*'", "context", "=", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", "if", "args", "[", "'project'", "]", ":", "context", "=", "google", ".", "datalab", ".", "Context", "(", "args", "[", "'project'", "]", ",", "context", ".", "credentials", ")", "return", "_render_list", "(", "[", "str", "(", "dataset", ")", "for", "dataset", "in", "bigquery", ".", "Datasets", "(", "context", ")", "if", "fnmatch", ".", "fnmatch", "(", "str", "(", "dataset", ")", ",", "filter_", ")", "]", ")", "elif", "args", "[", "'command'", "]", "==", "'create'", ":", "try", ":", "bigquery", ".", "Dataset", "(", "args", "[", "'name'", "]", ")", ".", "create", "(", "friendly_name", "=", "args", "[", "'friendly'", "]", ")", "except", "Exception", "as", "e", ":", "print", "(", "'Failed to create dataset %s: %s'", "%", "(", "args", "[", "'name'", "]", ",", "e", ")", ")", "elif", "args", "[", "'command'", "]", "==", "'delete'", ":", "try", ":", "bigquery", ".", "Dataset", "(", "args", "[", "'name'", "]", ")", ".", "delete", "(", ")", "except", "Exception", "as", "e", ":", "print", "(", "'Failed to delete dataset %s: %s'", "%", "(", "args", "[", "'name'", "]", ",", "e", ")", ")" ]
Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'.
[ "Implements", "the", "BigQuery", "dataset", "magic", "subcommand", "used", "to", "operate", "on", "datasets" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L650-L680
train
237,960
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_table_cell
def _table_cell(args, cell_body): """Implements the BigQuery table magic subcommand used to operate on tables The supported syntax is: %%bq tables <command> <args> Commands: {list, create, delete, describe, view} Args: args: the optional arguments following '%%bq tables command'. cell_body: optional contents of the cell interpreted as SQL, YAML or JSON. Returns: The HTML rendering for the table of datasets. """ if args['command'] == 'list': filter_ = args['filter'] if args['filter'] else '*' if args['dataset']: if args['project'] is None: datasets = [bigquery.Dataset(args['dataset'])] else: context = google.datalab.Context(args['project'], google.datalab.Context.default().credentials) datasets = [bigquery.Dataset(args['dataset'], context)] else: default_context = google.datalab.Context.default() context = google.datalab.Context(default_context.project_id, default_context.credentials) if args['project']: context.set_project_id(args['project']) datasets = bigquery.Datasets(context) tables = [] for dataset in datasets: tables.extend([table.full_name for table in dataset if fnmatch.fnmatch(table.full_name, filter_)]) return _render_list(tables) elif args['command'] == 'create': if cell_body is None: print('Failed to create %s: no schema specified' % args['name']) else: try: record = google.datalab.utils.commands.parse_config( cell_body, google.datalab.utils.commands.notebook_environment(), as_dict=False) jsonschema.validate(record, BigQuerySchema.TABLE_SCHEMA_SCHEMA) schema = bigquery.Schema(record['schema']) bigquery.Table(args['name']).create(schema=schema, overwrite=args['overwrite']) except Exception as e: print('Failed to create table %s: %s' % (args['name'], e)) elif args['command'] == 'describe': name = args['name'] table = _get_table(name) if not table: raise Exception('Could not find table %s' % name) html = _repr_html_table_schema(table.schema) return IPython.core.display.HTML(html) elif args['command'] == 'delete': try: bigquery.Table(args['name']).delete() except Exception as e: print('Failed to delete table %s: %s' % (args['name'], e)) elif args['command'] == 'view': name = args['name'] table = _get_table(name) if not table: raise Exception('Could not find table %s' % name) return table
python
def _table_cell(args, cell_body): """Implements the BigQuery table magic subcommand used to operate on tables The supported syntax is: %%bq tables <command> <args> Commands: {list, create, delete, describe, view} Args: args: the optional arguments following '%%bq tables command'. cell_body: optional contents of the cell interpreted as SQL, YAML or JSON. Returns: The HTML rendering for the table of datasets. """ if args['command'] == 'list': filter_ = args['filter'] if args['filter'] else '*' if args['dataset']: if args['project'] is None: datasets = [bigquery.Dataset(args['dataset'])] else: context = google.datalab.Context(args['project'], google.datalab.Context.default().credentials) datasets = [bigquery.Dataset(args['dataset'], context)] else: default_context = google.datalab.Context.default() context = google.datalab.Context(default_context.project_id, default_context.credentials) if args['project']: context.set_project_id(args['project']) datasets = bigquery.Datasets(context) tables = [] for dataset in datasets: tables.extend([table.full_name for table in dataset if fnmatch.fnmatch(table.full_name, filter_)]) return _render_list(tables) elif args['command'] == 'create': if cell_body is None: print('Failed to create %s: no schema specified' % args['name']) else: try: record = google.datalab.utils.commands.parse_config( cell_body, google.datalab.utils.commands.notebook_environment(), as_dict=False) jsonschema.validate(record, BigQuerySchema.TABLE_SCHEMA_SCHEMA) schema = bigquery.Schema(record['schema']) bigquery.Table(args['name']).create(schema=schema, overwrite=args['overwrite']) except Exception as e: print('Failed to create table %s: %s' % (args['name'], e)) elif args['command'] == 'describe': name = args['name'] table = _get_table(name) if not table: raise Exception('Could not find table %s' % name) html = _repr_html_table_schema(table.schema) return IPython.core.display.HTML(html) elif args['command'] == 'delete': try: bigquery.Table(args['name']).delete() except Exception as e: print('Failed to delete table %s: %s' % (args['name'], e)) elif args['command'] == 'view': name = args['name'] table = _get_table(name) if not table: raise Exception('Could not find table %s' % name) return table
[ "def", "_table_cell", "(", "args", ",", "cell_body", ")", ":", "if", "args", "[", "'command'", "]", "==", "'list'", ":", "filter_", "=", "args", "[", "'filter'", "]", "if", "args", "[", "'filter'", "]", "else", "'*'", "if", "args", "[", "'dataset'", "]", ":", "if", "args", "[", "'project'", "]", "is", "None", ":", "datasets", "=", "[", "bigquery", ".", "Dataset", "(", "args", "[", "'dataset'", "]", ")", "]", "else", ":", "context", "=", "google", ".", "datalab", ".", "Context", "(", "args", "[", "'project'", "]", ",", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", ".", "credentials", ")", "datasets", "=", "[", "bigquery", ".", "Dataset", "(", "args", "[", "'dataset'", "]", ",", "context", ")", "]", "else", ":", "default_context", "=", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", "context", "=", "google", ".", "datalab", ".", "Context", "(", "default_context", ".", "project_id", ",", "default_context", ".", "credentials", ")", "if", "args", "[", "'project'", "]", ":", "context", ".", "set_project_id", "(", "args", "[", "'project'", "]", ")", "datasets", "=", "bigquery", ".", "Datasets", "(", "context", ")", "tables", "=", "[", "]", "for", "dataset", "in", "datasets", ":", "tables", ".", "extend", "(", "[", "table", ".", "full_name", "for", "table", "in", "dataset", "if", "fnmatch", ".", "fnmatch", "(", "table", ".", "full_name", ",", "filter_", ")", "]", ")", "return", "_render_list", "(", "tables", ")", "elif", "args", "[", "'command'", "]", "==", "'create'", ":", "if", "cell_body", "is", "None", ":", "print", "(", "'Failed to create %s: no schema specified'", "%", "args", "[", "'name'", "]", ")", "else", ":", "try", ":", "record", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "parse_config", "(", "cell_body", ",", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", ",", "as_dict", "=", "False", ")", "jsonschema", ".", "validate", "(", "record", ",", "BigQuerySchema", ".", "TABLE_SCHEMA_SCHEMA", ")", "schema", "=", "bigquery", ".", "Schema", "(", "record", "[", "'schema'", "]", ")", "bigquery", ".", "Table", "(", "args", "[", "'name'", "]", ")", ".", "create", "(", "schema", "=", "schema", ",", "overwrite", "=", "args", "[", "'overwrite'", "]", ")", "except", "Exception", "as", "e", ":", "print", "(", "'Failed to create table %s: %s'", "%", "(", "args", "[", "'name'", "]", ",", "e", ")", ")", "elif", "args", "[", "'command'", "]", "==", "'describe'", ":", "name", "=", "args", "[", "'name'", "]", "table", "=", "_get_table", "(", "name", ")", "if", "not", "table", ":", "raise", "Exception", "(", "'Could not find table %s'", "%", "name", ")", "html", "=", "_repr_html_table_schema", "(", "table", ".", "schema", ")", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "html", ")", "elif", "args", "[", "'command'", "]", "==", "'delete'", ":", "try", ":", "bigquery", ".", "Table", "(", "args", "[", "'name'", "]", ")", ".", "delete", "(", ")", "except", "Exception", "as", "e", ":", "print", "(", "'Failed to delete table %s: %s'", "%", "(", "args", "[", "'name'", "]", ",", "e", ")", ")", "elif", "args", "[", "'command'", "]", "==", "'view'", ":", "name", "=", "args", "[", "'name'", "]", "table", "=", "_get_table", "(", "name", ")", "if", "not", "table", ":", "raise", "Exception", "(", "'Could not find table %s'", "%", "name", ")", "return", "table" ]
Implements the BigQuery table magic subcommand used to operate on tables The supported syntax is: %%bq tables <command> <args> Commands: {list, create, delete, describe, view} Args: args: the optional arguments following '%%bq tables command'. cell_body: optional contents of the cell interpreted as SQL, YAML or JSON. Returns: The HTML rendering for the table of datasets.
[ "Implements", "the", "BigQuery", "table", "magic", "subcommand", "used", "to", "operate", "on", "tables" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L683-L754
train
237,961
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_extract_cell
def _extract_cell(args, cell_body): """Implements the BigQuery extract magic used to extract query or table data to GCS. The supported syntax is: %bq extract <args> Args: args: the arguments following '%bigquery extract'. """ env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {} parameters = config.get('parameters') if args['table']: table = google.datalab.bigquery.Query.resolve_parameters(args['table'], parameters) source = _get_table(table) if not source: raise Exception('Could not find table %s' % table) csv_delimiter = args['delimiter'] if args['format'] == 'csv' else None path = google.datalab.bigquery.Query.resolve_parameters(args['path'], parameters) job = source.extract(path, format=args['format'], csv_delimiter=csv_delimiter, csv_header=args['header'], compress=args['compress']) elif args['query'] or args['view']: source_name = args['view'] or args['query'] source = google.datalab.utils.commands.get_notebook_item(source_name) if not source: raise Exception('Could not find ' + ('view ' + args['view'] if args['view'] else 'query ' + args['query'])) query = source if args['query'] else bigquery.Query.from_view(source) query_params = get_query_parameters(args, cell_body) if args['query'] else None output_options = QueryOutput.file(path=args['path'], format=args['format'], csv_delimiter=args['delimiter'], csv_header=args['header'], compress=args['compress'], use_cache=not args['nocache']) context = google.datalab.utils._utils._construct_context_for_args(args) job = query.execute(output_options, context=context, query_params=query_params) else: raise Exception('A query, table, or view is needed to extract') if job.failed: raise Exception('Extract failed: %s' % str(job.fatal_error)) elif job.errors: raise Exception('Extract completed with errors: %s' % str(job.errors)) return job.result()
python
def _extract_cell(args, cell_body): """Implements the BigQuery extract magic used to extract query or table data to GCS. The supported syntax is: %bq extract <args> Args: args: the arguments following '%bigquery extract'. """ env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {} parameters = config.get('parameters') if args['table']: table = google.datalab.bigquery.Query.resolve_parameters(args['table'], parameters) source = _get_table(table) if not source: raise Exception('Could not find table %s' % table) csv_delimiter = args['delimiter'] if args['format'] == 'csv' else None path = google.datalab.bigquery.Query.resolve_parameters(args['path'], parameters) job = source.extract(path, format=args['format'], csv_delimiter=csv_delimiter, csv_header=args['header'], compress=args['compress']) elif args['query'] or args['view']: source_name = args['view'] or args['query'] source = google.datalab.utils.commands.get_notebook_item(source_name) if not source: raise Exception('Could not find ' + ('view ' + args['view'] if args['view'] else 'query ' + args['query'])) query = source if args['query'] else bigquery.Query.from_view(source) query_params = get_query_parameters(args, cell_body) if args['query'] else None output_options = QueryOutput.file(path=args['path'], format=args['format'], csv_delimiter=args['delimiter'], csv_header=args['header'], compress=args['compress'], use_cache=not args['nocache']) context = google.datalab.utils._utils._construct_context_for_args(args) job = query.execute(output_options, context=context, query_params=query_params) else: raise Exception('A query, table, or view is needed to extract') if job.failed: raise Exception('Extract failed: %s' % str(job.fatal_error)) elif job.errors: raise Exception('Extract completed with errors: %s' % str(job.errors)) return job.result()
[ "def", "_extract_cell", "(", "args", ",", "cell_body", ")", ":", "env", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "config", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "parse_config", "(", "cell_body", ",", "env", ",", "False", ")", "or", "{", "}", "parameters", "=", "config", ".", "get", "(", "'parameters'", ")", "if", "args", "[", "'table'", "]", ":", "table", "=", "google", ".", "datalab", ".", "bigquery", ".", "Query", ".", "resolve_parameters", "(", "args", "[", "'table'", "]", ",", "parameters", ")", "source", "=", "_get_table", "(", "table", ")", "if", "not", "source", ":", "raise", "Exception", "(", "'Could not find table %s'", "%", "table", ")", "csv_delimiter", "=", "args", "[", "'delimiter'", "]", "if", "args", "[", "'format'", "]", "==", "'csv'", "else", "None", "path", "=", "google", ".", "datalab", ".", "bigquery", ".", "Query", ".", "resolve_parameters", "(", "args", "[", "'path'", "]", ",", "parameters", ")", "job", "=", "source", ".", "extract", "(", "path", ",", "format", "=", "args", "[", "'format'", "]", ",", "csv_delimiter", "=", "csv_delimiter", ",", "csv_header", "=", "args", "[", "'header'", "]", ",", "compress", "=", "args", "[", "'compress'", "]", ")", "elif", "args", "[", "'query'", "]", "or", "args", "[", "'view'", "]", ":", "source_name", "=", "args", "[", "'view'", "]", "or", "args", "[", "'query'", "]", "source", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "get_notebook_item", "(", "source_name", ")", "if", "not", "source", ":", "raise", "Exception", "(", "'Could not find '", "+", "(", "'view '", "+", "args", "[", "'view'", "]", "if", "args", "[", "'view'", "]", "else", "'query '", "+", "args", "[", "'query'", "]", ")", ")", "query", "=", "source", "if", "args", "[", "'query'", "]", "else", "bigquery", ".", "Query", ".", "from_view", "(", "source", ")", "query_params", "=", "get_query_parameters", "(", "args", ",", "cell_body", ")", "if", "args", "[", "'query'", "]", "else", "None", "output_options", "=", "QueryOutput", ".", "file", "(", "path", "=", "args", "[", "'path'", "]", ",", "format", "=", "args", "[", "'format'", "]", ",", "csv_delimiter", "=", "args", "[", "'delimiter'", "]", ",", "csv_header", "=", "args", "[", "'header'", "]", ",", "compress", "=", "args", "[", "'compress'", "]", ",", "use_cache", "=", "not", "args", "[", "'nocache'", "]", ")", "context", "=", "google", ".", "datalab", ".", "utils", ".", "_utils", ".", "_construct_context_for_args", "(", "args", ")", "job", "=", "query", ".", "execute", "(", "output_options", ",", "context", "=", "context", ",", "query_params", "=", "query_params", ")", "else", ":", "raise", "Exception", "(", "'A query, table, or view is needed to extract'", ")", "if", "job", ".", "failed", ":", "raise", "Exception", "(", "'Extract failed: %s'", "%", "str", "(", "job", ".", "fatal_error", ")", ")", "elif", "job", ".", "errors", ":", "raise", "Exception", "(", "'Extract completed with errors: %s'", "%", "str", "(", "job", ".", "errors", ")", ")", "return", "job", ".", "result", "(", ")" ]
Implements the BigQuery extract magic used to extract query or table data to GCS. The supported syntax is: %bq extract <args> Args: args: the arguments following '%bigquery extract'.
[ "Implements", "the", "BigQuery", "extract", "magic", "used", "to", "extract", "query", "or", "table", "data", "to", "GCS", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L757-L802
train
237,962
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
bq
def bq(line, cell=None): """Implements the bq cell magic for ipython notebooks. The supported syntax is: %%bq <command> [<args>] <cell> or: %bq <command> [<args>] Use %bq --help for a list of commands, or %bq <command> --help for help on a specific command. """ return google.datalab.utils.commands.handle_magic_line(line, cell, _bigquery_parser)
python
def bq(line, cell=None): """Implements the bq cell magic for ipython notebooks. The supported syntax is: %%bq <command> [<args>] <cell> or: %bq <command> [<args>] Use %bq --help for a list of commands, or %bq <command> --help for help on a specific command. """ return google.datalab.utils.commands.handle_magic_line(line, cell, _bigquery_parser)
[ "def", "bq", "(", "line", ",", "cell", "=", "None", ")", ":", "return", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "handle_magic_line", "(", "line", ",", "cell", ",", "_bigquery_parser", ")" ]
Implements the bq cell magic for ipython notebooks. The supported syntax is: %%bq <command> [<args>] <cell> or: %bq <command> [<args>] Use %bq --help for a list of commands, or %bq <command> --help for help on a specific command.
[ "Implements", "the", "bq", "cell", "magic", "for", "ipython", "notebooks", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L1028-L1043
train
237,963
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_table_viewer
def _table_viewer(table, rows_per_page=25, fields=None): """ Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per_page: how many rows to display at one time. fields: an array of field names to display; default is None which uses the full schema. Returns: A string containing the HTML for the table viewer. """ # TODO(gram): rework this to use google.datalab.utils.commands.chart_html if not table.exists(): raise Exception('Table %s does not exist' % table.full_name) if not table.is_listable(): return "Done" _HTML_TEMPLATE = u""" <div class="bqtv" id="{div_id}">{static_table}</div> <br />{meta_data}<br /> <script src="/static/components/requirejs/require.js"></script> <script> require.config({{ paths: {{ base: '/static/base', d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3', plotly: 'https://cdn.plot.ly/plotly-1.5.1.min.js?noext', jquery: '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min' }}, map: {{ '*': {{ datalab: 'nbextensions/gcpdatalab' }} }}, shim: {{ plotly: {{ deps: ['d3', 'jquery'], exports: 'plotly' }} }} }}); require(['datalab/charting', 'datalab/element!{div_id}', 'base/js/events', 'datalab/style!/nbextensions/gcpdatalab/charting.css'], function(charts, dom, events) {{ charts.render('gcharts', dom, events, '{chart_style}', [], {data}, {{ pageSize: {rows_per_page}, cssClassNames: {{ tableRow: 'gchart-table-row', headerRow: 'gchart-table-headerrow', oddTableRow: 'gchart-table-oddrow', selectedTableRow: 'gchart-table-selectedrow', hoverTableRow: 'gchart-table-hoverrow', tableCell: 'gchart-table-cell', headerCell: 'gchart-table-headercell', rowNumberCell: 'gchart-table-rownumcell' }} }}, {{source_index: {source_index}, fields: '{fields}'}}, 0, {total_rows}); }} ); </script> """ if fields is None: fields = google.datalab.utils.commands.get_field_list(fields, table.schema) div_id = google.datalab.utils.commands.Html.next_id() meta_count = ('rows: %d' % table.length) if table.length >= 0 else '' meta_name = table.full_name if table.job is None else ('job: %s' % table.job.id) if table.job: if table.job.cache_hit: meta_cost = 'cached' else: bytes = bigquery._query_stats.QueryStats._size_formatter(table.job.bytes_processed) meta_cost = '%s processed' % bytes meta_time = 'time: %.1fs' % table.job.total_time else: meta_cost = '' meta_time = '' data, total_count = google.datalab.utils.commands.get_data(table, fields, first_row=0, count=rows_per_page) if total_count < 0: # The table doesn't have a length metadata property but may still be small if we fetched less # rows than we asked for. fetched_count = len(data['rows']) if fetched_count < rows_per_page: total_count = fetched_count chart = 'table' if 0 <= total_count <= rows_per_page else 'paged_table' meta_entries = [meta_count, meta_time, meta_cost, meta_name] meta_data = '(%s)' % (', '.join([entry for entry in meta_entries if len(entry)])) return _HTML_TEMPLATE.format(div_id=div_id, static_table=google.datalab.utils.commands.HtmlBuilder .render_chart_data(data), meta_data=meta_data, chart_style=chart, source_index=google.datalab.utils.commands .get_data_source_index(table.full_name), fields=','.join(fields), total_rows=total_count, rows_per_page=rows_per_page, data=json.dumps(data, cls=google.datalab.utils.JSONEncoder))
python
def _table_viewer(table, rows_per_page=25, fields=None): """ Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per_page: how many rows to display at one time. fields: an array of field names to display; default is None which uses the full schema. Returns: A string containing the HTML for the table viewer. """ # TODO(gram): rework this to use google.datalab.utils.commands.chart_html if not table.exists(): raise Exception('Table %s does not exist' % table.full_name) if not table.is_listable(): return "Done" _HTML_TEMPLATE = u""" <div class="bqtv" id="{div_id}">{static_table}</div> <br />{meta_data}<br /> <script src="/static/components/requirejs/require.js"></script> <script> require.config({{ paths: {{ base: '/static/base', d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3', plotly: 'https://cdn.plot.ly/plotly-1.5.1.min.js?noext', jquery: '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min' }}, map: {{ '*': {{ datalab: 'nbextensions/gcpdatalab' }} }}, shim: {{ plotly: {{ deps: ['d3', 'jquery'], exports: 'plotly' }} }} }}); require(['datalab/charting', 'datalab/element!{div_id}', 'base/js/events', 'datalab/style!/nbextensions/gcpdatalab/charting.css'], function(charts, dom, events) {{ charts.render('gcharts', dom, events, '{chart_style}', [], {data}, {{ pageSize: {rows_per_page}, cssClassNames: {{ tableRow: 'gchart-table-row', headerRow: 'gchart-table-headerrow', oddTableRow: 'gchart-table-oddrow', selectedTableRow: 'gchart-table-selectedrow', hoverTableRow: 'gchart-table-hoverrow', tableCell: 'gchart-table-cell', headerCell: 'gchart-table-headercell', rowNumberCell: 'gchart-table-rownumcell' }} }}, {{source_index: {source_index}, fields: '{fields}'}}, 0, {total_rows}); }} ); </script> """ if fields is None: fields = google.datalab.utils.commands.get_field_list(fields, table.schema) div_id = google.datalab.utils.commands.Html.next_id() meta_count = ('rows: %d' % table.length) if table.length >= 0 else '' meta_name = table.full_name if table.job is None else ('job: %s' % table.job.id) if table.job: if table.job.cache_hit: meta_cost = 'cached' else: bytes = bigquery._query_stats.QueryStats._size_formatter(table.job.bytes_processed) meta_cost = '%s processed' % bytes meta_time = 'time: %.1fs' % table.job.total_time else: meta_cost = '' meta_time = '' data, total_count = google.datalab.utils.commands.get_data(table, fields, first_row=0, count=rows_per_page) if total_count < 0: # The table doesn't have a length metadata property but may still be small if we fetched less # rows than we asked for. fetched_count = len(data['rows']) if fetched_count < rows_per_page: total_count = fetched_count chart = 'table' if 0 <= total_count <= rows_per_page else 'paged_table' meta_entries = [meta_count, meta_time, meta_cost, meta_name] meta_data = '(%s)' % (', '.join([entry for entry in meta_entries if len(entry)])) return _HTML_TEMPLATE.format(div_id=div_id, static_table=google.datalab.utils.commands.HtmlBuilder .render_chart_data(data), meta_data=meta_data, chart_style=chart, source_index=google.datalab.utils.commands .get_data_source_index(table.full_name), fields=','.join(fields), total_rows=total_count, rows_per_page=rows_per_page, data=json.dumps(data, cls=google.datalab.utils.JSONEncoder))
[ "def", "_table_viewer", "(", "table", ",", "rows_per_page", "=", "25", ",", "fields", "=", "None", ")", ":", "# TODO(gram): rework this to use google.datalab.utils.commands.chart_html", "if", "not", "table", ".", "exists", "(", ")", ":", "raise", "Exception", "(", "'Table %s does not exist'", "%", "table", ".", "full_name", ")", "if", "not", "table", ".", "is_listable", "(", ")", ":", "return", "\"Done\"", "_HTML_TEMPLATE", "=", "u\"\"\"\n <div class=\"bqtv\" id=\"{div_id}\">{static_table}</div>\n <br />{meta_data}<br />\n <script src=\"/static/components/requirejs/require.js\"></script>\n <script>\n require.config({{\n paths: {{\n base: '/static/base',\n d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3',\n plotly: 'https://cdn.plot.ly/plotly-1.5.1.min.js?noext',\n jquery: '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min'\n }},\n map: {{\n '*': {{\n datalab: 'nbextensions/gcpdatalab'\n }}\n }},\n shim: {{\n plotly: {{\n deps: ['d3', 'jquery'],\n exports: 'plotly'\n }}\n }}\n }});\n\n require(['datalab/charting', 'datalab/element!{div_id}', 'base/js/events',\n 'datalab/style!/nbextensions/gcpdatalab/charting.css'],\n function(charts, dom, events) {{\n charts.render('gcharts', dom, events, '{chart_style}', [], {data},\n {{\n pageSize: {rows_per_page},\n cssClassNames: {{\n tableRow: 'gchart-table-row',\n headerRow: 'gchart-table-headerrow',\n oddTableRow: 'gchart-table-oddrow',\n selectedTableRow: 'gchart-table-selectedrow',\n hoverTableRow: 'gchart-table-hoverrow',\n tableCell: 'gchart-table-cell',\n headerCell: 'gchart-table-headercell',\n rowNumberCell: 'gchart-table-rownumcell'\n }}\n }},\n {{source_index: {source_index}, fields: '{fields}'}},\n 0,\n {total_rows});\n }}\n );\n </script>\n \"\"\"", "if", "fields", "is", "None", ":", "fields", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "get_field_list", "(", "fields", ",", "table", ".", "schema", ")", "div_id", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "Html", ".", "next_id", "(", ")", "meta_count", "=", "(", "'rows: %d'", "%", "table", ".", "length", ")", "if", "table", ".", "length", ">=", "0", "else", "''", "meta_name", "=", "table", ".", "full_name", "if", "table", ".", "job", "is", "None", "else", "(", "'job: %s'", "%", "table", ".", "job", ".", "id", ")", "if", "table", ".", "job", ":", "if", "table", ".", "job", ".", "cache_hit", ":", "meta_cost", "=", "'cached'", "else", ":", "bytes", "=", "bigquery", ".", "_query_stats", ".", "QueryStats", ".", "_size_formatter", "(", "table", ".", "job", ".", "bytes_processed", ")", "meta_cost", "=", "'%s processed'", "%", "bytes", "meta_time", "=", "'time: %.1fs'", "%", "table", ".", "job", ".", "total_time", "else", ":", "meta_cost", "=", "''", "meta_time", "=", "''", "data", ",", "total_count", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "get_data", "(", "table", ",", "fields", ",", "first_row", "=", "0", ",", "count", "=", "rows_per_page", ")", "if", "total_count", "<", "0", ":", "# The table doesn't have a length metadata property but may still be small if we fetched less", "# rows than we asked for.", "fetched_count", "=", "len", "(", "data", "[", "'rows'", "]", ")", "if", "fetched_count", "<", "rows_per_page", ":", "total_count", "=", "fetched_count", "chart", "=", "'table'", "if", "0", "<=", "total_count", "<=", "rows_per_page", "else", "'paged_table'", "meta_entries", "=", "[", "meta_count", ",", "meta_time", ",", "meta_cost", ",", "meta_name", "]", "meta_data", "=", "'(%s)'", "%", "(", "', '", ".", "join", "(", "[", "entry", "for", "entry", "in", "meta_entries", "if", "len", "(", "entry", ")", "]", ")", ")", "return", "_HTML_TEMPLATE", ".", "format", "(", "div_id", "=", "div_id", ",", "static_table", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "HtmlBuilder", ".", "render_chart_data", "(", "data", ")", ",", "meta_data", "=", "meta_data", ",", "chart_style", "=", "chart", ",", "source_index", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "get_data_source_index", "(", "table", ".", "full_name", ")", ",", "fields", "=", "','", ".", "join", "(", "fields", ")", ",", "total_rows", "=", "total_count", ",", "rows_per_page", "=", "rows_per_page", ",", "data", "=", "json", ".", "dumps", "(", "data", ",", "cls", "=", "google", ".", "datalab", ".", "utils", ".", "JSONEncoder", ")", ")" ]
Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per_page: how many rows to display at one time. fields: an array of field names to display; default is None which uses the full schema. Returns: A string containing the HTML for the table viewer.
[ "Return", "a", "table", "viewer", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L1074-L1186
train
237,964
googledatalab/pydatalab
datalab/bigquery/_udf.py
UDF._build_js
def _build_js(inputs, outputs, name, implementation, support_code): """Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of the function implementation: a javascript function defining the UDF logic. support_code: additional javascript code that the function can use. """ # Construct a comma-separated list of input field names # For example, field1,field2,... input_fields = json.dumps([f[0] for f in inputs]) # Construct a json representation of the output schema # For example, [{'name':'field1','type':'string'},...] output_fields = [{'name': f[0], 'type': f[1]} for f in outputs] output_fields = json.dumps(output_fields, sort_keys=True) # Build the JS from the individual bits with proper escaping of the implementation if support_code is None: support_code = '' return ('{code}\n{name}={implementation};\nbigquery.defineFunction(\'{name}\', {inputs}, ' '{outputs}, {name});').format(code=support_code, name=name, implementation=implementation, inputs=str(input_fields), outputs=str(output_fields))
python
def _build_js(inputs, outputs, name, implementation, support_code): """Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of the function implementation: a javascript function defining the UDF logic. support_code: additional javascript code that the function can use. """ # Construct a comma-separated list of input field names # For example, field1,field2,... input_fields = json.dumps([f[0] for f in inputs]) # Construct a json representation of the output schema # For example, [{'name':'field1','type':'string'},...] output_fields = [{'name': f[0], 'type': f[1]} for f in outputs] output_fields = json.dumps(output_fields, sort_keys=True) # Build the JS from the individual bits with proper escaping of the implementation if support_code is None: support_code = '' return ('{code}\n{name}={implementation};\nbigquery.defineFunction(\'{name}\', {inputs}, ' '{outputs}, {name});').format(code=support_code, name=name, implementation=implementation, inputs=str(input_fields), outputs=str(output_fields))
[ "def", "_build_js", "(", "inputs", ",", "outputs", ",", "name", ",", "implementation", ",", "support_code", ")", ":", "# Construct a comma-separated list of input field names", "# For example, field1,field2,...", "input_fields", "=", "json", ".", "dumps", "(", "[", "f", "[", "0", "]", "for", "f", "in", "inputs", "]", ")", "# Construct a json representation of the output schema", "# For example, [{'name':'field1','type':'string'},...]", "output_fields", "=", "[", "{", "'name'", ":", "f", "[", "0", "]", ",", "'type'", ":", "f", "[", "1", "]", "}", "for", "f", "in", "outputs", "]", "output_fields", "=", "json", ".", "dumps", "(", "output_fields", ",", "sort_keys", "=", "True", ")", "# Build the JS from the individual bits with proper escaping of the implementation", "if", "support_code", "is", "None", ":", "support_code", "=", "''", "return", "(", "'{code}\\n{name}={implementation};\\nbigquery.defineFunction(\\'{name}\\', {inputs}, '", "'{outputs}, {name});'", ")", ".", "format", "(", "code", "=", "support_code", ",", "name", "=", "name", ",", "implementation", "=", "implementation", ",", "inputs", "=", "str", "(", "input_fields", ")", ",", "outputs", "=", "str", "(", "output_fields", ")", ")" ]
Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of the function implementation: a javascript function defining the UDF logic. support_code: additional javascript code that the function can use.
[ "Creates", "a", "BigQuery", "SQL", "UDF", "javascript", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_udf.py#L59-L84
train
237,965
googledatalab/pydatalab
datalab/bigquery/_sampling.py
Sampling.sampling_query
def sampling_query(sql, fields=None, count=5, sampling=None): """Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. Returns: A SQL query string for sampling the input sql. """ if sampling is None: sampling = Sampling.default(count=count, fields=fields) return sampling(sql)
python
def sampling_query(sql, fields=None, count=5, sampling=None): """Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. Returns: A SQL query string for sampling the input sql. """ if sampling is None: sampling = Sampling.default(count=count, fields=fields) return sampling(sql)
[ "def", "sampling_query", "(", "sql", ",", "fields", "=", "None", ",", "count", "=", "5", ",", "sampling", "=", "None", ")", ":", "if", "sampling", "is", "None", ":", "sampling", "=", "Sampling", ".", "default", "(", "count", "=", "count", ",", "fields", "=", "fields", ")", "return", "sampling", "(", "sql", ")" ]
Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. Returns: A SQL query string for sampling the input sql.
[ "Returns", "a", "sampling", "query", "for", "the", "SQL", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_sampling.py#L74-L88
train
237,966
googledatalab/pydatalab
google/datalab/ml/_fasets.py
FacetsOverview._remove_nonascii
def _remove_nonascii(self, df): """Make copy and remove non-ascii characters from it.""" df_copy = df.copy(deep=True) for col in df_copy.columns: if (df_copy[col].dtype == np.dtype('O')): df_copy[col] = df[col].apply( lambda x: re.sub(r'[^\x00-\x7f]', r'', x) if isinstance(x, six.string_types) else x) return df_copy
python
def _remove_nonascii(self, df): """Make copy and remove non-ascii characters from it.""" df_copy = df.copy(deep=True) for col in df_copy.columns: if (df_copy[col].dtype == np.dtype('O')): df_copy[col] = df[col].apply( lambda x: re.sub(r'[^\x00-\x7f]', r'', x) if isinstance(x, six.string_types) else x) return df_copy
[ "def", "_remove_nonascii", "(", "self", ",", "df", ")", ":", "df_copy", "=", "df", ".", "copy", "(", "deep", "=", "True", ")", "for", "col", "in", "df_copy", ".", "columns", ":", "if", "(", "df_copy", "[", "col", "]", ".", "dtype", "==", "np", ".", "dtype", "(", "'O'", ")", ")", ":", "df_copy", "[", "col", "]", "=", "df", "[", "col", "]", ".", "apply", "(", "lambda", "x", ":", "re", ".", "sub", "(", "r'[^\\x00-\\x7f]'", ",", "r''", ",", "x", ")", "if", "isinstance", "(", "x", ",", "six", ".", "string_types", ")", "else", "x", ")", "return", "df_copy" ]
Make copy and remove non-ascii characters from it.
[ "Make", "copy", "and", "remove", "non", "-", "ascii", "characters", "from", "it", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_fasets.py#L27-L36
train
237,967
googledatalab/pydatalab
google/datalab/ml/_fasets.py
FacetsOverview.plot
def plot(self, data): """ Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe. """ import IPython if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()): raise ValueError('Expect a dictionary where the values are all dataframes.') gfsg = GenericFeatureStatisticsGenerator() data = [{'name': k, 'table': self._remove_nonascii(v)} for k, v in six.iteritems(data)] data_proto = gfsg.ProtoFromDataFrames(data) protostr = base64.b64encode(data_proto.SerializeToString()).decode("utf-8") html_id = 'f' + datalab.utils.commands.Html.next_id() HTML_TEMPLATE = """<link rel="import" href="/nbextensions/gcpdatalab/extern/facets-jupyter.html" > <facets-overview id="{html_id}"></facets-overview> <script> document.querySelector("#{html_id}").protoInput = "{protostr}"; </script>""" html = HTML_TEMPLATE.format(html_id=html_id, protostr=protostr) return IPython.core.display.HTML(html)
python
def plot(self, data): """ Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe. """ import IPython if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()): raise ValueError('Expect a dictionary where the values are all dataframes.') gfsg = GenericFeatureStatisticsGenerator() data = [{'name': k, 'table': self._remove_nonascii(v)} for k, v in six.iteritems(data)] data_proto = gfsg.ProtoFromDataFrames(data) protostr = base64.b64encode(data_proto.SerializeToString()).decode("utf-8") html_id = 'f' + datalab.utils.commands.Html.next_id() HTML_TEMPLATE = """<link rel="import" href="/nbextensions/gcpdatalab/extern/facets-jupyter.html" > <facets-overview id="{html_id}"></facets-overview> <script> document.querySelector("#{html_id}").protoInput = "{protostr}"; </script>""" html = HTML_TEMPLATE.format(html_id=html_id, protostr=protostr) return IPython.core.display.HTML(html)
[ "def", "plot", "(", "self", ",", "data", ")", ":", "import", "IPython", "if", "not", "isinstance", "(", "data", ",", "dict", ")", "or", "not", "all", "(", "isinstance", "(", "v", ",", "pd", ".", "DataFrame", ")", "for", "v", "in", "data", ".", "values", "(", ")", ")", ":", "raise", "ValueError", "(", "'Expect a dictionary where the values are all dataframes.'", ")", "gfsg", "=", "GenericFeatureStatisticsGenerator", "(", ")", "data", "=", "[", "{", "'name'", ":", "k", ",", "'table'", ":", "self", ".", "_remove_nonascii", "(", "v", ")", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "data", ")", "]", "data_proto", "=", "gfsg", ".", "ProtoFromDataFrames", "(", "data", ")", "protostr", "=", "base64", ".", "b64encode", "(", "data_proto", ".", "SerializeToString", "(", ")", ")", ".", "decode", "(", "\"utf-8\"", ")", "html_id", "=", "'f'", "+", "datalab", ".", "utils", ".", "commands", ".", "Html", ".", "next_id", "(", ")", "HTML_TEMPLATE", "=", "\"\"\"<link rel=\"import\" href=\"/nbextensions/gcpdatalab/extern/facets-jupyter.html\" >\n <facets-overview id=\"{html_id}\"></facets-overview>\n <script>\n document.querySelector(\"#{html_id}\").protoInput = \"{protostr}\";\n </script>\"\"\"", "html", "=", "HTML_TEMPLATE", ".", "format", "(", "html_id", "=", "html_id", ",", "protostr", "=", "protostr", ")", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "html", ")" ]
Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe.
[ "Plots", "an", "overview", "in", "a", "list", "of", "dataframes" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_fasets.py#L38-L62
train
237,968
googledatalab/pydatalab
google/datalab/ml/_fasets.py
FacetsDiveview.plot
def plot(self, data, height=1000, render_large_data=False): """ Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output. """ import IPython if not isinstance(data, pd.DataFrame): raise ValueError('Expect a DataFrame.') if (len(data) > 10000 and not render_large_data): raise ValueError('Facets dive may not work well with more than 10000 rows. ' + 'Reduce data or set "render_large_data" to True.') jsonstr = data.to_json(orient='records') html_id = 'f' + datalab.utils.commands.Html.next_id() HTML_TEMPLATE = """ <link rel="import" href="/nbextensions/gcpdatalab/extern/facets-jupyter.html"> <facets-dive id="{html_id}" height="{height}"></facets-dive> <script> var data = {jsonstr}; document.querySelector("#{html_id}").data = data; </script>""" html = HTML_TEMPLATE.format(html_id=html_id, jsonstr=jsonstr, height=height) return IPython.core.display.HTML(html)
python
def plot(self, data, height=1000, render_large_data=False): """ Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output. """ import IPython if not isinstance(data, pd.DataFrame): raise ValueError('Expect a DataFrame.') if (len(data) > 10000 and not render_large_data): raise ValueError('Facets dive may not work well with more than 10000 rows. ' + 'Reduce data or set "render_large_data" to True.') jsonstr = data.to_json(orient='records') html_id = 'f' + datalab.utils.commands.Html.next_id() HTML_TEMPLATE = """ <link rel="import" href="/nbextensions/gcpdatalab/extern/facets-jupyter.html"> <facets-dive id="{html_id}" height="{height}"></facets-dive> <script> var data = {jsonstr}; document.querySelector("#{html_id}").data = data; </script>""" html = HTML_TEMPLATE.format(html_id=html_id, jsonstr=jsonstr, height=height) return IPython.core.display.HTML(html)
[ "def", "plot", "(", "self", ",", "data", ",", "height", "=", "1000", ",", "render_large_data", "=", "False", ")", ":", "import", "IPython", "if", "not", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "raise", "ValueError", "(", "'Expect a DataFrame.'", ")", "if", "(", "len", "(", "data", ")", ">", "10000", "and", "not", "render_large_data", ")", ":", "raise", "ValueError", "(", "'Facets dive may not work well with more than 10000 rows. '", "+", "'Reduce data or set \"render_large_data\" to True.'", ")", "jsonstr", "=", "data", ".", "to_json", "(", "orient", "=", "'records'", ")", "html_id", "=", "'f'", "+", "datalab", ".", "utils", ".", "commands", ".", "Html", ".", "next_id", "(", ")", "HTML_TEMPLATE", "=", "\"\"\"\n <link rel=\"import\" href=\"/nbextensions/gcpdatalab/extern/facets-jupyter.html\">\n <facets-dive id=\"{html_id}\" height=\"{height}\"></facets-dive>\n <script>\n var data = {jsonstr};\n document.querySelector(\"#{html_id}\").data = data;\n </script>\"\"\"", "html", "=", "HTML_TEMPLATE", ".", "format", "(", "html_id", "=", "html_id", ",", "jsonstr", "=", "jsonstr", ",", "height", "=", "height", ")", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "html", ")" ]
Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output.
[ "Plots", "a", "detail", "view", "of", "data", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_fasets.py#L68-L95
train
237,969
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator.DtypeToType
def DtypeToType(self, dtype): """Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.""" if dtype.char in np.typecodes['AllFloat']: return self.fs_proto.FLOAT elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or np.issubdtype(dtype, np.datetime64) or np.issubdtype(dtype, np.timedelta64)): return self.fs_proto.INT else: return self.fs_proto.STRING
python
def DtypeToType(self, dtype): """Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.""" if dtype.char in np.typecodes['AllFloat']: return self.fs_proto.FLOAT elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or np.issubdtype(dtype, np.datetime64) or np.issubdtype(dtype, np.timedelta64)): return self.fs_proto.INT else: return self.fs_proto.STRING
[ "def", "DtypeToType", "(", "self", ",", "dtype", ")", ":", "if", "dtype", ".", "char", "in", "np", ".", "typecodes", "[", "'AllFloat'", "]", ":", "return", "self", ".", "fs_proto", ".", "FLOAT", "elif", "(", "dtype", ".", "char", "in", "np", ".", "typecodes", "[", "'AllInteger'", "]", "or", "dtype", "==", "np", ".", "bool", "or", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "datetime64", ")", "or", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "timedelta64", ")", ")", ":", "return", "self", ".", "fs_proto", ".", "INT", "else", ":", "return", "self", ".", "fs_proto", ".", "STRING" ]
Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.
[ "Converts", "a", "Numpy", "dtype", "to", "the", "FeatureNameStatistics", ".", "Type", "proto", "enum", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L58-L67
train
237,970
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator.NdarrayToEntry
def NdarrayToEntry(self, x): """Converts an ndarray to the Entry format.""" row_counts = [] for row in x: try: rc = np.count_nonzero(~np.isnan(row)) if rc != 0: row_counts.append(rc) except TypeError: try: row_counts.append(row.size) except AttributeError: row_counts.append(1) data_type = self.DtypeToType(x.dtype) converter = self.DtypeToNumberConverter(x.dtype) flattened = x.ravel() orig_size = len(flattened) # Remove all None and nan values and count how many were removed. flattened = flattened[flattened != np.array(None)] if converter: flattened = converter(flattened) if data_type == self.fs_proto.STRING: flattened_temp = [] for x in flattened: try: if str(x) != 'nan': flattened_temp.append(x) except UnicodeEncodeError: if x.encode('utf-8') != 'nan': flattened_temp.append(x) flattened = flattened_temp else: flattened = flattened[~np.isnan(flattened)].tolist() missing = orig_size - len(flattened) return { 'vals': flattened, 'counts': row_counts, 'missing': missing, 'type': data_type }
python
def NdarrayToEntry(self, x): """Converts an ndarray to the Entry format.""" row_counts = [] for row in x: try: rc = np.count_nonzero(~np.isnan(row)) if rc != 0: row_counts.append(rc) except TypeError: try: row_counts.append(row.size) except AttributeError: row_counts.append(1) data_type = self.DtypeToType(x.dtype) converter = self.DtypeToNumberConverter(x.dtype) flattened = x.ravel() orig_size = len(flattened) # Remove all None and nan values and count how many were removed. flattened = flattened[flattened != np.array(None)] if converter: flattened = converter(flattened) if data_type == self.fs_proto.STRING: flattened_temp = [] for x in flattened: try: if str(x) != 'nan': flattened_temp.append(x) except UnicodeEncodeError: if x.encode('utf-8') != 'nan': flattened_temp.append(x) flattened = flattened_temp else: flattened = flattened[~np.isnan(flattened)].tolist() missing = orig_size - len(flattened) return { 'vals': flattened, 'counts': row_counts, 'missing': missing, 'type': data_type }
[ "def", "NdarrayToEntry", "(", "self", ",", "x", ")", ":", "row_counts", "=", "[", "]", "for", "row", "in", "x", ":", "try", ":", "rc", "=", "np", ".", "count_nonzero", "(", "~", "np", ".", "isnan", "(", "row", ")", ")", "if", "rc", "!=", "0", ":", "row_counts", ".", "append", "(", "rc", ")", "except", "TypeError", ":", "try", ":", "row_counts", ".", "append", "(", "row", ".", "size", ")", "except", "AttributeError", ":", "row_counts", ".", "append", "(", "1", ")", "data_type", "=", "self", ".", "DtypeToType", "(", "x", ".", "dtype", ")", "converter", "=", "self", ".", "DtypeToNumberConverter", "(", "x", ".", "dtype", ")", "flattened", "=", "x", ".", "ravel", "(", ")", "orig_size", "=", "len", "(", "flattened", ")", "# Remove all None and nan values and count how many were removed.", "flattened", "=", "flattened", "[", "flattened", "!=", "np", ".", "array", "(", "None", ")", "]", "if", "converter", ":", "flattened", "=", "converter", "(", "flattened", ")", "if", "data_type", "==", "self", ".", "fs_proto", ".", "STRING", ":", "flattened_temp", "=", "[", "]", "for", "x", "in", "flattened", ":", "try", ":", "if", "str", "(", "x", ")", "!=", "'nan'", ":", "flattened_temp", ".", "append", "(", "x", ")", "except", "UnicodeEncodeError", ":", "if", "x", ".", "encode", "(", "'utf-8'", ")", "!=", "'nan'", ":", "flattened_temp", ".", "append", "(", "x", ")", "flattened", "=", "flattened_temp", "else", ":", "flattened", "=", "flattened", "[", "~", "np", ".", "isnan", "(", "flattened", ")", "]", ".", "tolist", "(", ")", "missing", "=", "orig_size", "-", "len", "(", "flattened", ")", "return", "{", "'vals'", ":", "flattened", ",", "'counts'", ":", "row_counts", ",", "'missing'", ":", "missing", ",", "'type'", ":", "data_type", "}" ]
Converts an ndarray to the Entry format.
[ "Converts", "an", "ndarray", "to", "the", "Entry", "format", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L96-L137
train
237,971
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
serving_from_csv_input
def serving_from_csv_input(train_config, args, keep_target): """Read the input features from a placeholder csv string tensor.""" examples = tf.placeholder( dtype=tf.string, shape=(None,), name='csv_input_string') features = parse_example_tensor(examples=examples, train_config=train_config, keep_target=keep_target) if keep_target: target = features.pop(train_config['target_column']) else: target = None features, target = preprocess_input( features=features, target=target, train_config=train_config, preprocess_output_dir=args.preprocess_output_dir, model_type=args.model_type) return input_fn_utils.InputFnOps(features, target, {'csv_line': examples} )
python
def serving_from_csv_input(train_config, args, keep_target): """Read the input features from a placeholder csv string tensor.""" examples = tf.placeholder( dtype=tf.string, shape=(None,), name='csv_input_string') features = parse_example_tensor(examples=examples, train_config=train_config, keep_target=keep_target) if keep_target: target = features.pop(train_config['target_column']) else: target = None features, target = preprocess_input( features=features, target=target, train_config=train_config, preprocess_output_dir=args.preprocess_output_dir, model_type=args.model_type) return input_fn_utils.InputFnOps(features, target, {'csv_line': examples} )
[ "def", "serving_from_csv_input", "(", "train_config", ",", "args", ",", "keep_target", ")", ":", "examples", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "string", ",", "shape", "=", "(", "None", ",", ")", ",", "name", "=", "'csv_input_string'", ")", "features", "=", "parse_example_tensor", "(", "examples", "=", "examples", ",", "train_config", "=", "train_config", ",", "keep_target", "=", "keep_target", ")", "if", "keep_target", ":", "target", "=", "features", ".", "pop", "(", "train_config", "[", "'target_column'", "]", ")", "else", ":", "target", "=", "None", "features", ",", "target", "=", "preprocess_input", "(", "features", "=", "features", ",", "target", "=", "target", ",", "train_config", "=", "train_config", ",", "preprocess_output_dir", "=", "args", ".", "preprocess_output_dir", ",", "model_type", "=", "args", ".", "model_type", ")", "return", "input_fn_utils", ".", "InputFnOps", "(", "features", ",", "target", ",", "{", "'csv_line'", ":", "examples", "}", ")" ]
Read the input features from a placeholder csv string tensor.
[ "Read", "the", "input", "features", "from", "a", "placeholder", "csv", "string", "tensor", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L90-L115
train
237,972
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
parse_example_tensor
def parse_example_tensor(examples, train_config, keep_target): """Read the csv files. Args: examples: string tensor train_config: training config keep_target: if true, the target column is expected to exist and it is returned in the features dict. Returns: Dict of feature_name to tensor. Target feature is in the dict. """ csv_header = [] if keep_target: csv_header = train_config['csv_header'] else: csv_header = [name for name in train_config['csv_header'] if name != train_config['target_column']] # record_defaults are used by tf.decode_csv to insert defaults, and to infer # the datatype. record_defaults = [[train_config['csv_defaults'][name]] for name in csv_header] tensors = tf.decode_csv(examples, record_defaults, name='csv_to_tensors') # I'm not really sure why expand_dims needs to be called. If using regression # models, it errors without it. tensors = [tf.expand_dims(x, axis=1) for x in tensors] tensor_dict = dict(zip(csv_header, tensors)) return tensor_dict
python
def parse_example_tensor(examples, train_config, keep_target): """Read the csv files. Args: examples: string tensor train_config: training config keep_target: if true, the target column is expected to exist and it is returned in the features dict. Returns: Dict of feature_name to tensor. Target feature is in the dict. """ csv_header = [] if keep_target: csv_header = train_config['csv_header'] else: csv_header = [name for name in train_config['csv_header'] if name != train_config['target_column']] # record_defaults are used by tf.decode_csv to insert defaults, and to infer # the datatype. record_defaults = [[train_config['csv_defaults'][name]] for name in csv_header] tensors = tf.decode_csv(examples, record_defaults, name='csv_to_tensors') # I'm not really sure why expand_dims needs to be called. If using regression # models, it errors without it. tensors = [tf.expand_dims(x, axis=1) for x in tensors] tensor_dict = dict(zip(csv_header, tensors)) return tensor_dict
[ "def", "parse_example_tensor", "(", "examples", ",", "train_config", ",", "keep_target", ")", ":", "csv_header", "=", "[", "]", "if", "keep_target", ":", "csv_header", "=", "train_config", "[", "'csv_header'", "]", "else", ":", "csv_header", "=", "[", "name", "for", "name", "in", "train_config", "[", "'csv_header'", "]", "if", "name", "!=", "train_config", "[", "'target_column'", "]", "]", "# record_defaults are used by tf.decode_csv to insert defaults, and to infer", "# the datatype.", "record_defaults", "=", "[", "[", "train_config", "[", "'csv_defaults'", "]", "[", "name", "]", "]", "for", "name", "in", "csv_header", "]", "tensors", "=", "tf", ".", "decode_csv", "(", "examples", ",", "record_defaults", ",", "name", "=", "'csv_to_tensors'", ")", "# I'm not really sure why expand_dims needs to be called. If using regression", "# models, it errors without it.", "tensors", "=", "[", "tf", ".", "expand_dims", "(", "x", ",", "axis", "=", "1", ")", "for", "x", "in", "tensors", "]", "tensor_dict", "=", "dict", "(", "zip", "(", "csv_header", ",", "tensors", ")", ")", "return", "tensor_dict" ]
Read the csv files. Args: examples: string tensor train_config: training config keep_target: if true, the target column is expected to exist and it is returned in the features dict. Returns: Dict of feature_name to tensor. Target feature is in the dict.
[ "Read", "the", "csv", "files", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L281-L312
train
237,973
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
get_estimator
def get_estimator(output_dir, train_config, args): """Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean estimator Raises: ValueError: if config is wrong. """ # Check the requested mode fits the preprocessed data. target_name = train_config['target_column'] if is_classification_model(args.model_type) and target_name not in \ train_config['categorical_columns']: raise ValueError('When using a classification model, the target must be a ' 'categorical variable.') if is_regression_model(args.model_type) and target_name not in \ train_config['numerical_columns']: raise ValueError('When using a regression model, the target must be a ' 'numerical variable.') # Check layers used for dnn models. if is_dnn_model(args.model_type) and not args.layer_sizes: raise ValueError('--layer-size* must be used with DNN models') if is_linear_model(args.model_type) and args.layer_sizes: raise ValueError('--layer-size* cannot be used with linear models') # Build tf.learn features feature_columns = _tflearn_features(train_config, args) # Set how often to run checkpointing in terms of time. config = tf.contrib.learn.RunConfig( save_checkpoints_secs=args.save_checkpoints_secs) train_dir = os.path.join(output_dir, 'train') if args.model_type == 'dnn_regression': estimator = tf.contrib.learn.DNNRegressor( feature_columns=feature_columns, hidden_units=args.layer_sizes, config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) elif args.model_type == 'linear_regression': estimator = tf.contrib.learn.LinearRegressor( feature_columns=feature_columns, config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) elif args.model_type == 'dnn_classification': estimator = tf.contrib.learn.DNNClassifier( feature_columns=feature_columns, hidden_units=args.layer_sizes, n_classes=train_config['vocab_stats'][target_name]['n_classes'], config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) elif args.model_type == 'linear_classification': estimator = tf.contrib.learn.LinearClassifier( feature_columns=feature_columns, n_classes=train_config['vocab_stats'][target_name]['n_classes'], config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) else: raise ValueError('bad --model-type value') return estimator
python
def get_estimator(output_dir, train_config, args): """Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean estimator Raises: ValueError: if config is wrong. """ # Check the requested mode fits the preprocessed data. target_name = train_config['target_column'] if is_classification_model(args.model_type) and target_name not in \ train_config['categorical_columns']: raise ValueError('When using a classification model, the target must be a ' 'categorical variable.') if is_regression_model(args.model_type) and target_name not in \ train_config['numerical_columns']: raise ValueError('When using a regression model, the target must be a ' 'numerical variable.') # Check layers used for dnn models. if is_dnn_model(args.model_type) and not args.layer_sizes: raise ValueError('--layer-size* must be used with DNN models') if is_linear_model(args.model_type) and args.layer_sizes: raise ValueError('--layer-size* cannot be used with linear models') # Build tf.learn features feature_columns = _tflearn_features(train_config, args) # Set how often to run checkpointing in terms of time. config = tf.contrib.learn.RunConfig( save_checkpoints_secs=args.save_checkpoints_secs) train_dir = os.path.join(output_dir, 'train') if args.model_type == 'dnn_regression': estimator = tf.contrib.learn.DNNRegressor( feature_columns=feature_columns, hidden_units=args.layer_sizes, config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) elif args.model_type == 'linear_regression': estimator = tf.contrib.learn.LinearRegressor( feature_columns=feature_columns, config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) elif args.model_type == 'dnn_classification': estimator = tf.contrib.learn.DNNClassifier( feature_columns=feature_columns, hidden_units=args.layer_sizes, n_classes=train_config['vocab_stats'][target_name]['n_classes'], config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) elif args.model_type == 'linear_classification': estimator = tf.contrib.learn.LinearClassifier( feature_columns=feature_columns, n_classes=train_config['vocab_stats'][target_name]['n_classes'], config=config, model_dir=train_dir, optimizer=tf.train.AdamOptimizer( args.learning_rate, epsilon=args.epsilon)) else: raise ValueError('bad --model-type value') return estimator
[ "def", "get_estimator", "(", "output_dir", ",", "train_config", ",", "args", ")", ":", "# Check the requested mode fits the preprocessed data.", "target_name", "=", "train_config", "[", "'target_column'", "]", "if", "is_classification_model", "(", "args", ".", "model_type", ")", "and", "target_name", "not", "in", "train_config", "[", "'categorical_columns'", "]", ":", "raise", "ValueError", "(", "'When using a classification model, the target must be a '", "'categorical variable.'", ")", "if", "is_regression_model", "(", "args", ".", "model_type", ")", "and", "target_name", "not", "in", "train_config", "[", "'numerical_columns'", "]", ":", "raise", "ValueError", "(", "'When using a regression model, the target must be a '", "'numerical variable.'", ")", "# Check layers used for dnn models.", "if", "is_dnn_model", "(", "args", ".", "model_type", ")", "and", "not", "args", ".", "layer_sizes", ":", "raise", "ValueError", "(", "'--layer-size* must be used with DNN models'", ")", "if", "is_linear_model", "(", "args", ".", "model_type", ")", "and", "args", ".", "layer_sizes", ":", "raise", "ValueError", "(", "'--layer-size* cannot be used with linear models'", ")", "# Build tf.learn features", "feature_columns", "=", "_tflearn_features", "(", "train_config", ",", "args", ")", "# Set how often to run checkpointing in terms of time.", "config", "=", "tf", ".", "contrib", ".", "learn", ".", "RunConfig", "(", "save_checkpoints_secs", "=", "args", ".", "save_checkpoints_secs", ")", "train_dir", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'train'", ")", "if", "args", ".", "model_type", "==", "'dnn_regression'", ":", "estimator", "=", "tf", ".", "contrib", ".", "learn", ".", "DNNRegressor", "(", "feature_columns", "=", "feature_columns", ",", "hidden_units", "=", "args", ".", "layer_sizes", ",", "config", "=", "config", ",", "model_dir", "=", "train_dir", ",", "optimizer", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "args", ".", "learning_rate", ",", "epsilon", "=", "args", ".", "epsilon", ")", ")", "elif", "args", ".", "model_type", "==", "'linear_regression'", ":", "estimator", "=", "tf", ".", "contrib", ".", "learn", ".", "LinearRegressor", "(", "feature_columns", "=", "feature_columns", ",", "config", "=", "config", ",", "model_dir", "=", "train_dir", ",", "optimizer", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "args", ".", "learning_rate", ",", "epsilon", "=", "args", ".", "epsilon", ")", ")", "elif", "args", ".", "model_type", "==", "'dnn_classification'", ":", "estimator", "=", "tf", ".", "contrib", ".", "learn", ".", "DNNClassifier", "(", "feature_columns", "=", "feature_columns", ",", "hidden_units", "=", "args", ".", "layer_sizes", ",", "n_classes", "=", "train_config", "[", "'vocab_stats'", "]", "[", "target_name", "]", "[", "'n_classes'", "]", ",", "config", "=", "config", ",", "model_dir", "=", "train_dir", ",", "optimizer", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "args", ".", "learning_rate", ",", "epsilon", "=", "args", ".", "epsilon", ")", ")", "elif", "args", ".", "model_type", "==", "'linear_classification'", ":", "estimator", "=", "tf", ".", "contrib", ".", "learn", ".", "LinearClassifier", "(", "feature_columns", "=", "feature_columns", ",", "n_classes", "=", "train_config", "[", "'vocab_stats'", "]", "[", "target_name", "]", "[", "'n_classes'", "]", ",", "config", "=", "config", ",", "model_dir", "=", "train_dir", ",", "optimizer", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "args", ".", "learning_rate", ",", "epsilon", "=", "args", ".", "epsilon", ")", ")", "else", ":", "raise", "ValueError", "(", "'bad --model-type value'", ")", "return", "estimator" ]
Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean estimator Raises: ValueError: if config is wrong.
[ "Returns", "a", "tf", "learn", "estimator", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L367-L445
train
237,974
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
preprocess_input
def preprocess_input(features, target, train_config, preprocess_output_dir, model_type): """Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_dir: folder should contain the vocab files. model_type: the tf model type. Raises: ValueError: if wrong transforms are used Returns: New features dict and new target tensor. """ target_name = train_config['target_column'] key_name = train_config['key_column'] # Do the numerical transforms. # Numerical transforms supported for regression/classification # 1) num -> do nothing (identity, default) # 2) num -> scale to -1, 1 (scale) # 3) num -> scale to -a, a (scale with value parameter) with tf.name_scope('numerical_feature_preprocess'): if train_config['numerical_columns']: numerical_analysis_file = os.path.join(preprocess_output_dir, NUMERICAL_ANALYSIS) if not file_io.file_exists(numerical_analysis_file): raise ValueError('File %s not found in %s' % (NUMERICAL_ANALYSIS, preprocess_output_dir)) numerical_anlysis = json.loads( python_portable_string( file_io.read_file_to_string(numerical_analysis_file))) for name in train_config['numerical_columns']: if name == target_name or name == key_name: continue transform_config = train_config['transforms'].get(name, {}) transform_name = transform_config.get('transform', None) if transform_name == 'scale': value = float(transform_config.get('value', 1.0)) features[name] = _scale_tensor( features[name], range_min=numerical_anlysis[name]['min'], range_max=numerical_anlysis[name]['max'], scale_min=-value, scale_max=value) elif transform_name == 'identity' or transform_name is None: pass else: raise ValueError(('For numerical variables, only scale ' 'and identity are supported: ' 'Error for %s') % name) # Do target transform if it exists. if target is not None: with tf.name_scope('target_feature_preprocess'): if target_name in train_config['categorical_columns']: labels = train_config['vocab_stats'][target_name]['labels'] table = tf.contrib.lookup.string_to_index_table_from_tensor(labels) target = table.lookup(target) # target = tf.contrib.lookup.string_to_index(target, labels) # Do categorical transforms. Only apply vocab mapping. The real # transforms are done with tf learn column features. with tf.name_scope('categorical_feature_preprocess'): for name in train_config['categorical_columns']: if name == key_name or name == target_name: continue transform_config = train_config['transforms'].get(name, {}) transform_name = transform_config.get('transform', None) if is_dnn_model(model_type): if transform_name == 'embedding' or transform_name == 'one_hot' or transform_name is None: map_vocab = True else: raise ValueError('Unknown transform %s' % transform_name) elif is_linear_model(model_type): if (transform_name == 'one_hot' or transform_name is None): map_vocab = True elif transform_name == 'embedding': map_vocab = False else: raise ValueError('Unknown transform %s' % transform_name) if map_vocab: labels = train_config['vocab_stats'][name]['labels'] table = tf.contrib.lookup.string_to_index_table_from_tensor(labels) features[name] = table.lookup(features[name]) return features, target
python
def preprocess_input(features, target, train_config, preprocess_output_dir, model_type): """Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_dir: folder should contain the vocab files. model_type: the tf model type. Raises: ValueError: if wrong transforms are used Returns: New features dict and new target tensor. """ target_name = train_config['target_column'] key_name = train_config['key_column'] # Do the numerical transforms. # Numerical transforms supported for regression/classification # 1) num -> do nothing (identity, default) # 2) num -> scale to -1, 1 (scale) # 3) num -> scale to -a, a (scale with value parameter) with tf.name_scope('numerical_feature_preprocess'): if train_config['numerical_columns']: numerical_analysis_file = os.path.join(preprocess_output_dir, NUMERICAL_ANALYSIS) if not file_io.file_exists(numerical_analysis_file): raise ValueError('File %s not found in %s' % (NUMERICAL_ANALYSIS, preprocess_output_dir)) numerical_anlysis = json.loads( python_portable_string( file_io.read_file_to_string(numerical_analysis_file))) for name in train_config['numerical_columns']: if name == target_name or name == key_name: continue transform_config = train_config['transforms'].get(name, {}) transform_name = transform_config.get('transform', None) if transform_name == 'scale': value = float(transform_config.get('value', 1.0)) features[name] = _scale_tensor( features[name], range_min=numerical_anlysis[name]['min'], range_max=numerical_anlysis[name]['max'], scale_min=-value, scale_max=value) elif transform_name == 'identity' or transform_name is None: pass else: raise ValueError(('For numerical variables, only scale ' 'and identity are supported: ' 'Error for %s') % name) # Do target transform if it exists. if target is not None: with tf.name_scope('target_feature_preprocess'): if target_name in train_config['categorical_columns']: labels = train_config['vocab_stats'][target_name]['labels'] table = tf.contrib.lookup.string_to_index_table_from_tensor(labels) target = table.lookup(target) # target = tf.contrib.lookup.string_to_index(target, labels) # Do categorical transforms. Only apply vocab mapping. The real # transforms are done with tf learn column features. with tf.name_scope('categorical_feature_preprocess'): for name in train_config['categorical_columns']: if name == key_name or name == target_name: continue transform_config = train_config['transforms'].get(name, {}) transform_name = transform_config.get('transform', None) if is_dnn_model(model_type): if transform_name == 'embedding' or transform_name == 'one_hot' or transform_name is None: map_vocab = True else: raise ValueError('Unknown transform %s' % transform_name) elif is_linear_model(model_type): if (transform_name == 'one_hot' or transform_name is None): map_vocab = True elif transform_name == 'embedding': map_vocab = False else: raise ValueError('Unknown transform %s' % transform_name) if map_vocab: labels = train_config['vocab_stats'][name]['labels'] table = tf.contrib.lookup.string_to_index_table_from_tensor(labels) features[name] = table.lookup(features[name]) return features, target
[ "def", "preprocess_input", "(", "features", ",", "target", ",", "train_config", ",", "preprocess_output_dir", ",", "model_type", ")", ":", "target_name", "=", "train_config", "[", "'target_column'", "]", "key_name", "=", "train_config", "[", "'key_column'", "]", "# Do the numerical transforms.", "# Numerical transforms supported for regression/classification", "# 1) num -> do nothing (identity, default)", "# 2) num -> scale to -1, 1 (scale)", "# 3) num -> scale to -a, a (scale with value parameter)", "with", "tf", ".", "name_scope", "(", "'numerical_feature_preprocess'", ")", ":", "if", "train_config", "[", "'numerical_columns'", "]", ":", "numerical_analysis_file", "=", "os", ".", "path", ".", "join", "(", "preprocess_output_dir", ",", "NUMERICAL_ANALYSIS", ")", "if", "not", "file_io", ".", "file_exists", "(", "numerical_analysis_file", ")", ":", "raise", "ValueError", "(", "'File %s not found in %s'", "%", "(", "NUMERICAL_ANALYSIS", ",", "preprocess_output_dir", ")", ")", "numerical_anlysis", "=", "json", ".", "loads", "(", "python_portable_string", "(", "file_io", ".", "read_file_to_string", "(", "numerical_analysis_file", ")", ")", ")", "for", "name", "in", "train_config", "[", "'numerical_columns'", "]", ":", "if", "name", "==", "target_name", "or", "name", "==", "key_name", ":", "continue", "transform_config", "=", "train_config", "[", "'transforms'", "]", ".", "get", "(", "name", ",", "{", "}", ")", "transform_name", "=", "transform_config", ".", "get", "(", "'transform'", ",", "None", ")", "if", "transform_name", "==", "'scale'", ":", "value", "=", "float", "(", "transform_config", ".", "get", "(", "'value'", ",", "1.0", ")", ")", "features", "[", "name", "]", "=", "_scale_tensor", "(", "features", "[", "name", "]", ",", "range_min", "=", "numerical_anlysis", "[", "name", "]", "[", "'min'", "]", ",", "range_max", "=", "numerical_anlysis", "[", "name", "]", "[", "'max'", "]", ",", "scale_min", "=", "-", "value", ",", "scale_max", "=", "value", ")", "elif", "transform_name", "==", "'identity'", "or", "transform_name", "is", "None", ":", "pass", "else", ":", "raise", "ValueError", "(", "(", "'For numerical variables, only scale '", "'and identity are supported: '", "'Error for %s'", ")", "%", "name", ")", "# Do target transform if it exists.", "if", "target", "is", "not", "None", ":", "with", "tf", ".", "name_scope", "(", "'target_feature_preprocess'", ")", ":", "if", "target_name", "in", "train_config", "[", "'categorical_columns'", "]", ":", "labels", "=", "train_config", "[", "'vocab_stats'", "]", "[", "target_name", "]", "[", "'labels'", "]", "table", "=", "tf", ".", "contrib", ".", "lookup", ".", "string_to_index_table_from_tensor", "(", "labels", ")", "target", "=", "table", ".", "lookup", "(", "target", ")", "# target = tf.contrib.lookup.string_to_index(target, labels)", "# Do categorical transforms. Only apply vocab mapping. The real", "# transforms are done with tf learn column features.", "with", "tf", ".", "name_scope", "(", "'categorical_feature_preprocess'", ")", ":", "for", "name", "in", "train_config", "[", "'categorical_columns'", "]", ":", "if", "name", "==", "key_name", "or", "name", "==", "target_name", ":", "continue", "transform_config", "=", "train_config", "[", "'transforms'", "]", ".", "get", "(", "name", ",", "{", "}", ")", "transform_name", "=", "transform_config", ".", "get", "(", "'transform'", ",", "None", ")", "if", "is_dnn_model", "(", "model_type", ")", ":", "if", "transform_name", "==", "'embedding'", "or", "transform_name", "==", "'one_hot'", "or", "transform_name", "is", "None", ":", "map_vocab", "=", "True", "else", ":", "raise", "ValueError", "(", "'Unknown transform %s'", "%", "transform_name", ")", "elif", "is_linear_model", "(", "model_type", ")", ":", "if", "(", "transform_name", "==", "'one_hot'", "or", "transform_name", "is", "None", ")", ":", "map_vocab", "=", "True", "elif", "transform_name", "==", "'embedding'", ":", "map_vocab", "=", "False", "else", ":", "raise", "ValueError", "(", "'Unknown transform %s'", "%", "transform_name", ")", "if", "map_vocab", ":", "labels", "=", "train_config", "[", "'vocab_stats'", "]", "[", "name", "]", "[", "'labels'", "]", "table", "=", "tf", ".", "contrib", ".", "lookup", ".", "string_to_index_table_from_tensor", "(", "labels", ")", "features", "[", "name", "]", "=", "table", ".", "lookup", "(", "features", "[", "name", "]", ")", "return", "features", ",", "target" ]
Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_dir: folder should contain the vocab files. model_type: the tf model type. Raises: ValueError: if wrong transforms are used Returns: New features dict and new target tensor.
[ "Perform", "some", "transformations", "after", "reading", "in", "the", "input", "tensors", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L448-L542
train
237,975
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
_scale_tensor
def _scale_tensor(tensor, range_min, range_max, scale_min, scale_max): """Scale a tensor to scale_min to scale_max. Args: tensor: input tensor. Should be a numerical tensor. range_min: min expected value for this feature/tensor. range_max: max expected Value. scale_min: new expected min value. scale_max: new expected max value. Returns: scaled tensor. """ if range_min == range_max: return tensor float_tensor = tf.to_float(tensor) scaled_tensor = tf.divide((tf.subtract(float_tensor, range_min) * tf.constant(float(scale_max - scale_min))), tf.constant(float(range_max - range_min))) shifted_tensor = scaled_tensor + tf.constant(float(scale_min)) return shifted_tensor
python
def _scale_tensor(tensor, range_min, range_max, scale_min, scale_max): """Scale a tensor to scale_min to scale_max. Args: tensor: input tensor. Should be a numerical tensor. range_min: min expected value for this feature/tensor. range_max: max expected Value. scale_min: new expected min value. scale_max: new expected max value. Returns: scaled tensor. """ if range_min == range_max: return tensor float_tensor = tf.to_float(tensor) scaled_tensor = tf.divide((tf.subtract(float_tensor, range_min) * tf.constant(float(scale_max - scale_min))), tf.constant(float(range_max - range_min))) shifted_tensor = scaled_tensor + tf.constant(float(scale_min)) return shifted_tensor
[ "def", "_scale_tensor", "(", "tensor", ",", "range_min", ",", "range_max", ",", "scale_min", ",", "scale_max", ")", ":", "if", "range_min", "==", "range_max", ":", "return", "tensor", "float_tensor", "=", "tf", ".", "to_float", "(", "tensor", ")", "scaled_tensor", "=", "tf", ".", "divide", "(", "(", "tf", ".", "subtract", "(", "float_tensor", ",", "range_min", ")", "*", "tf", ".", "constant", "(", "float", "(", "scale_max", "-", "scale_min", ")", ")", ")", ",", "tf", ".", "constant", "(", "float", "(", "range_max", "-", "range_min", ")", ")", ")", "shifted_tensor", "=", "scaled_tensor", "+", "tf", ".", "constant", "(", "float", "(", "scale_min", ")", ")", "return", "shifted_tensor" ]
Scale a tensor to scale_min to scale_max. Args: tensor: input tensor. Should be a numerical tensor. range_min: min expected value for this feature/tensor. range_max: max expected Value. scale_min: new expected min value. scale_max: new expected max value. Returns: scaled tensor.
[ "Scale", "a", "tensor", "to", "scale_min", "to", "scale_max", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L545-L567
train
237,976
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
_tflearn_features
def _tflearn_features(train_config, args): """Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was applied in preprocess_input. Args: train_config: our train config object args: command line args. Returns: List of TF lean feature columns. Raises: ValueError: if wrong transforms are used for the model type. """ feature_columns = [] target_name = train_config['target_column'] key_name = train_config['key_column'] for name in train_config['numerical_columns']: if name != target_name and name != key_name: feature_columns.append(tf.contrib.layers.real_valued_column( name, dimension=1)) # Supported transforms: # for DNN # 1) string -> make int -> embedding (embedding) # 2) string -> make int -> one_hot (one_hot, default) # for linear # 1) string -> sparse_column_with_hash_bucket (embedding) # 2) string -> make int -> sparse_column_with_integerized_feature (one_hot, default) # It is unfortunate that tf.layers has different feature transforms if the # model is linear or DNN. This pacakge should not expose to the user that # we are using tf.layers. It is crazy that DNN models support more feature # types (like string -> hash sparse column -> embedding) for name in train_config['categorical_columns']: if name != target_name and name != key_name: transform_config = train_config['transforms'].get(name, {}) transform_name = transform_config.get('transform', None) if is_dnn_model(args.model_type): if transform_name == 'embedding': sparse = tf.contrib.layers.sparse_column_with_integerized_feature( name, bucket_size=train_config['vocab_stats'][name]['n_classes']) learn_feature = tf.contrib.layers.embedding_column( sparse, dimension=transform_config['embedding_dim']) elif transform_name == 'one_hot' or transform_name is None: sparse = tf.contrib.layers.sparse_column_with_integerized_feature( name, bucket_size=train_config['vocab_stats'][name]['n_classes']) learn_feature = tf.contrib.layers.one_hot_column(sparse) else: raise ValueError(('Unknown transform name. Only \'embedding\' ' 'and \'one_hot\' transforms are supported. Got %s') % transform_name) elif is_linear_model(args.model_type): if transform_name == 'one_hot' or transform_name is None: learn_feature = tf.contrib.layers.sparse_column_with_integerized_feature( name, bucket_size=train_config['vocab_stats'][name]['n_classes']) elif transform_name == 'embedding': learn_feature = tf.contrib.layers.sparse_column_with_hash_bucket( name, hash_bucket_size=transform_config['embedding_dim']) else: raise ValueError(('Unknown transform name. Only \'embedding\' ' 'and \'one_hot\' transforms are supported. Got %s') % transform_name) # Save the feature feature_columns.append(learn_feature) return feature_columns
python
def _tflearn_features(train_config, args): """Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was applied in preprocess_input. Args: train_config: our train config object args: command line args. Returns: List of TF lean feature columns. Raises: ValueError: if wrong transforms are used for the model type. """ feature_columns = [] target_name = train_config['target_column'] key_name = train_config['key_column'] for name in train_config['numerical_columns']: if name != target_name and name != key_name: feature_columns.append(tf.contrib.layers.real_valued_column( name, dimension=1)) # Supported transforms: # for DNN # 1) string -> make int -> embedding (embedding) # 2) string -> make int -> one_hot (one_hot, default) # for linear # 1) string -> sparse_column_with_hash_bucket (embedding) # 2) string -> make int -> sparse_column_with_integerized_feature (one_hot, default) # It is unfortunate that tf.layers has different feature transforms if the # model is linear or DNN. This pacakge should not expose to the user that # we are using tf.layers. It is crazy that DNN models support more feature # types (like string -> hash sparse column -> embedding) for name in train_config['categorical_columns']: if name != target_name and name != key_name: transform_config = train_config['transforms'].get(name, {}) transform_name = transform_config.get('transform', None) if is_dnn_model(args.model_type): if transform_name == 'embedding': sparse = tf.contrib.layers.sparse_column_with_integerized_feature( name, bucket_size=train_config['vocab_stats'][name]['n_classes']) learn_feature = tf.contrib.layers.embedding_column( sparse, dimension=transform_config['embedding_dim']) elif transform_name == 'one_hot' or transform_name is None: sparse = tf.contrib.layers.sparse_column_with_integerized_feature( name, bucket_size=train_config['vocab_stats'][name]['n_classes']) learn_feature = tf.contrib.layers.one_hot_column(sparse) else: raise ValueError(('Unknown transform name. Only \'embedding\' ' 'and \'one_hot\' transforms are supported. Got %s') % transform_name) elif is_linear_model(args.model_type): if transform_name == 'one_hot' or transform_name is None: learn_feature = tf.contrib.layers.sparse_column_with_integerized_feature( name, bucket_size=train_config['vocab_stats'][name]['n_classes']) elif transform_name == 'embedding': learn_feature = tf.contrib.layers.sparse_column_with_hash_bucket( name, hash_bucket_size=transform_config['embedding_dim']) else: raise ValueError(('Unknown transform name. Only \'embedding\' ' 'and \'one_hot\' transforms are supported. Got %s') % transform_name) # Save the feature feature_columns.append(learn_feature) return feature_columns
[ "def", "_tflearn_features", "(", "train_config", ",", "args", ")", ":", "feature_columns", "=", "[", "]", "target_name", "=", "train_config", "[", "'target_column'", "]", "key_name", "=", "train_config", "[", "'key_column'", "]", "for", "name", "in", "train_config", "[", "'numerical_columns'", "]", ":", "if", "name", "!=", "target_name", "and", "name", "!=", "key_name", ":", "feature_columns", ".", "append", "(", "tf", ".", "contrib", ".", "layers", ".", "real_valued_column", "(", "name", ",", "dimension", "=", "1", ")", ")", "# Supported transforms:", "# for DNN", "# 1) string -> make int -> embedding (embedding)", "# 2) string -> make int -> one_hot (one_hot, default)", "# for linear", "# 1) string -> sparse_column_with_hash_bucket (embedding)", "# 2) string -> make int -> sparse_column_with_integerized_feature (one_hot, default)", "# It is unfortunate that tf.layers has different feature transforms if the", "# model is linear or DNN. This pacakge should not expose to the user that", "# we are using tf.layers. It is crazy that DNN models support more feature", "# types (like string -> hash sparse column -> embedding)", "for", "name", "in", "train_config", "[", "'categorical_columns'", "]", ":", "if", "name", "!=", "target_name", "and", "name", "!=", "key_name", ":", "transform_config", "=", "train_config", "[", "'transforms'", "]", ".", "get", "(", "name", ",", "{", "}", ")", "transform_name", "=", "transform_config", ".", "get", "(", "'transform'", ",", "None", ")", "if", "is_dnn_model", "(", "args", ".", "model_type", ")", ":", "if", "transform_name", "==", "'embedding'", ":", "sparse", "=", "tf", ".", "contrib", ".", "layers", ".", "sparse_column_with_integerized_feature", "(", "name", ",", "bucket_size", "=", "train_config", "[", "'vocab_stats'", "]", "[", "name", "]", "[", "'n_classes'", "]", ")", "learn_feature", "=", "tf", ".", "contrib", ".", "layers", ".", "embedding_column", "(", "sparse", ",", "dimension", "=", "transform_config", "[", "'embedding_dim'", "]", ")", "elif", "transform_name", "==", "'one_hot'", "or", "transform_name", "is", "None", ":", "sparse", "=", "tf", ".", "contrib", ".", "layers", ".", "sparse_column_with_integerized_feature", "(", "name", ",", "bucket_size", "=", "train_config", "[", "'vocab_stats'", "]", "[", "name", "]", "[", "'n_classes'", "]", ")", "learn_feature", "=", "tf", ".", "contrib", ".", "layers", ".", "one_hot_column", "(", "sparse", ")", "else", ":", "raise", "ValueError", "(", "(", "'Unknown transform name. Only \\'embedding\\' '", "'and \\'one_hot\\' transforms are supported. Got %s'", ")", "%", "transform_name", ")", "elif", "is_linear_model", "(", "args", ".", "model_type", ")", ":", "if", "transform_name", "==", "'one_hot'", "or", "transform_name", "is", "None", ":", "learn_feature", "=", "tf", ".", "contrib", ".", "layers", ".", "sparse_column_with_integerized_feature", "(", "name", ",", "bucket_size", "=", "train_config", "[", "'vocab_stats'", "]", "[", "name", "]", "[", "'n_classes'", "]", ")", "elif", "transform_name", "==", "'embedding'", ":", "learn_feature", "=", "tf", ".", "contrib", ".", "layers", ".", "sparse_column_with_hash_bucket", "(", "name", ",", "hash_bucket_size", "=", "transform_config", "[", "'embedding_dim'", "]", ")", "else", ":", "raise", "ValueError", "(", "(", "'Unknown transform name. Only \\'embedding\\' '", "'and \\'one_hot\\' transforms are supported. Got %s'", ")", "%", "transform_name", ")", "# Save the feature", "feature_columns", ".", "append", "(", "learn_feature", ")", "return", "feature_columns" ]
Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was applied in preprocess_input. Args: train_config: our train config object args: command line args. Returns: List of TF lean feature columns. Raises: ValueError: if wrong transforms are used for the model type.
[ "Builds", "the", "tf", ".", "learn", "feature", "list", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L570-L647
train
237,977
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
get_vocabulary
def get_vocabulary(preprocess_output_dir, name): """Loads the vocabulary file as a list of strings. Args: preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name. name: name of the csv column. Returns: List of strings. Raises: ValueError: if file is missing. """ vocab_file = os.path.join(preprocess_output_dir, CATEGORICAL_ANALYSIS % name) if not file_io.file_exists(vocab_file): raise ValueError('File %s not found in %s' % (CATEGORICAL_ANALYSIS % name, preprocess_output_dir)) labels = python_portable_string( file_io.read_file_to_string(vocab_file)).split('\n') label_values = [x for x in labels if x] # remove empty lines return label_values
python
def get_vocabulary(preprocess_output_dir, name): """Loads the vocabulary file as a list of strings. Args: preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name. name: name of the csv column. Returns: List of strings. Raises: ValueError: if file is missing. """ vocab_file = os.path.join(preprocess_output_dir, CATEGORICAL_ANALYSIS % name) if not file_io.file_exists(vocab_file): raise ValueError('File %s not found in %s' % (CATEGORICAL_ANALYSIS % name, preprocess_output_dir)) labels = python_portable_string( file_io.read_file_to_string(vocab_file)).split('\n') label_values = [x for x in labels if x] # remove empty lines return label_values
[ "def", "get_vocabulary", "(", "preprocess_output_dir", ",", "name", ")", ":", "vocab_file", "=", "os", ".", "path", ".", "join", "(", "preprocess_output_dir", ",", "CATEGORICAL_ANALYSIS", "%", "name", ")", "if", "not", "file_io", ".", "file_exists", "(", "vocab_file", ")", ":", "raise", "ValueError", "(", "'File %s not found in %s'", "%", "(", "CATEGORICAL_ANALYSIS", "%", "name", ",", "preprocess_output_dir", ")", ")", "labels", "=", "python_portable_string", "(", "file_io", ".", "read_file_to_string", "(", "vocab_file", ")", ")", ".", "split", "(", "'\\n'", ")", "label_values", "=", "[", "x", "for", "x", "in", "labels", "if", "x", "]", "# remove empty lines", "return", "label_values" ]
Loads the vocabulary file as a list of strings. Args: preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name. name: name of the csv column. Returns: List of strings. Raises: ValueError: if file is missing.
[ "Loads", "the", "vocabulary", "file", "as", "a", "list", "of", "strings", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L655-L677
train
237,978
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
validate_metadata
def validate_metadata(train_config): """Perform some checks that the trainig config is correct. Args: train_config: train config as produced by merge_metadata() Raises: ValueError: if columns look wrong. """ # Make sure we have a default for every column if len(train_config['csv_header']) != len(train_config['csv_defaults']): raise ValueError('Unequal number of columns in input features file and ' 'schema file.') # Check there are no missing columns. sorted_colums has two copies of the # target column because the target column is also listed in # categorical_columns or numerical_columns. sorted_columns = sorted(train_config['csv_header'] + [train_config['target_column']]) sorted_columns2 = sorted(train_config['categorical_columns'] + train_config['numerical_columns'] + [train_config['key_column']] + [train_config['target_column']]) if sorted_columns2 != sorted_columns: raise ValueError('Each csv header must be a numerical/categorical type, a ' ' key, or a target.')
python
def validate_metadata(train_config): """Perform some checks that the trainig config is correct. Args: train_config: train config as produced by merge_metadata() Raises: ValueError: if columns look wrong. """ # Make sure we have a default for every column if len(train_config['csv_header']) != len(train_config['csv_defaults']): raise ValueError('Unequal number of columns in input features file and ' 'schema file.') # Check there are no missing columns. sorted_colums has two copies of the # target column because the target column is also listed in # categorical_columns or numerical_columns. sorted_columns = sorted(train_config['csv_header'] + [train_config['target_column']]) sorted_columns2 = sorted(train_config['categorical_columns'] + train_config['numerical_columns'] + [train_config['key_column']] + [train_config['target_column']]) if sorted_columns2 != sorted_columns: raise ValueError('Each csv header must be a numerical/categorical type, a ' ' key, or a target.')
[ "def", "validate_metadata", "(", "train_config", ")", ":", "# Make sure we have a default for every column", "if", "len", "(", "train_config", "[", "'csv_header'", "]", ")", "!=", "len", "(", "train_config", "[", "'csv_defaults'", "]", ")", ":", "raise", "ValueError", "(", "'Unequal number of columns in input features file and '", "'schema file.'", ")", "# Check there are no missing columns. sorted_colums has two copies of the", "# target column because the target column is also listed in", "# categorical_columns or numerical_columns.", "sorted_columns", "=", "sorted", "(", "train_config", "[", "'csv_header'", "]", "+", "[", "train_config", "[", "'target_column'", "]", "]", ")", "sorted_columns2", "=", "sorted", "(", "train_config", "[", "'categorical_columns'", "]", "+", "train_config", "[", "'numerical_columns'", "]", "+", "[", "train_config", "[", "'key_column'", "]", "]", "+", "[", "train_config", "[", "'target_column'", "]", "]", ")", "if", "sorted_columns2", "!=", "sorted_columns", ":", "raise", "ValueError", "(", "'Each csv header must be a numerical/categorical type, a '", "' key, or a target.'", ")" ]
Perform some checks that the trainig config is correct. Args: train_config: train config as produced by merge_metadata() Raises: ValueError: if columns look wrong.
[ "Perform", "some", "checks", "that", "the", "trainig", "config", "is", "correct", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L811-L838
train
237,979
googledatalab/pydatalab
datalab/context/_project.py
Projects.get_default_id
def get_default_id(credentials=None): """ Get default project id. Returns: the default project id if there is one, or None. """ project_id = _utils.get_project_id() if project_id is None: projects, _ = Projects(credentials)._retrieve_projects(None, 2) if len(projects) == 1: project_id = projects[0].id return project_id
python
def get_default_id(credentials=None): """ Get default project id. Returns: the default project id if there is one, or None. """ project_id = _utils.get_project_id() if project_id is None: projects, _ = Projects(credentials)._retrieve_projects(None, 2) if len(projects) == 1: project_id = projects[0].id return project_id
[ "def", "get_default_id", "(", "credentials", "=", "None", ")", ":", "project_id", "=", "_utils", ".", "get_project_id", "(", ")", "if", "project_id", "is", "None", ":", "projects", ",", "_", "=", "Projects", "(", "credentials", ")", ".", "_retrieve_projects", "(", "None", ",", "2", ")", "if", "len", "(", "projects", ")", "==", "1", ":", "project_id", "=", "projects", "[", "0", "]", ".", "id", "return", "project_id" ]
Get default project id. Returns: the default project id if there is one, or None.
[ "Get", "default", "project", "id", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/context/_project.py#L97-L107
train
237,980
jpvanhal/flask-split
flask_split/core.py
init_app
def init_app(state): """ Prepare the Flask application for Flask-Split. :param state: :class:`BlueprintSetupState` instance """ app = state.app app.config.setdefault('SPLIT_ALLOW_MULTIPLE_EXPERIMENTS', False) app.config.setdefault('SPLIT_DB_FAILOVER', False) app.config.setdefault('SPLIT_IGNORE_IP_ADDRESSES', []) app.config.setdefault('SPLIT_ROBOT_REGEX', r""" (?i)\b( Baidu| Gigabot| Googlebot| libwww-perl| lwp-trivial| msnbot| SiteUptime| Slurp| WordPress| ZIBB| ZyBorg )\b """) app.jinja_env.globals.update({ 'ab_test': ab_test, 'finished': finished }) @app.template_filter() def percentage(number): number *= 100 if abs(number) < 10: return "%.1f%%" % round(number, 1) else: return "%d%%" % round(number)
python
def init_app(state): """ Prepare the Flask application for Flask-Split. :param state: :class:`BlueprintSetupState` instance """ app = state.app app.config.setdefault('SPLIT_ALLOW_MULTIPLE_EXPERIMENTS', False) app.config.setdefault('SPLIT_DB_FAILOVER', False) app.config.setdefault('SPLIT_IGNORE_IP_ADDRESSES', []) app.config.setdefault('SPLIT_ROBOT_REGEX', r""" (?i)\b( Baidu| Gigabot| Googlebot| libwww-perl| lwp-trivial| msnbot| SiteUptime| Slurp| WordPress| ZIBB| ZyBorg )\b """) app.jinja_env.globals.update({ 'ab_test': ab_test, 'finished': finished }) @app.template_filter() def percentage(number): number *= 100 if abs(number) < 10: return "%.1f%%" % round(number, 1) else: return "%d%%" % round(number)
[ "def", "init_app", "(", "state", ")", ":", "app", "=", "state", ".", "app", "app", ".", "config", ".", "setdefault", "(", "'SPLIT_ALLOW_MULTIPLE_EXPERIMENTS'", ",", "False", ")", "app", ".", "config", ".", "setdefault", "(", "'SPLIT_DB_FAILOVER'", ",", "False", ")", "app", ".", "config", ".", "setdefault", "(", "'SPLIT_IGNORE_IP_ADDRESSES'", ",", "[", "]", ")", "app", ".", "config", ".", "setdefault", "(", "'SPLIT_ROBOT_REGEX'", ",", "r\"\"\"\n (?i)\\b(\n Baidu|\n Gigabot|\n Googlebot|\n libwww-perl|\n lwp-trivial|\n msnbot|\n SiteUptime|\n Slurp|\n WordPress|\n ZIBB|\n ZyBorg\n )\\b\n \"\"\"", ")", "app", ".", "jinja_env", ".", "globals", ".", "update", "(", "{", "'ab_test'", ":", "ab_test", ",", "'finished'", ":", "finished", "}", ")", "@", "app", ".", "template_filter", "(", ")", "def", "percentage", "(", "number", ")", ":", "number", "*=", "100", "if", "abs", "(", "number", ")", "<", "10", ":", "return", "\"%.1f%%\"", "%", "round", "(", "number", ",", "1", ")", "else", ":", "return", "\"%d%%\"", "%", "round", "(", "number", ")" ]
Prepare the Flask application for Flask-Split. :param state: :class:`BlueprintSetupState` instance
[ "Prepare", "the", "Flask", "application", "for", "Flask", "-", "Split", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/core.py#L23-L61
train
237,981
jpvanhal/flask-split
flask_split/core.py
finished
def finished(experiment_name, reset=True): """ Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternative they started with. Defaults to `True`. """ if _exclude_visitor(): return redis = _get_redis_connection() try: experiment = Experiment.find(redis, experiment_name) if not experiment: return alternative_name = _get_session().get(experiment.key) if alternative_name: split_finished = set(session.get('split_finished', [])) if experiment.key not in split_finished: alternative = Alternative( redis, alternative_name, experiment_name) alternative.increment_completion() if reset: _get_session().pop(experiment.key, None) try: split_finished.remove(experiment.key) except KeyError: pass else: split_finished.add(experiment.key) session['split_finished'] = list(split_finished) except ConnectionError: if not current_app.config['SPLIT_DB_FAILOVER']: raise
python
def finished(experiment_name, reset=True): """ Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternative they started with. Defaults to `True`. """ if _exclude_visitor(): return redis = _get_redis_connection() try: experiment = Experiment.find(redis, experiment_name) if not experiment: return alternative_name = _get_session().get(experiment.key) if alternative_name: split_finished = set(session.get('split_finished', [])) if experiment.key not in split_finished: alternative = Alternative( redis, alternative_name, experiment_name) alternative.increment_completion() if reset: _get_session().pop(experiment.key, None) try: split_finished.remove(experiment.key) except KeyError: pass else: split_finished.add(experiment.key) session['split_finished'] = list(split_finished) except ConnectionError: if not current_app.config['SPLIT_DB_FAILOVER']: raise
[ "def", "finished", "(", "experiment_name", ",", "reset", "=", "True", ")", ":", "if", "_exclude_visitor", "(", ")", ":", "return", "redis", "=", "_get_redis_connection", "(", ")", "try", ":", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",", "experiment_name", ")", "if", "not", "experiment", ":", "return", "alternative_name", "=", "_get_session", "(", ")", ".", "get", "(", "experiment", ".", "key", ")", "if", "alternative_name", ":", "split_finished", "=", "set", "(", "session", ".", "get", "(", "'split_finished'", ",", "[", "]", ")", ")", "if", "experiment", ".", "key", "not", "in", "split_finished", ":", "alternative", "=", "Alternative", "(", "redis", ",", "alternative_name", ",", "experiment_name", ")", "alternative", ".", "increment_completion", "(", ")", "if", "reset", ":", "_get_session", "(", ")", ".", "pop", "(", "experiment", ".", "key", ",", "None", ")", "try", ":", "split_finished", ".", "remove", "(", "experiment", ".", "key", ")", "except", "KeyError", ":", "pass", "else", ":", "split_finished", ".", "add", "(", "experiment", ".", "key", ")", "session", "[", "'split_finished'", "]", "=", "list", "(", "split_finished", ")", "except", "ConnectionError", ":", "if", "not", "current_app", ".", "config", "[", "'SPLIT_DB_FAILOVER'", "]", ":", "raise" ]
Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternative they started with. Defaults to `True`.
[ "Track", "a", "conversion", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/core.py#L108-L142
train
237,982
jpvanhal/flask-split
flask_split/core.py
_is_robot
def _is_robot(): """ Return `True` if the current visitor is a robot or spider, or `False` otherwise. This function works by comparing the request's user agent with a regular expression. The regular expression can be configured with the ``SPLIT_ROBOT_REGEX`` setting. """ robot_regex = current_app.config['SPLIT_ROBOT_REGEX'] user_agent = request.headers.get('User-Agent', '') return re.search(robot_regex, user_agent, flags=re.VERBOSE)
python
def _is_robot(): """ Return `True` if the current visitor is a robot or spider, or `False` otherwise. This function works by comparing the request's user agent with a regular expression. The regular expression can be configured with the ``SPLIT_ROBOT_REGEX`` setting. """ robot_regex = current_app.config['SPLIT_ROBOT_REGEX'] user_agent = request.headers.get('User-Agent', '') return re.search(robot_regex, user_agent, flags=re.VERBOSE)
[ "def", "_is_robot", "(", ")", ":", "robot_regex", "=", "current_app", ".", "config", "[", "'SPLIT_ROBOT_REGEX'", "]", "user_agent", "=", "request", ".", "headers", ".", "get", "(", "'User-Agent'", ",", "''", ")", "return", "re", ".", "search", "(", "robot_regex", ",", "user_agent", ",", "flags", "=", "re", ".", "VERBOSE", ")" ]
Return `True` if the current visitor is a robot or spider, or `False` otherwise. This function works by comparing the request's user agent with a regular expression. The regular expression can be configured with the ``SPLIT_ROBOT_REGEX`` setting.
[ "Return", "True", "if", "the", "current", "visitor", "is", "a", "robot", "or", "spider", "or", "False", "otherwise", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/core.py#L206-L217
train
237,983
jpvanhal/flask-split
flask_split/models.py
Experiment.start_time
def start_time(self): """The start time of this experiment.""" t = self.redis.hget('experiment_start_times', self.name) if t: return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S')
python
def start_time(self): """The start time of this experiment.""" t = self.redis.hget('experiment_start_times', self.name) if t: return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S')
[ "def", "start_time", "(", "self", ")", ":", "t", "=", "self", ".", "redis", ".", "hget", "(", "'experiment_start_times'", ",", "self", ".", "name", ")", "if", "t", ":", "return", "datetime", ".", "strptime", "(", "t", ",", "'%Y-%m-%dT%H:%M:%S'", ")" ]
The start time of this experiment.
[ "The", "start", "time", "of", "this", "experiment", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/models.py#L163-L167
train
237,984
jpvanhal/flask-split
flask_split/models.py
Experiment.reset
def reset(self): """Delete all data for this experiment.""" for alternative in self.alternatives: alternative.reset() self.reset_winner() self.increment_version()
python
def reset(self): """Delete all data for this experiment.""" for alternative in self.alternatives: alternative.reset() self.reset_winner() self.increment_version()
[ "def", "reset", "(", "self", ")", ":", "for", "alternative", "in", "self", ".", "alternatives", ":", "alternative", ".", "reset", "(", ")", "self", ".", "reset_winner", "(", ")", "self", ".", "increment_version", "(", ")" ]
Delete all data for this experiment.
[ "Delete", "all", "data", "for", "this", "experiment", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/models.py#L211-L216
train
237,985
jpvanhal/flask-split
flask_split/models.py
Experiment.delete
def delete(self): """Delete this experiment and all its data.""" for alternative in self.alternatives: alternative.delete() self.reset_winner() self.redis.srem('experiments', self.name) self.redis.delete(self.name) self.increment_version()
python
def delete(self): """Delete this experiment and all its data.""" for alternative in self.alternatives: alternative.delete() self.reset_winner() self.redis.srem('experiments', self.name) self.redis.delete(self.name) self.increment_version()
[ "def", "delete", "(", "self", ")", ":", "for", "alternative", "in", "self", ".", "alternatives", ":", "alternative", ".", "delete", "(", ")", "self", ".", "reset_winner", "(", ")", "self", ".", "redis", ".", "srem", "(", "'experiments'", ",", "self", ".", "name", ")", "self", ".", "redis", ".", "delete", "(", "self", ".", "name", ")", "self", ".", "increment_version", "(", ")" ]
Delete this experiment and all its data.
[ "Delete", "this", "experiment", "and", "all", "its", "data", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/models.py#L218-L225
train
237,986
jpvanhal/flask-split
flask_split/utils.py
_get_redis_connection
def _get_redis_connection(): """ Return a Redis connection based on the Flask application's configuration. The connection parameters are retrieved from `REDIS_URL` configuration variable. :return: an instance of :class:`redis.Connection` """ url = current_app.config.get('REDIS_URL', 'redis://localhost:6379') return redis.from_url(url, decode_responses=True)
python
def _get_redis_connection(): """ Return a Redis connection based on the Flask application's configuration. The connection parameters are retrieved from `REDIS_URL` configuration variable. :return: an instance of :class:`redis.Connection` """ url = current_app.config.get('REDIS_URL', 'redis://localhost:6379') return redis.from_url(url, decode_responses=True)
[ "def", "_get_redis_connection", "(", ")", ":", "url", "=", "current_app", ".", "config", ".", "get", "(", "'REDIS_URL'", ",", "'redis://localhost:6379'", ")", "return", "redis", ".", "from_url", "(", "url", ",", "decode_responses", "=", "True", ")" ]
Return a Redis connection based on the Flask application's configuration. The connection parameters are retrieved from `REDIS_URL` configuration variable. :return: an instance of :class:`redis.Connection`
[ "Return", "a", "Redis", "connection", "based", "on", "the", "Flask", "application", "s", "configuration", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/utils.py#L24-L34
train
237,987
jpvanhal/flask-split
flask_split/views.py
set_experiment_winner
def set_experiment_winner(experiment): """Mark an alternative as the winner of the experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: alternative_name = request.form.get('alternative') alternative = Alternative(redis, alternative_name, experiment.name) if alternative.name in experiment.alternative_names: experiment.winner = alternative.name return redirect(url_for('.index'))
python
def set_experiment_winner(experiment): """Mark an alternative as the winner of the experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: alternative_name = request.form.get('alternative') alternative = Alternative(redis, alternative_name, experiment.name) if alternative.name in experiment.alternative_names: experiment.winner = alternative.name return redirect(url_for('.index'))
[ "def", "set_experiment_winner", "(", "experiment", ")", ":", "redis", "=", "_get_redis_connection", "(", ")", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",", "experiment", ")", "if", "experiment", ":", "alternative_name", "=", "request", ".", "form", ".", "get", "(", "'alternative'", ")", "alternative", "=", "Alternative", "(", "redis", ",", "alternative_name", ",", "experiment", ".", "name", ")", "if", "alternative", ".", "name", "in", "experiment", ".", "alternative_names", ":", "experiment", ".", "winner", "=", "alternative", ".", "name", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")" ]
Mark an alternative as the winner of the experiment.
[ "Mark", "an", "alternative", "as", "the", "winner", "of", "the", "experiment", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/views.py#L44-L53
train
237,988
jpvanhal/flask-split
flask_split/views.py
reset_experiment
def reset_experiment(experiment): """Delete all data for an experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.reset() return redirect(url_for('.index'))
python
def reset_experiment(experiment): """Delete all data for an experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.reset() return redirect(url_for('.index'))
[ "def", "reset_experiment", "(", "experiment", ")", ":", "redis", "=", "_get_redis_connection", "(", ")", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",", "experiment", ")", "if", "experiment", ":", "experiment", ".", "reset", "(", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")" ]
Delete all data for an experiment.
[ "Delete", "all", "data", "for", "an", "experiment", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/views.py#L57-L63
train
237,989
jpvanhal/flask-split
flask_split/views.py
delete_experiment
def delete_experiment(experiment): """Delete an experiment and all its data.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.delete() return redirect(url_for('.index'))
python
def delete_experiment(experiment): """Delete an experiment and all its data.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.delete() return redirect(url_for('.index'))
[ "def", "delete_experiment", "(", "experiment", ")", ":", "redis", "=", "_get_redis_connection", "(", ")", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",", "experiment", ")", "if", "experiment", ":", "experiment", ".", "delete", "(", ")", "return", "redirect", "(", "url_for", "(", "'.index'", ")", ")" ]
Delete an experiment and all its data.
[ "Delete", "an", "experiment", "and", "all", "its", "data", "." ]
52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/views.py#L67-L73
train
237,990
tobami/littlechef
littlechef/chef.py
_get_ipaddress
def _get_ipaddress(node): """Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added, False otherwise """ if "ipaddress" not in node: with settings(hide('stdout'), warn_only=True): output = sudo('ohai -l warn ipaddress') if output.succeeded: try: node['ipaddress'] = json.loads(output)[0] except ValueError: abort("Could not parse ohai's output for ipaddress" ":\n {0}".format(output)) return True return False
python
def _get_ipaddress(node): """Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added, False otherwise """ if "ipaddress" not in node: with settings(hide('stdout'), warn_only=True): output = sudo('ohai -l warn ipaddress') if output.succeeded: try: node['ipaddress'] = json.loads(output)[0] except ValueError: abort("Could not parse ohai's output for ipaddress" ":\n {0}".format(output)) return True return False
[ "def", "_get_ipaddress", "(", "node", ")", ":", "if", "\"ipaddress\"", "not", "in", "node", ":", "with", "settings", "(", "hide", "(", "'stdout'", ")", ",", "warn_only", "=", "True", ")", ":", "output", "=", "sudo", "(", "'ohai -l warn ipaddress'", ")", "if", "output", ".", "succeeded", ":", "try", ":", "node", "[", "'ipaddress'", "]", "=", "json", ".", "loads", "(", "output", ")", "[", "0", "]", "except", "ValueError", ":", "abort", "(", "\"Could not parse ohai's output for ipaddress\"", "\":\\n {0}\"", ".", "format", "(", "output", ")", ")", "return", "True", "return", "False" ]
Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added, False otherwise
[ "Adds", "the", "ipaddress", "attribute", "to", "the", "given", "node", "object", "if", "not", "already", "present", "and", "it", "is", "correctly", "given", "by", "ohai", "Returns", "True", "if", "ipaddress", "is", "added", "False", "otherwise" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L55-L71
train
237,991
tobami/littlechef
littlechef/chef.py
sync_node
def sync_node(node): """Builds, synchronizes and configures a node. It also injects the ipaddress to the node's config file if not already existent. """ if node.get('dummy') or 'dummy' in node.get('tags', []): lib.print_header("Skipping dummy: {0}".format(env.host)) return False current_node = lib.get_node(node['name']) # Always configure Chef Solo solo.configure(current_node) ipaddress = _get_ipaddress(node) # Everything was configured alright, so save the node configuration # This is done without credentials, so that we keep the node name used # by the user and not the hostname or IP translated by .ssh/config filepath = save_config(node, ipaddress) try: # Synchronize the kitchen directory _synchronize_node(filepath, node) # Execute Chef Solo _configure_node() finally: _node_cleanup() return True
python
def sync_node(node): """Builds, synchronizes and configures a node. It also injects the ipaddress to the node's config file if not already existent. """ if node.get('dummy') or 'dummy' in node.get('tags', []): lib.print_header("Skipping dummy: {0}".format(env.host)) return False current_node = lib.get_node(node['name']) # Always configure Chef Solo solo.configure(current_node) ipaddress = _get_ipaddress(node) # Everything was configured alright, so save the node configuration # This is done without credentials, so that we keep the node name used # by the user and not the hostname or IP translated by .ssh/config filepath = save_config(node, ipaddress) try: # Synchronize the kitchen directory _synchronize_node(filepath, node) # Execute Chef Solo _configure_node() finally: _node_cleanup() return True
[ "def", "sync_node", "(", "node", ")", ":", "if", "node", ".", "get", "(", "'dummy'", ")", "or", "'dummy'", "in", "node", ".", "get", "(", "'tags'", ",", "[", "]", ")", ":", "lib", ".", "print_header", "(", "\"Skipping dummy: {0}\"", ".", "format", "(", "env", ".", "host", ")", ")", "return", "False", "current_node", "=", "lib", ".", "get_node", "(", "node", "[", "'name'", "]", ")", "# Always configure Chef Solo", "solo", ".", "configure", "(", "current_node", ")", "ipaddress", "=", "_get_ipaddress", "(", "node", ")", "# Everything was configured alright, so save the node configuration", "# This is done without credentials, so that we keep the node name used", "# by the user and not the hostname or IP translated by .ssh/config", "filepath", "=", "save_config", "(", "node", ",", "ipaddress", ")", "try", ":", "# Synchronize the kitchen directory", "_synchronize_node", "(", "filepath", ",", "node", ")", "# Execute Chef Solo", "_configure_node", "(", ")", "finally", ":", "_node_cleanup", "(", ")", "return", "True" ]
Builds, synchronizes and configures a node. It also injects the ipaddress to the node's config file if not already existent.
[ "Builds", "synchronizes", "and", "configures", "a", "node", ".", "It", "also", "injects", "the", "ipaddress", "to", "the", "node", "s", "config", "file", "if", "not", "already", "existent", "." ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L86-L110
train
237,992
tobami/littlechef
littlechef/chef.py
build_dct
def build_dct(dic, keys, value): """Builds a dictionary with arbitrary depth out of a key list""" key = keys.pop(0) if len(keys): dic.setdefault(key, {}) build_dct(dic[key], keys, value) else: # Transform cookbook default attribute strings into proper booleans if value == "false": value = False elif value == "true": value = True # It's a leaf, assign value dic[key] = deepcopy(value)
python
def build_dct(dic, keys, value): """Builds a dictionary with arbitrary depth out of a key list""" key = keys.pop(0) if len(keys): dic.setdefault(key, {}) build_dct(dic[key], keys, value) else: # Transform cookbook default attribute strings into proper booleans if value == "false": value = False elif value == "true": value = True # It's a leaf, assign value dic[key] = deepcopy(value)
[ "def", "build_dct", "(", "dic", ",", "keys", ",", "value", ")", ":", "key", "=", "keys", ".", "pop", "(", "0", ")", "if", "len", "(", "keys", ")", ":", "dic", ".", "setdefault", "(", "key", ",", "{", "}", ")", "build_dct", "(", "dic", "[", "key", "]", ",", "keys", ",", "value", ")", "else", ":", "# Transform cookbook default attribute strings into proper booleans", "if", "value", "==", "\"false\"", ":", "value", "=", "False", "elif", "value", "==", "\"true\"", ":", "value", "=", "True", "# It's a leaf, assign value", "dic", "[", "key", "]", "=", "deepcopy", "(", "value", ")" ]
Builds a dictionary with arbitrary depth out of a key list
[ "Builds", "a", "dictionary", "with", "arbitrary", "depth", "out", "of", "a", "key", "list" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L192-L205
train
237,993
tobami/littlechef
littlechef/chef.py
update_dct
def update_dct(dic1, dic2): """Merges two dictionaries recursively dic2 will have preference over dic1 """ for key, val in dic2.items(): if isinstance(val, dict): dic1.setdefault(key, {}) update_dct(dic1[key], val) else: dic1[key] = val
python
def update_dct(dic1, dic2): """Merges two dictionaries recursively dic2 will have preference over dic1 """ for key, val in dic2.items(): if isinstance(val, dict): dic1.setdefault(key, {}) update_dct(dic1[key], val) else: dic1[key] = val
[ "def", "update_dct", "(", "dic1", ",", "dic2", ")", ":", "for", "key", ",", "val", "in", "dic2", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "dic1", ".", "setdefault", "(", "key", ",", "{", "}", ")", "update_dct", "(", "dic1", "[", "key", "]", ",", "val", ")", "else", ":", "dic1", "[", "key", "]", "=", "val" ]
Merges two dictionaries recursively dic2 will have preference over dic1
[ "Merges", "two", "dictionaries", "recursively", "dic2", "will", "have", "preference", "over", "dic1" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L208-L218
train
237,994
tobami/littlechef
littlechef/chef.py
_add_merged_attributes
def _add_merged_attributes(node, all_recipes, all_roles): """Merges attributes from cookbooks, node and roles Chef Attribute precedence: http://docs.opscode.com/essentials_cookbook_attribute_files.html#attribute-precedence LittleChef implements, in precedence order: - Cookbook default - Environment default - Role default - Node normal - Role override - Environment override NOTE: In order for cookbook attributes to be read, they need to be correctly defined in its metadata.json """ # Get cookbooks from extended recipes attributes = {} for recipe in node['recipes']: # Find this recipe found = False for r in all_recipes: if recipe == r['name']: found = True for attr in r['attributes']: if r['attributes'][attr].get('type') == "hash": value = {} else: value = r['attributes'][attr].get('default') # Attribute dictionaries are defined as a single # compound key. Split and build proper dict build_dct(attributes, attr.split("/"), value) if not found: error = "Could not find recipe '{0}' while ".format(recipe) error += "building node data bag for '{0}'".format(node['name']) abort(error) # Get default role attributes for role in node['roles']: for r in all_roles: if role == r['name']: update_dct(attributes, r.get('default_attributes', {})) # Get default environment attributes environment = lib.get_environment(node['chef_environment']) update_dct(attributes, environment.get('default_attributes', {})) # Get normal node attributes non_attribute_fields = [ 'id', 'name', 'role', 'roles', 'recipes', 'run_list', 'ipaddress'] node_attributes = {} for key in node: if key in non_attribute_fields: continue node_attributes[key] = node[key] update_dct(attributes, node_attributes) # Get override role attributes for role in node['roles']: for r in all_roles: if role == r['name']: update_dct(attributes, r.get('override_attributes', {})) # Get override environment attributes update_dct(attributes, environment.get('override_attributes', {})) # Merge back to the original node object node.update(attributes)
python
def _add_merged_attributes(node, all_recipes, all_roles): """Merges attributes from cookbooks, node and roles Chef Attribute precedence: http://docs.opscode.com/essentials_cookbook_attribute_files.html#attribute-precedence LittleChef implements, in precedence order: - Cookbook default - Environment default - Role default - Node normal - Role override - Environment override NOTE: In order for cookbook attributes to be read, they need to be correctly defined in its metadata.json """ # Get cookbooks from extended recipes attributes = {} for recipe in node['recipes']: # Find this recipe found = False for r in all_recipes: if recipe == r['name']: found = True for attr in r['attributes']: if r['attributes'][attr].get('type') == "hash": value = {} else: value = r['attributes'][attr].get('default') # Attribute dictionaries are defined as a single # compound key. Split and build proper dict build_dct(attributes, attr.split("/"), value) if not found: error = "Could not find recipe '{0}' while ".format(recipe) error += "building node data bag for '{0}'".format(node['name']) abort(error) # Get default role attributes for role in node['roles']: for r in all_roles: if role == r['name']: update_dct(attributes, r.get('default_attributes', {})) # Get default environment attributes environment = lib.get_environment(node['chef_environment']) update_dct(attributes, environment.get('default_attributes', {})) # Get normal node attributes non_attribute_fields = [ 'id', 'name', 'role', 'roles', 'recipes', 'run_list', 'ipaddress'] node_attributes = {} for key in node: if key in non_attribute_fields: continue node_attributes[key] = node[key] update_dct(attributes, node_attributes) # Get override role attributes for role in node['roles']: for r in all_roles: if role == r['name']: update_dct(attributes, r.get('override_attributes', {})) # Get override environment attributes update_dct(attributes, environment.get('override_attributes', {})) # Merge back to the original node object node.update(attributes)
[ "def", "_add_merged_attributes", "(", "node", ",", "all_recipes", ",", "all_roles", ")", ":", "# Get cookbooks from extended recipes", "attributes", "=", "{", "}", "for", "recipe", "in", "node", "[", "'recipes'", "]", ":", "# Find this recipe", "found", "=", "False", "for", "r", "in", "all_recipes", ":", "if", "recipe", "==", "r", "[", "'name'", "]", ":", "found", "=", "True", "for", "attr", "in", "r", "[", "'attributes'", "]", ":", "if", "r", "[", "'attributes'", "]", "[", "attr", "]", ".", "get", "(", "'type'", ")", "==", "\"hash\"", ":", "value", "=", "{", "}", "else", ":", "value", "=", "r", "[", "'attributes'", "]", "[", "attr", "]", ".", "get", "(", "'default'", ")", "# Attribute dictionaries are defined as a single", "# compound key. Split and build proper dict", "build_dct", "(", "attributes", ",", "attr", ".", "split", "(", "\"/\"", ")", ",", "value", ")", "if", "not", "found", ":", "error", "=", "\"Could not find recipe '{0}' while \"", ".", "format", "(", "recipe", ")", "error", "+=", "\"building node data bag for '{0}'\"", ".", "format", "(", "node", "[", "'name'", "]", ")", "abort", "(", "error", ")", "# Get default role attributes", "for", "role", "in", "node", "[", "'roles'", "]", ":", "for", "r", "in", "all_roles", ":", "if", "role", "==", "r", "[", "'name'", "]", ":", "update_dct", "(", "attributes", ",", "r", ".", "get", "(", "'default_attributes'", ",", "{", "}", ")", ")", "# Get default environment attributes", "environment", "=", "lib", ".", "get_environment", "(", "node", "[", "'chef_environment'", "]", ")", "update_dct", "(", "attributes", ",", "environment", ".", "get", "(", "'default_attributes'", ",", "{", "}", ")", ")", "# Get normal node attributes", "non_attribute_fields", "=", "[", "'id'", ",", "'name'", ",", "'role'", ",", "'roles'", ",", "'recipes'", ",", "'run_list'", ",", "'ipaddress'", "]", "node_attributes", "=", "{", "}", "for", "key", "in", "node", ":", "if", "key", "in", "non_attribute_fields", ":", "continue", "node_attributes", "[", "key", "]", "=", "node", "[", "key", "]", "update_dct", "(", "attributes", ",", "node_attributes", ")", "# Get override role attributes", "for", "role", "in", "node", "[", "'roles'", "]", ":", "for", "r", "in", "all_roles", ":", "if", "role", "==", "r", "[", "'name'", "]", ":", "update_dct", "(", "attributes", ",", "r", ".", "get", "(", "'override_attributes'", ",", "{", "}", ")", ")", "# Get override environment attributes", "update_dct", "(", "attributes", ",", "environment", ".", "get", "(", "'override_attributes'", ",", "{", "}", ")", ")", "# Merge back to the original node object", "node", ".", "update", "(", "attributes", ")" ]
Merges attributes from cookbooks, node and roles Chef Attribute precedence: http://docs.opscode.com/essentials_cookbook_attribute_files.html#attribute-precedence LittleChef implements, in precedence order: - Cookbook default - Environment default - Role default - Node normal - Role override - Environment override NOTE: In order for cookbook attributes to be read, they need to be correctly defined in its metadata.json
[ "Merges", "attributes", "from", "cookbooks", "node", "and", "roles" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L232-L300
train
237,995
tobami/littlechef
littlechef/chef.py
build_node_data_bag
def build_node_data_bag(): """Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames should be fqdns) 'hostname': Uses the first part of the filename as the hostname (until it finds a period) minus the .json extension 'domain': filename minus the first part of the filename (hostname) minus the .json extension In addition, it will contain the merged attributes from: All default cookbook attributes corresponding to the node All attributes found in nodes/<item>.json file Default and override attributes from all roles """ nodes = lib.get_nodes() node_data_bag_path = os.path.join('data_bags', 'node') # In case there are leftovers remove_local_node_data_bag() os.makedirs(node_data_bag_path) all_recipes = lib.get_recipes() all_roles = lib.get_roles() for node in nodes: # Dots are not allowed (only alphanumeric), substitute by underscores node['id'] = node['name'].replace('.', '_') # Build extended role list node['role'] = lib.get_roles_in_node(node) node['roles'] = node['role'][:] for role in node['role']: node['roles'].extend(lib.get_roles_in_role(role)) node['roles'] = list(set(node['roles'])) # Build extended recipe list node['recipes'] = lib.get_recipes_in_node(node) # Add recipes found inside each roles in the extended role list for role in node['roles']: node['recipes'].extend(lib.get_recipes_in_role(role)) node['recipes'] = list(set(node['recipes'])) # Add node attributes _add_merged_attributes(node, all_recipes, all_roles) _add_automatic_attributes(node) # Save node data bag item with open(os.path.join( 'data_bags', 'node', node['id'] + '.json'), 'w') as f: f.write(json.dumps(node))
python
def build_node_data_bag(): """Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames should be fqdns) 'hostname': Uses the first part of the filename as the hostname (until it finds a period) minus the .json extension 'domain': filename minus the first part of the filename (hostname) minus the .json extension In addition, it will contain the merged attributes from: All default cookbook attributes corresponding to the node All attributes found in nodes/<item>.json file Default and override attributes from all roles """ nodes = lib.get_nodes() node_data_bag_path = os.path.join('data_bags', 'node') # In case there are leftovers remove_local_node_data_bag() os.makedirs(node_data_bag_path) all_recipes = lib.get_recipes() all_roles = lib.get_roles() for node in nodes: # Dots are not allowed (only alphanumeric), substitute by underscores node['id'] = node['name'].replace('.', '_') # Build extended role list node['role'] = lib.get_roles_in_node(node) node['roles'] = node['role'][:] for role in node['role']: node['roles'].extend(lib.get_roles_in_role(role)) node['roles'] = list(set(node['roles'])) # Build extended recipe list node['recipes'] = lib.get_recipes_in_node(node) # Add recipes found inside each roles in the extended role list for role in node['roles']: node['recipes'].extend(lib.get_recipes_in_role(role)) node['recipes'] = list(set(node['recipes'])) # Add node attributes _add_merged_attributes(node, all_recipes, all_roles) _add_automatic_attributes(node) # Save node data bag item with open(os.path.join( 'data_bags', 'node', node['id'] + '.json'), 'w') as f: f.write(json.dumps(node))
[ "def", "build_node_data_bag", "(", ")", ":", "nodes", "=", "lib", ".", "get_nodes", "(", ")", "node_data_bag_path", "=", "os", ".", "path", ".", "join", "(", "'data_bags'", ",", "'node'", ")", "# In case there are leftovers", "remove_local_node_data_bag", "(", ")", "os", ".", "makedirs", "(", "node_data_bag_path", ")", "all_recipes", "=", "lib", ".", "get_recipes", "(", ")", "all_roles", "=", "lib", ".", "get_roles", "(", ")", "for", "node", "in", "nodes", ":", "# Dots are not allowed (only alphanumeric), substitute by underscores", "node", "[", "'id'", "]", "=", "node", "[", "'name'", "]", ".", "replace", "(", "'.'", ",", "'_'", ")", "# Build extended role list", "node", "[", "'role'", "]", "=", "lib", ".", "get_roles_in_node", "(", "node", ")", "node", "[", "'roles'", "]", "=", "node", "[", "'role'", "]", "[", ":", "]", "for", "role", "in", "node", "[", "'role'", "]", ":", "node", "[", "'roles'", "]", ".", "extend", "(", "lib", ".", "get_roles_in_role", "(", "role", ")", ")", "node", "[", "'roles'", "]", "=", "list", "(", "set", "(", "node", "[", "'roles'", "]", ")", ")", "# Build extended recipe list", "node", "[", "'recipes'", "]", "=", "lib", ".", "get_recipes_in_node", "(", "node", ")", "# Add recipes found inside each roles in the extended role list", "for", "role", "in", "node", "[", "'roles'", "]", ":", "node", "[", "'recipes'", "]", ".", "extend", "(", "lib", ".", "get_recipes_in_role", "(", "role", ")", ")", "node", "[", "'recipes'", "]", "=", "list", "(", "set", "(", "node", "[", "'recipes'", "]", ")", ")", "# Add node attributes", "_add_merged_attributes", "(", "node", ",", "all_recipes", ",", "all_roles", ")", "_add_automatic_attributes", "(", "node", ")", "# Save node data bag item", "with", "open", "(", "os", ".", "path", ".", "join", "(", "'data_bags'", ",", "'node'", ",", "node", "[", "'id'", "]", "+", "'.json'", ")", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "node", ")", ")" ]
Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames should be fqdns) 'hostname': Uses the first part of the filename as the hostname (until it finds a period) minus the .json extension 'domain': filename minus the first part of the filename (hostname) minus the .json extension In addition, it will contain the merged attributes from: All default cookbook attributes corresponding to the node All attributes found in nodes/<item>.json file Default and override attributes from all roles
[ "Builds", "one", "node", "data", "bag", "item", "per", "file", "found", "in", "the", "nodes", "directory" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L303-L352
train
237,996
tobami/littlechef
littlechef/chef.py
remove_local_node_data_bag
def remove_local_node_data_bag(): """Removes generated 'node' data_bag locally""" node_data_bag_path = os.path.join('data_bags', 'node') if os.path.exists(node_data_bag_path): shutil.rmtree(node_data_bag_path)
python
def remove_local_node_data_bag(): """Removes generated 'node' data_bag locally""" node_data_bag_path = os.path.join('data_bags', 'node') if os.path.exists(node_data_bag_path): shutil.rmtree(node_data_bag_path)
[ "def", "remove_local_node_data_bag", "(", ")", ":", "node_data_bag_path", "=", "os", ".", "path", ".", "join", "(", "'data_bags'", ",", "'node'", ")", "if", "os", ".", "path", ".", "exists", "(", "node_data_bag_path", ")", ":", "shutil", ".", "rmtree", "(", "node_data_bag_path", ")" ]
Removes generated 'node' data_bag locally
[ "Removes", "generated", "node", "data_bag", "locally" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L355-L359
train
237,997
tobami/littlechef
littlechef/chef.py
ensure_berksfile_cookbooks_are_installed
def ensure_berksfile_cookbooks_are_installed(): """Run 'berks vendor' to berksfile cookbooks directory""" msg = "Vendoring cookbooks from Berksfile {0} to directory {1}..." print(msg.format(env.berksfile, env.berksfile_cookbooks_directory)) run_vendor = True cookbooks_dir = env.berksfile_cookbooks_directory berksfile_lock_path = cookbooks_dir+'/Berksfile.lock' berksfile_lock_exists = os.path.isfile(berksfile_lock_path) cookbooks_dir_exists = os.path.isdir(cookbooks_dir) if cookbooks_dir_exists and berksfile_lock_exists: berksfile_mtime = os.stat('Berksfile').st_mtime cookbooks_mtime = os.stat(berksfile_lock_path).st_mtime run_vendor = berksfile_mtime > cookbooks_mtime if run_vendor: if cookbooks_dir_exists: shutil.rmtree(env.berksfile_cookbooks_directory) p = subprocess.Popen(['berks', 'vendor', env.berksfile_cookbooks_directory], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if env.verbose or p.returncode: print stdout, stderr
python
def ensure_berksfile_cookbooks_are_installed(): """Run 'berks vendor' to berksfile cookbooks directory""" msg = "Vendoring cookbooks from Berksfile {0} to directory {1}..." print(msg.format(env.berksfile, env.berksfile_cookbooks_directory)) run_vendor = True cookbooks_dir = env.berksfile_cookbooks_directory berksfile_lock_path = cookbooks_dir+'/Berksfile.lock' berksfile_lock_exists = os.path.isfile(berksfile_lock_path) cookbooks_dir_exists = os.path.isdir(cookbooks_dir) if cookbooks_dir_exists and berksfile_lock_exists: berksfile_mtime = os.stat('Berksfile').st_mtime cookbooks_mtime = os.stat(berksfile_lock_path).st_mtime run_vendor = berksfile_mtime > cookbooks_mtime if run_vendor: if cookbooks_dir_exists: shutil.rmtree(env.berksfile_cookbooks_directory) p = subprocess.Popen(['berks', 'vendor', env.berksfile_cookbooks_directory], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if env.verbose or p.returncode: print stdout, stderr
[ "def", "ensure_berksfile_cookbooks_are_installed", "(", ")", ":", "msg", "=", "\"Vendoring cookbooks from Berksfile {0} to directory {1}...\"", "print", "(", "msg", ".", "format", "(", "env", ".", "berksfile", ",", "env", ".", "berksfile_cookbooks_directory", ")", ")", "run_vendor", "=", "True", "cookbooks_dir", "=", "env", ".", "berksfile_cookbooks_directory", "berksfile_lock_path", "=", "cookbooks_dir", "+", "'/Berksfile.lock'", "berksfile_lock_exists", "=", "os", ".", "path", ".", "isfile", "(", "berksfile_lock_path", ")", "cookbooks_dir_exists", "=", "os", ".", "path", ".", "isdir", "(", "cookbooks_dir", ")", "if", "cookbooks_dir_exists", "and", "berksfile_lock_exists", ":", "berksfile_mtime", "=", "os", ".", "stat", "(", "'Berksfile'", ")", ".", "st_mtime", "cookbooks_mtime", "=", "os", ".", "stat", "(", "berksfile_lock_path", ")", ".", "st_mtime", "run_vendor", "=", "berksfile_mtime", ">", "cookbooks_mtime", "if", "run_vendor", ":", "if", "cookbooks_dir_exists", ":", "shutil", ".", "rmtree", "(", "env", ".", "berksfile_cookbooks_directory", ")", "p", "=", "subprocess", ".", "Popen", "(", "[", "'berks'", ",", "'vendor'", ",", "env", ".", "berksfile_cookbooks_directory", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "if", "env", ".", "verbose", "or", "p", ".", "returncode", ":", "print", "stdout", ",", "stderr" ]
Run 'berks vendor' to berksfile cookbooks directory
[ "Run", "berks", "vendor", "to", "berksfile", "cookbooks", "directory" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L362-L388
train
237,998
tobami/littlechef
littlechef/chef.py
_remove_remote_node_data_bag
def _remove_remote_node_data_bag(): """Removes generated 'node' data_bag from the remote node""" node_data_bag_path = os.path.join(env.node_work_path, 'data_bags', 'node') if exists(node_data_bag_path): sudo("rm -rf {0}".format(node_data_bag_path))
python
def _remove_remote_node_data_bag(): """Removes generated 'node' data_bag from the remote node""" node_data_bag_path = os.path.join(env.node_work_path, 'data_bags', 'node') if exists(node_data_bag_path): sudo("rm -rf {0}".format(node_data_bag_path))
[ "def", "_remove_remote_node_data_bag", "(", ")", ":", "node_data_bag_path", "=", "os", ".", "path", ".", "join", "(", "env", ".", "node_work_path", ",", "'data_bags'", ",", "'node'", ")", "if", "exists", "(", "node_data_bag_path", ")", ":", "sudo", "(", "\"rm -rf {0}\"", ".", "format", "(", "node_data_bag_path", ")", ")" ]
Removes generated 'node' data_bag from the remote node
[ "Removes", "generated", "node", "data_bag", "from", "the", "remote", "node" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L391-L395
train
237,999