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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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, datal... | 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, datal... | [
"def",
"_get_schema",
"(",
"name",
")",
":",
"item",
"=",
"datalab",
".",
"utils",
".",
"commands",
".",
"get_notebook_item",
"(",
"name",
")",
"if",
"not",
"item",
":",
"item",
"=",
"_get_table",
"(",
"name",
")",
"if",
"isinstance",
"(",
"item",
",",... | 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 |
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 |
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 ... | 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 ... | [
"def",
"_datasets_line",
"(",
"args",
")",
":",
"filter_",
"=",
"args",
"[",
"'filter'",
"]",
"if",
"args",
"[",
"'filter'",
"]",
"else",
"'*'",
"return",
"_render_list",
"(",
"[",
"str",
"(",
"dataset",
")",
"for",
"dataset",
"in",
"datalab",
".",
"bi... | 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 |
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 ... | 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 ... | [
"def",
"_tables_line",
"(",
"args",
")",
":",
"filter_",
"=",
"args",
"[",
"'filter'",
"]",
"if",
"args",
"[",
"'filter'",
"]",
"else",
"'*'",
"if",
"args",
"[",
"'dataset'",
"]",
":",
"if",
"args",
"[",
"'project'",
"]",
"is",
"None",
":",
"datasets... | 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 |
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... | 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... | [
"def",
"_extract_line",
"(",
"args",
")",
":",
"name",
"=",
"args",
"[",
"'source'",
"]",
"source",
"=",
"datalab",
".",
"utils",
".",
"commands",
".",
"get_notebook_item",
"(",
"name",
")",
"if",
"not",
"source",
":",
"source",
"=",
"_get_table",
"(",
... | 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 |
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.... | 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.... | [
"def",
"bigquery",
"(",
"line",
",",
"cell",
"=",
"None",
")",
":",
"namespace",
"=",
"{",
"}",
"if",
"line",
".",
"find",
"(",
"'$'",
")",
">=",
"0",
":",
"namespace",
"=",
"datalab",
".",
"utils",
".",
"commands",
".",
"notebook_environment",
"(",
... | 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 |
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 u... | 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 u... | [
"def",
"table",
"(",
"name",
"=",
"None",
",",
"mode",
"=",
"'create'",
",",
"use_cache",
"=",
"True",
",",
"priority",
"=",
"'interactive'",
",",
"allow_large_results",
"=",
"False",
")",
":",
"output",
"=",
"QueryOutput",
"(",
")",
"output",
".",
"_out... | 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 ... | [
"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 |
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 e... | 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 e... | [
"def",
"file",
"(",
"path",
",",
"format",
"=",
"'csv'",
",",
"csv_delimiter",
"=",
"','",
",",
"csv_header",
"=",
"True",
",",
"compress",
"=",
"False",
",",
"use_cache",
"=",
"True",
")",
":",
"output",
"=",
"QueryOutput",
"(",
")",
"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 ... | [
"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 |
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: wh... | 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: wh... | [
"def",
"dataframe",
"(",
"start_row",
"=",
"0",
",",
"max_rows",
"=",
"None",
",",
"use_cache",
"=",
"True",
")",
":",
"output",
"=",
"QueryOutput",
"(",
")",
"output",
".",
"_output_type",
"=",
"'dataframe'",
"output",
".",
"_dataframe_start_row",
"=",
"s... | 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 |
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
... | 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
... | [
"def",
"list",
"(",
")",
":",
"running_list",
"=",
"[",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--logdir'",
")",
"parser",
".",
"add_argument",
"(",
"'--port'",
")",
"for",
"p",
"in",
"psutil... | List running TensorBoard instances. | [
"List",
"running",
"TensorBoard",
"instances",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_tensorboard.py#L33-L47 | train |
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 use... | 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 use... | [
"def",
"start",
"(",
"logdir",
")",
":",
"if",
"logdir",
".",
"startswith",
"(",
"'gs://'",
")",
":",
"datalab",
".",
"storage",
".",
"_api",
".",
"Api",
".",
"verify_permitted_to_read",
"(",
"logdir",
")",
"port",
"=",
"datalab",
".",
"utils",
".",
"p... | 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 |
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 |
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 bes... | 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 bes... | [
"def",
"build_graph",
"(",
"self",
")",
":",
"import",
"tensorflow",
"as",
"tf",
"input_jpeg",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"string",
",",
"shape",
"=",
"None",
")",
"image",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"input_jp... | 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... | [
"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 |
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_p... | 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_p... | [
"def",
"restore_from_checkpoint",
"(",
"self",
",",
"checkpoint_path",
")",
":",
"import",
"tensorflow",
"as",
"tf",
"all_vars",
"=",
"tf",
".",
"contrib",
".",
"slim",
".",
"get_variables_to_restore",
"(",
"exclude",
"=",
"[",
"'InceptionV3/AuxLogits'",
",",
"'... | 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 |
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.embeddi... | 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.embeddi... | [
"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 |
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... | 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... | [
"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_scop... | 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.
... | [
"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 |
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 Incept... | 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 Incept... | [
"def",
"build_inception_graph",
"(",
"self",
")",
":",
"image_str_tensor",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"string",
",",
"shape",
"=",
"[",
"None",
"]",
")",
"image",
"=",
"tf",
".",
"map_fn",
"(",
"_util",
".",
"decode_and_resize",
",",
... | 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... | [
"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 |
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=i... | 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=i... | [
"def",
"build_graph",
"(",
"self",
",",
"data_paths",
",",
"batch_size",
",",
"graph_mod",
")",
":",
"tensors",
"=",
"GraphReferences",
"(",
")",
"is_training",
"=",
"graph_mod",
"==",
"GraphMod",
".",
"TRAIN",
"if",
"data_paths",
":",
"_",
",",
"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 |
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.... | 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.... | [
"def",
"restore_from_checkpoint",
"(",
"self",
",",
"session",
",",
"inception_checkpoint_file",
",",
"trained_checkpoint_file",
")",
":",
"inception_exclude_scopes",
"=",
"[",
"'InceptionV3/AuxLogits'",
",",
"'InceptionV3/Logits'",
",",
"'global_step'",
",",
"'final_ops'",... | 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 checkpoi... | [
"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 |
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
... | 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
... | [
"def",
"build_prediction_graph",
"(",
"self",
")",
":",
"tensors",
"=",
"self",
".",
"build_graph",
"(",
"None",
",",
"1",
",",
"GraphMod",
".",
"PREDICT",
")",
"keys_placeholder",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"string",
",",
"shape",
"=... | 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 |
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', outp... | 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', outp... | [
"def",
"export",
"(",
"self",
",",
"last_checkpoint",
",",
"output_dir",
")",
":",
"logging",
".",
"info",
"(",
"'Exporting prediction graph to %s'",
",",
"output_dir",
")",
"with",
"tf",
".",
"Session",
"(",
"graph",
"=",
"tf",
".",
"Graph",
"(",
")",
")"... | 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 |
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_... | 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_... | [
"def",
"format_metric_values",
"(",
"self",
",",
"metric_values",
")",
":",
"loss_str",
"=",
"'N/A'",
"accuracy_str",
"=",
"'N/A'",
"try",
":",
"loss_str",
"=",
"'loss: %.3f'",
"%",
"metric_values",
"[",
"0",
"]",
"accuracy_str",
"=",
"'accuracy: %.3f'",
"%",
... | 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 |
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 t... | 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 t... | [
"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",
"n... | 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 pack... | [
"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 |
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 |
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'... | 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'... | [
"def",
"_date",
"(",
"val",
",",
"offset",
"=",
"None",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"val",
"if",
"val",
"==",
"''",
"or",
"val",
"==",
"'now'",
":",
"when",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"elif"... | 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)... | [
"A",
"special",
"pseudo",
"-",
"type",
"for",
"pipeline",
"arguments",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L119-L177 | train |
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",
")",
")",
... | 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 |
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 |
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': _datest... | 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': _datest... | [
"def",
"_arguments",
"(",
"code",
",",
"module",
")",
":",
"arg_parser",
"=",
"CommandParser",
".",
"create",
"(",
"''",
")",
"try",
":",
"builtins",
"=",
"{",
"'source'",
":",
"_table",
",",
"'datestring'",
":",
"_datestring",
"}",
"env",
"=",
"{",
"}... | 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 |
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.
"""
line... | 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.
"""
line... | [
"def",
"_split_cell",
"(",
"cell",
",",
"module",
")",
":",
"lines",
"=",
"cell",
".",
"split",
"(",
"'\\n'",
")",
"code",
"=",
"None",
"last_def",
"=",
"-",
"1",
"name",
"=",
"None",
"define_wild_re",
"=",
"re",
".",
"compile",
"(",
"'^DEFINE\\s+.*$'"... | 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 |
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... | 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... | [
"def",
"sql_cell",
"(",
"args",
",",
"cell",
")",
":",
"name",
"=",
"args",
"[",
"'module'",
"]",
"if",
"args",
"[",
"'module'",
"]",
"else",
"'_sql_cell'",
"module",
"=",
"imp",
".",
"new_module",
"(",
"name",
")",
"query",
"=",
"_split_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:
... | [
"Implements",
"the",
"SQL",
"cell",
"magic",
"for",
"ipython",
"notebooks",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/commands/_sql.py#L370-L402 | train |
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(
... | 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(
... | [
"def",
"get_reader_input_fn",
"(",
"train_config",
",",
"preprocess_output_dir",
",",
"model_type",
",",
"data_paths",
",",
"batch_size",
",",
"shuffle",
",",
"num_epochs",
"=",
"None",
")",
":",
"def",
"get_input_features",
"(",
")",
":",
"_",
",",
"examples",
... | 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 |
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",
")",
"l... | 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 |
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 rela... | 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 rela... | [
"def",
"sd",
"(",
"line",
",",
"cell",
"=",
"None",
")",
":",
"parser",
"=",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"CommandParser",
"(",
"prog",
"=",
"'%sd'",
",",
"description",
"=",
"(",
"'Execute various Stackdriver related operati... | 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 |
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.... | 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.... | [
"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",
"("... | 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 |
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,
... | 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,
... | [
"def",
"read_vocab",
"(",
"args",
",",
"column_name",
")",
":",
"vocab_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"analysis",
",",
"feature_transforms",
".",
"VOCAB_ANALYSIS_FILE",
"%",
"column_name",
")",
"if",
"not",
"file_io",
".",
"f... | 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 |
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:
... | 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:
... | [
"def",
"get_item",
"(",
"env",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"for",
"key",
"in",
"name",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"isinstance",
"(",
"env",
",",
"dict",
")",
"and",
"key",
"in",
"env",
":",
"env",
"=",
"en... | 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 foun... | [
"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 |
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",
"(",
... | 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 |
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': ... | 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': ... | [
"def",
"configure_pipeline",
"(",
"p",
",",
"dataset",
",",
"model_dir",
",",
"output_csv",
",",
"output_bq_table",
")",
":",
"data",
"=",
"_util",
".",
"get_sources_from_dataset",
"(",
"p",
",",
"dataset",
",",
"'predict'",
")",
"if",
"len",
"(",
"dataset",... | 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 |
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.
... | 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.
... | [
"def",
"sampling_query",
"(",
"sql",
",",
"context",
",",
"fields",
"=",
"None",
",",
"count",
"=",
"5",
",",
"sampling",
"=",
"None",
",",
"udfs",
"=",
"None",
",",
"data_sources",
"=",
"None",
")",
":",
"return",
"Query",
"(",
"_sampling",
".",
"Sa... | 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 ... | [
"Returns",
"a",
"sampling",
"Query",
"for",
"the",
"SQL",
"object",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L37-L54 | train |
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'
... | 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'
... | [
"def",
"results",
"(",
"self",
",",
"use_cache",
"=",
"True",
",",
"dialect",
"=",
"None",
",",
"billing_tier",
"=",
"None",
")",
":",
"if",
"not",
"use_cache",
"or",
"(",
"self",
".",
"_results",
"is",
"None",
")",
":",
"self",
".",
"execute",
"(",
... | 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'... | [
"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 |
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... | 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... | [
"def",
"extract",
"(",
"self",
",",
"storage_uris",
",",
"format",
"=",
"'csv'",
",",
"csv_delimiter",
"=",
"','",
",",
"csv_header",
"=",
"True",
",",
"compress",
"=",
"False",
",",
"use_cache",
"=",
"True",
",",
"dialect",
"=",
"None",
",",
"billing_ti... | 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 ',').
... | [
"Exports",
"the",
"query",
"results",
"to",
"GCS",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L231-L261 | train |
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... | 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... | [
"def",
"to_dataframe",
"(",
"self",
",",
"start_row",
"=",
"0",
",",
"max_rows",
"=",
"None",
",",
"use_cache",
"=",
"True",
",",
"dialect",
"=",
"None",
",",
"billing_tier",
"=",
"None",
")",
":",
"return",
"self",
".",
"results",
"(",
"use_cache",
"=... | 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', 'sta... | [
"Exports",
"the",
"query",
"results",
"to",
"a",
"Pandas",
"dataframe",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L303-L323 | train |
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:... | 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:... | [
"def",
"sample",
"(",
"self",
",",
"count",
"=",
"5",
",",
"fields",
"=",
"None",
",",
"sampling",
"=",
"None",
",",
"use_cache",
"=",
"True",
",",
"dialect",
"=",
"None",
",",
"billing_tier",
"=",
"None",
")",
":",
"return",
"Query",
".",
"sampling_... | 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 tabl... | [
"Retrieves",
"a",
"sampling",
"of",
"rows",
"for",
"the",
"query",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L379-L406 | train |
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 Ta... | 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 Ta... | [
"def",
"execute",
"(",
"self",
",",
"table_name",
"=",
"None",
",",
"table_mode",
"=",
"'create'",
",",
"use_cache",
"=",
"True",
",",
"priority",
"=",
"'interactive'",
",",
"allow_large_results",
"=",
"False",
",",
"dialect",
"=",
"None",
",",
"billing_tier... | 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
... | [
"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 |
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.
f... | 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.
f... | [
"def",
"to_view",
"(",
"self",
",",
"view_name",
")",
":",
"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 |
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 wil... | 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 wil... | [
"def",
"format_help",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_cell_args",
":",
"return",
"super",
"(",
"CommandParser",
",",
"self",
")",
".",
"format_help",
"(",
")",
"else",
":",
"epilog",
"=",
"self",
".",
"epilog",
"self",
".",
"epilog",... | 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 |
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:
... | 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:
... | [
"def",
"_get_subparsers",
"(",
"self",
")",
":",
"subparsers",
"=",
"[",
"]",
"for",
"action",
"in",
"self",
".",
"_actions",
":",
"if",
"isinstance",
"(",
"action",
",",
"argparse",
".",
"_SubParsersAction",
")",
":",
"for",
"_",
",",
"subparser",
"in",... | Recursively get subparsers. | [
"Recursively",
"get",
"subparsers",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L101-L113 | train |
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 subparse... | 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 subparse... | [
"def",
"_get_subparser_line_args",
"(",
"self",
",",
"subparser_prog",
")",
":",
"subparsers",
"=",
"self",
".",
"_get_subparsers",
"(",
")",
"for",
"subparser",
"in",
"subparsers",
":",
"if",
"subparser_prog",
"==",
"subparser",
".",
"prog",
":",
"args_to_parse... | 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 |
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",
"s... | 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 |
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:
... | 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:
... | [
"def",
"add_cell_argument",
"(",
"self",
",",
"name",
",",
"help",
",",
"required",
"=",
"False",
")",
":",
"for",
"action",
"in",
"self",
".",
"_actions",
":",
"if",
"action",
".",
"dest",
"==",
"name",
":",
"raise",
"ValueError",
"(",
"'Arg \"%s\" was ... | 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 |
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 ... | 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 ... | [
"def",
"parse",
"(",
"self",
",",
"line",
",",
"cell",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"ipy",
"=",
"IPython",
".",
"get_ipython",
"(",
")",
"namespace",
"=",
"ipy",
".",
"user_ns",
"args",
"=",
"CommandP... | 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... | [
"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 |
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_fil... | 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_fil... | [
"def",
"_glob_events_files",
"(",
"self",
",",
"paths",
",",
"recursive",
")",
":",
"event_files",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
"dirs",
"=",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"path",
")",
"dirs",
"=",
"filter",
"(",
"lambda",... | 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 |
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):
... | 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):
... | [
"def",
"list_events",
"(",
"self",
")",
":",
"event_dir_dict",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"for",
"event_file",
"in",
"self",
".",
"_glob_events_files",
"(",
"self",
".",
"_paths",
",",
"recursive",
"=",
"True",
")",
":",
"dir"... | 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 |
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 i... | 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 i... | [
"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 opti... | [
"Create",
"an",
"external",
"table",
"for",
"a",
"GCS",
"object",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_federated_table.py#L24-L64 | train |
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... | 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... | [
"def",
"get_query_parameters",
"(",
"args",
",",
"cell_body",
",",
"date_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
":",
"env",
"=",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"notebook_environment",
"(",
")",
... | 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: arg... | [
"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",
"... | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L355-L382 | train |
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'.
... | 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'.
... | [
"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>'",
")",
"param_pattern",
"=",
"r'^\\s... | 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 (i... | [
"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 |
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 ... | 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 ... | [
"def",
"_datasource_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"name",
"=",
"args",
"[",
"'name'",
"]",
"paths",
"=",
"args",
"[",
"'paths'",
"]",
"data_format",
"=",
"(",
"args",
"[",
"'format'",
"]",
"or",
"'CSV'",
")",
".",
"lower",
"(",
")",... | 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 |
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... | 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... | [
"def",
"_query_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"name",
"=",
"args",
"[",
"'name'",
"]",
"udfs",
"=",
"args",
"[",
"'udfs'",
"]",
"datasources",
"=",
"args",
"[",
"'datasources'",
"]",
"subqueries",
"=",
"args",
"[",
"'subqueries'",
"]",
... | 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 |
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(... | 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(... | [
"def",
"_get_table",
"(",
"name",
")",
":",
"item",
"=",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"get_notebook_item",
"(",
"name",
")",
"if",
"isinstance",
"(",
"item",
",",
"bigquery",
".",
"Table",
")",
":",
"return",
"item",
"t... | 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 |
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 |
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... | 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... | [
"def",
"_dataset_line",
"(",
"args",
")",
":",
"if",
"args",
"[",
"'command'",
"]",
"==",
"'list'",
":",
"filter_",
"=",
"args",
"[",
"'filter'",
"]",
"if",
"args",
"[",
"'filter'",
"]",
"else",
"'*'",
"context",
"=",
"google",
".",
"datalab",
".",
"... | 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 |
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: o... | 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: o... | [
"def",
"_table_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"if",
"args",
"[",
"'command'",
"]",
"==",
"'list'",
":",
"filter_",
"=",
"args",
"[",
"'filter'",
"]",
"if",
"args",
"[",
"'filter'",
"]",
"else",
"'*'",
"if",
"args",
"[",
"'dataset'",
... | 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 interprete... | [
"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 |
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 = g... | 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 = g... | [
"def",
"_extract_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"env",
"=",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"notebook_environment",
"(",
")",
"config",
"=",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"par... | 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 |
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... | 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... | [
"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 |
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... | 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... | [
"def",
"_table_viewer",
"(",
"table",
",",
"rows_per_page",
"=",
"25",
",",
"fields",
"=",
"None",
")",
":",
"if",
"not",
"table",
".",
"exists",
"(",
")",
":",
"raise",
"Exception",
"(",
"'Table %s does not exist'",
"%",
"table",
".",
"full_name",
")",
... | 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 arra... | [
"Return",
"a",
"table",
"viewer",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L1074-L1186 | train |
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 th... | 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 th... | [
"def",
"_build_js",
"(",
"inputs",
",",
"outputs",
",",
"name",
",",
"implementation",
",",
"support_code",
")",
":",
"input_fields",
"=",
"json",
".",
"dumps",
"(",
"[",
"f",
"[",
"0",
"]",
"for",
"f",
"in",
"inputs",
"]",
")",
"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 log... | [
"Creates",
"a",
"BigQuery",
"SQL",
"UDF",
"javascript",
"object",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_udf.py#L59-L84 | train |
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... | 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... | [
"def",
"sampling_query",
"(",
"sql",
",",
"fields",
"=",
"None",
",",
"count",
"=",
"5",
",",
"sampling",
"=",
"None",
")",
":",
"if",
"sampling",
"is",
"None",
":",
"sampling",
"=",
"Sampling",
".",
"default",
"(",
"count",
"=",
"count",
",",
"field... | 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 appl... | [
"Returns",
"a",
"sampling",
"query",
"for",
"the",
"SQL",
"object",
"."
] | d9031901d5bca22fe0d5925d204e6698df9852e1 | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_sampling.py#L74-L88 | train |
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.st... | 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.st... | [
"def",
"_remove_nonascii",
"(",
"self",
",",
"df",
")",
":",
"df_copy",
"=",
"df",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"for",
"col",
"in",
"df_copy",
".",
"columns",
":",
"if",
"(",
"df_copy",
"[",
"col",
"]",
".",
"dtype",
"==",
"np",
".... | 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 |
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 dictiona... | 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 dictiona... | [
"def",
"plot",
"(",
"self",
",",
"data",
")",
":",
"import",
"IPython",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
"or",
"not",
"all",
"(",
"isinstance",
"(",
"v",
",",
"pd",
".",
"DataFrame",
")",
"for",
"v",
"in",
"data",
".",
"v... | 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 |
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) > 1... | 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) > 1... | [
"def",
"plot",
"(",
"self",
",",
"data",
",",
"height",
"=",
"1000",
",",
"render_large_data",
"=",
"False",
")",
":",
"import",
"IPython",
"if",
"not",
"isinstance",
"(",
"data",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"'Exp... | 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 |
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
... | 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
... | [
"def",
"DtypeToType",
"(",
"self",
",",
"dtype",
")",
":",
"if",
"dtype",
".",
"char",
"in",
"np",
".",
"typecodes",
"[",
"'AllFloat'",
"]",
":",
"return",
"self",
".",
"fs_proto",
".",
"FLOAT",
"elif",
"(",
"dtype",
".",
"char",
"in",
"np",
".",
"... | 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 |
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 Att... | 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 Att... | [
"def",
"NdarrayToEntry",
"(",
"self",
",",
"x",
")",
":",
"row_counts",
"=",
"[",
"]",
"for",
"row",
"in",
"x",
":",
"try",
":",
"rc",
"=",
"np",
".",
"count_nonzero",
"(",
"~",
"np",
".",
"isnan",
"(",
"row",
")",
")",
"if",
"rc",
"!=",
"0",
... | 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 |
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,
... | 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,
... | [
"def",
"serving_from_csv_input",
"(",
"train_config",
",",
"args",
",",
"keep_target",
")",
":",
"examples",
"=",
"tf",
".",
"placeholder",
"(",
"dtype",
"=",
"tf",
".",
"string",
",",
"shape",
"=",
"(",
"None",
",",
")",
",",
"name",
"=",
"'csv_input_st... | 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 |
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.... | 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.... | [
"def",
"parse_example_tensor",
"(",
"examples",
",",
"train_config",
",",
"keep_target",
")",
":",
"csv_header",
"=",
"[",
"]",
"if",
"keep_target",
":",
"csv_header",
"=",
"train_config",
"[",
"'csv_header'",
"]",
"else",
":",
"csv_header",
"=",
"[",
"name",
... | 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 |
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
... | 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
... | [
"def",
"get_estimator",
"(",
"output_dir",
",",
"train_config",
",",
"args",
")",
":",
"target_name",
"=",
"train_config",
"[",
"'target_column'",
"]",
"if",
"is_classification_model",
"(",
"args",
".",
"model_type",
")",
"and",
"target_name",
"not",
"in",
"trai... | 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... | [
"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 |
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_... | 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_... | [
"def",
"preprocess_input",
"(",
"features",
",",
"target",
",",
"train_config",
",",
"preprocess_output_dir",
",",
"model_type",
")",
":",
"target_name",
"=",
"train_config",
"[",
"'target_column'",
"]",
"key_name",
"=",
"train_config",
"[",
"'key_column'",
"]",
"... | 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 ... | [
"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 |
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.
... | 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.
... | [
"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_te... | 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 |
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 appl... | 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 appl... | [
"def",
"_tflearn_features",
"(",
"train_config",
",",
"args",
")",
":",
"feature_columns",
"=",
"[",
"]",
"target_name",
"=",
"train_config",
"[",
"'target_column'",
"]",
"key_name",
"=",
"train_config",
"[",
"'key_column'",
"]",
"for",
"name",
"in",
"train_conf... | 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_conf... | [
"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 |
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_f... | 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_f... | [
"def",
"get_vocabulary",
"(",
"preprocess_output_dir",
",",
"name",
")",
":",
"vocab_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"preprocess_output_dir",
",",
"CATEGORICAL_ANALYSIS",
"%",
"name",
")",
"if",
"not",
"file_io",
".",
"file_exists",
"(",
"voca... | 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 |
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(... | 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(... | [
"def",
"validate_metadata",
"(",
"train_config",
")",
":",
"if",
"len",
"(",
"train_config",
"[",
"'csv_header'",
"]",
")",
"!=",
"len",
"(",
"train_config",
"[",
"'csv_defaults'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'Unequal number of columns in input fea... | 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 |
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:
proj... | 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:
proj... | [
"def",
"get_default_id",
"(",
"credentials",
"=",
"None",
")",
":",
"project_id",
"=",
"_utils",
".",
"get_project_id",
"(",
")",
"if",
"project_id",
"is",
"None",
":",
"projects",
",",
"_",
"=",
"Projects",
"(",
"credentials",
")",
".",
"_retrieve_projects"... | 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 |
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('SPLI... | 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('SPLI... | [
"def",
"init_app",
"(",
"state",
")",
":",
"app",
"=",
"state",
".",
"app",
"app",
".",
"config",
".",
"setdefault",
"(",
"'SPLIT_ALLOW_MULTIPLE_EXPERIMENTS'",
",",
"False",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'SPLIT_DB_FAILOVER'",
",",
"Fals... | 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 |
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 alternat... | 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 alternat... | [
"def",
"finished",
"(",
"experiment_name",
",",
"reset",
"=",
"True",
")",
":",
"if",
"_exclude_visitor",
"(",
")",
":",
"return",
"redis",
"=",
"_get_redis_connection",
"(",
")",
"try",
":",
"experiment",
"=",
"Experiment",
".",
"find",
"(",
"redis",
",",... | 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 |
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 = ... | 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 = ... | [
"def",
"_is_robot",
"(",
")",
":",
"robot_regex",
"=",
"current_app",
".",
"config",
"[",
"'SPLIT_ROBOT_REGEX'",
"]",
"user_agent",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'User-Agent'",
",",
"''",
")",
"return",
"re",
".",
"search",
"(",
"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. | [
"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 |
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 |
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 |
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",
"... | 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 |
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... | 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... | [
"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 |
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... | 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... | [
"def",
"set_experiment_winner",
"(",
"experiment",
")",
":",
"redis",
"=",
"_get_redis_connection",
"(",
")",
"experiment",
"=",
"Experiment",
".",
"find",
"(",
"redis",
",",
"experiment",
")",
"if",
"experiment",
":",
"alternative_name",
"=",
"request",
".",
... | 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 |
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",
"(",
")",
"retur... | 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 |
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",
"(",
")",
"ret... | 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 |
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 =... | 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 =... | [
"def",
"_get_ipaddress",
"(",
"node",
")",
":",
"if",
"\"ipaddress\"",
"not",
"in",
"node",
":",
"with",
"settings",
"(",
"hide",
"(",
"'stdout'",
")",
",",
"warn_only",
"=",
"True",
")",
":",
"output",
"=",
"sudo",
"(",
"'ohai -l warn ipaddress'",
")",
... | 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 |
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
... | 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
... | [
"def",
"sync_node",
"(",
"node",
")",
":",
"if",
"node",
".",
"get",
"(",
"'dummy'",
")",
"or",
"'dummy'",
"in",
"node",
".",
"get",
"(",
"'tags'",
",",
"[",
"]",
")",
":",
"lib",
".",
"print_header",
"(",
"\"Skipping dummy: {0}\"",
".",
"format",
"(... | 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 |
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 ==... | 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 ==... | [
"def",
"build_dct",
"(",
"dic",
",",
"keys",
",",
"value",
")",
":",
"key",
"=",
"keys",
".",
"pop",
"(",
"0",
")",
"if",
"len",
"(",
"keys",
")",
":",
"dic",
".",
"setdefault",
"(",
"key",
",",
"{",
"}",
")",
"build_dct",
"(",
"dic",
"[",
"k... | 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 |
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",
",",
"{",
"}",
")",
"upd... | 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 |
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
-... | 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
-... | [
"def",
"_add_merged_attributes",
"(",
"node",
",",
"all_recipes",
",",
"all_roles",
")",
":",
"attributes",
"=",
"{",
"}",
"for",
"recipe",
"in",
"node",
"[",
"'recipes'",
"]",
":",
"found",
"=",
"False",
"for",
"r",
"in",
"all_recipes",
":",
"if",
"reci... | 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... | [
"Merges",
"attributes",
"from",
"cookbooks",
"node",
"and",
"roles"
] | aab8c94081b38100a69cc100bc4278ae7419c58e | https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L232-L300 | train |
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 ... | 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 ... | [
"def",
"build_node_data_bag",
"(",
")",
":",
"nodes",
"=",
"lib",
".",
"get_nodes",
"(",
")",
"node_data_bag_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'data_bags'",
",",
"'node'",
")",
"remove_local_node_data_bag",
"(",
")",
"os",
".",
"makedirs",
... | 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... | [
"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 |
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",
"("... | 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 |
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_... | 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_... | [
"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 '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 |
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",
"(",
"\"r... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.