repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
googledatalab/pydatalab
google/datalab/ml/_confusion_matrix.py
ConfusionMatrix.from_bigquery
def from_bigquery(sql): """Create a ConfusionMatrix from a BigQuery table or query. Args: sql: Can be one of: A SQL query string. A Bigquery table string. A Query object defined with '%%bq query --name [query_name]'. The query results or table must include "target", "p...
python
def from_bigquery(sql): """Create a ConfusionMatrix from a BigQuery table or query. Args: sql: Can be one of: A SQL query string. A Bigquery table string. A Query object defined with '%%bq query --name [query_name]'. The query results or table must include "target", "p...
[ "def", "from_bigquery", "(", "sql", ")", ":", "if", "isinstance", "(", "sql", ",", "bq", ".", "Query", ")", ":", "sql", "=", "sql", ".", "_expanded_sql", "(", ")", "parts", "=", "sql", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")"...
Create a ConfusionMatrix from a BigQuery table or query. Args: sql: Can be one of: A SQL query string. A Bigquery table string. A Query object defined with '%%bq query --name [query_name]'. The query results or table must include "target", "predicted" columns. Returns:...
[ "Create", "a", "ConfusionMatrix", "from", "a", "BigQuery", "table", "or", "query", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L80-L113
googledatalab/pydatalab
google/datalab/ml/_confusion_matrix.py
ConfusionMatrix.to_dataframe
def to_dataframe(self): """Convert the confusion matrix to a dataframe. Returns: A DataFrame with "target", "predicted", "count" columns. """ data = [] for target_index, target_row in enumerate(self._cm): for predicted_index, count in enumerate(target_row): data.append((self._l...
python
def to_dataframe(self): """Convert the confusion matrix to a dataframe. Returns: A DataFrame with "target", "predicted", "count" columns. """ data = [] for target_index, target_row in enumerate(self._cm): for predicted_index, count in enumerate(target_row): data.append((self._l...
[ "def", "to_dataframe", "(", "self", ")", ":", "data", "=", "[", "]", "for", "target_index", ",", "target_row", "in", "enumerate", "(", "self", ".", "_cm", ")", ":", "for", "predicted_index", ",", "count", "in", "enumerate", "(", "target_row", ")", ":", ...
Convert the confusion matrix to a dataframe. Returns: A DataFrame with "target", "predicted", "count" columns.
[ "Convert", "the", "confusion", "matrix", "to", "a", "dataframe", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L115-L127
googledatalab/pydatalab
google/datalab/ml/_confusion_matrix.py
ConfusionMatrix.plot
def plot(self, figsize=None, rotation=45): """Plot the confusion matrix. Args: figsize: tuple (x, y) of ints. Sets the size of the figure rotation: the rotation angle of the labels on the x-axis. """ fig, ax = plt.subplots(figsize=figsize) plt.imshow(self._cm, interpolation='nearest',...
python
def plot(self, figsize=None, rotation=45): """Plot the confusion matrix. Args: figsize: tuple (x, y) of ints. Sets the size of the figure rotation: the rotation angle of the labels on the x-axis. """ fig, ax = plt.subplots(figsize=figsize) plt.imshow(self._cm, interpolation='nearest',...
[ "def", "plot", "(", "self", ",", "figsize", "=", "None", ",", "rotation", "=", "45", ")", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figsize", ")", "plt", ".", "imshow", "(", "self", ".", "_cm", ",", "interpolation", ...
Plot the confusion matrix. Args: figsize: tuple (x, y) of ints. Sets the size of the figure rotation: the rotation angle of the labels on the x-axis.
[ "Plot", "the", "confusion", "matrix", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L129-L159
googledatalab/pydatalab
google/datalab/contrib/pipeline/composer/_api.py
Api.get_environment_details
def get_environment_details(zone, environment): """ Issues a request to Composer to get the environment details. Args: zone: GCP zone of the composer environment environment: name of the Composer environment Returns: A parsed result object. Raises: Exception if there is an error...
python
def get_environment_details(zone, environment): """ Issues a request to Composer to get the environment details. Args: zone: GCP zone of the composer environment environment: name of the Composer environment Returns: A parsed result object. Raises: Exception if there is an error...
[ "def", "get_environment_details", "(", "zone", ",", "environment", ")", ":", "default_context", "=", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", "url", "=", "(", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_ENVIRONMENTS_PATH_FORMA...
Issues a request to Composer to get the environment details. Args: zone: GCP zone of the composer environment environment: name of the Composer environment Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
[ "Issues", "a", "request", "to", "Composer", "to", "get", "the", "environment", "details", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/composer/_api.py#L24-L39
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.buckets_delete
def buckets_delete(self, bucket): """Issues a request to delete a bucket. Args: bucket: the name of the bucket. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket) google.datalab.utils.Http.request(url, method='DELET...
python
def buckets_delete(self, bucket): """Issues a request to delete a bucket. Args: bucket: the name of the bucket. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket) google.datalab.utils.Http.request(url, method='DELET...
[ "def", "buckets_delete", "(", "self", ",", "bucket", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_BUCKET_PATH", "%", "bucket", ")", "google", ".", "datalab", ".", "utils", ".", "Http", ".", "request", "(", "url", ",", "metho...
Issues a request to delete a bucket. Args: bucket: the name of the bucket. Raises: Exception if there is an error performing the operation.
[ "Issues", "a", "request", "to", "delete", "a", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L72-L82
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.buckets_get
def buckets_get(self, bucket, projection='noAcl'): """Issues a request to retrieve information about a bucket. Args: bucket: the name of the bucket. projection: the projection of the bucket information to retrieve. Returns: A parsed bucket information dictionary. Raises: Excepti...
python
def buckets_get(self, bucket, projection='noAcl'): """Issues a request to retrieve information about a bucket. Args: bucket: the name of the bucket. projection: the projection of the bucket information to retrieve. Returns: A parsed bucket information dictionary. Raises: Excepti...
[ "def", "buckets_get", "(", "self", ",", "bucket", ",", "projection", "=", "'noAcl'", ")", ":", "args", "=", "{", "'projection'", ":", "projection", "}", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_BUCKET_PATH", "%", "bucket", ")", "ret...
Issues a request to retrieve information about a bucket. Args: bucket: the name of the bucket. projection: the projection of the bucket information to retrieve. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error performing the operation.
[ "Issues", "a", "request", "to", "retrieve", "information", "about", "a", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L84-L97
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.buckets_list
def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): """Issues a request to retrieve the list of buckets. Args: projection: the projection of the bucket information to retrieve. max_results: an optional maximum number of objects to retrieve. page_token:...
python
def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): """Issues a request to retrieve the list of buckets. Args: projection: the projection of the bucket information to retrieve. max_results: an optional maximum number of objects to retrieve. page_token:...
[ "def", "buckets_list", "(", "self", ",", "projection", "=", "'noAcl'", ",", "max_results", "=", "0", ",", "page_token", "=", "None", ",", "project_id", "=", "None", ")", ":", "if", "max_results", "==", "0", ":", "max_results", "=", "Api", ".", "_MAX_RESU...
Issues a request to retrieve the list of buckets. Args: projection: the projection of the bucket information to retrieve. max_results: an optional maximum number of objects to retrieve. page_token: an optional token to continue the retrieval. project_id: the project whose buckets should be ...
[ "Issues", "a", "request", "to", "retrieve", "the", "list", "of", "buckets", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L99-L122
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.object_download
def object_download(self, bucket, key, start_offset=0, byte_count=None): """Reads the contents of an object as text. Args: bucket: the name of the bucket containing the object. key: the key of the object to be read. start_offset: the start offset of bytes to read. byte_count: the number...
python
def object_download(self, bucket, key, start_offset=0, byte_count=None): """Reads the contents of an object as text. Args: bucket: the name of the bucket containing the object. key: the key of the object to be read. start_offset: the start offset of bytes to read. byte_count: the number...
[ "def", "object_download", "(", "self", ",", "bucket", ",", "key", ",", "start_offset", "=", "0", ",", "byte_count", "=", "None", ")", ":", "args", "=", "{", "'alt'", ":", "'media'", "}", "headers", "=", "{", "}", "if", "start_offset", ">", "0", "or",...
Reads the contents of an object as text. Args: bucket: the name of the bucket containing the object. key: the key of the object to be read. start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text con...
[ "Reads", "the", "contents", "of", "an", "object", "as", "text", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L124-L146
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.object_upload
def object_upload(self, bucket, key, content, content_type): """Writes text content to the object. Args: bucket: the name of the bucket containing the object. key: the key of the object to be written. content: the text content to be written. content_type: the type of text content. R...
python
def object_upload(self, bucket, key, content, content_type): """Writes text content to the object. Args: bucket: the name of the bucket containing the object. key: the key of the object to be written. content: the text content to be written. content_type: the type of text content. R...
[ "def", "object_upload", "(", "self", ",", "bucket", ",", "key", ",", "content", ",", "content_type", ")", ":", "args", "=", "{", "'uploadType'", ":", "'media'", ",", "'name'", ":", "key", "}", "headers", "=", "{", "'Content-Type'", ":", "content_type", "...
Writes text content to the object. Args: bucket: the name of the bucket containing the object. key: the key of the object to be written. content: the text content to be written. content_type: the type of text content. Raises: Exception if the object could not be written to.
[ "Writes", "text", "content", "to", "the", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L148-L164
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.objects_list
def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): """Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. prefix: an optional key prefix. delimiter: an ...
python
def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False, max_results=0, page_token=None): """Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. prefix: an optional key prefix. delimiter: an ...
[ "def", "objects_list", "(", "self", ",", "bucket", ",", "prefix", "=", "None", ",", "delimiter", "=", "None", ",", "projection", "=", "'noAcl'", ",", "versions", "=", "False", ",", "max_results", "=", "0", ",", "page_token", "=", "None", ")", ":", "if"...
Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. prefix: an optional key prefix. delimiter: an optional key delimiter. projection: the projection of the objects to retrieve. versions: whether to list each version of a file as a distinct o...
[ "Issues", "a", "request", "to", "retrieve", "information", "about", "an", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L215-L248
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.objects_patch
def objects_patch(self, bucket, key, info): """Updates the metadata associated with an object. Args: bucket: the name of the bucket containing the object. key: the key of the object being updated. info: the metadata to update. Returns: A parsed object information dictionary. Rai...
python
def objects_patch(self, bucket, key, info): """Updates the metadata associated with an object. Args: bucket: the name of the bucket containing the object. key: the key of the object being updated. info: the metadata to update. Returns: A parsed object information dictionary. Rai...
[ "def", "objects_patch", "(", "self", ",", "bucket", ",", "key", ",", "info", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_OBJECT_PATH", "%", "(", "bucket", ",", "Api", ".", "_escape_key", "(", "key", ")", ")", ")", "return...
Updates the metadata associated with an object. Args: bucket: the name of the bucket containing the object. key: the key of the object being updated. info: the metadata to update. Returns: A parsed object information dictionary. Raises: Exception if there is an error performin...
[ "Updates", "the", "metadata", "associated", "with", "an", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L250-L264
googledatalab/pydatalab
google/datalab/storage/_api.py
Api.verify_permitted_to_read
def verify_permitted_to_read(gs_path): """Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read. """ # TODO(qimingj): Storage APIs need to be modified to allo...
python
def verify_permitted_to_read(gs_path): """Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read. """ # TODO(qimingj): Storage APIs need to be modified to allo...
[ "def", "verify_permitted_to_read", "(", "gs_path", ")", ":", "# TODO(qimingj): Storage APIs need to be modified to allow absence of project", "# or credential on Objects. When that happens we can move the function", "# to Objects class.", "from", ".", "import", ...
Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read.
[ "Check", "if", "the", "user", "has", "permissions", "to", "read", "from", "the", "given", "path", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_api.py#L272-L301
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_api.py
preprocess_async
def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None): """Preprocess data. Produce output that can be used by training efficiently. Args: train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet. If eval_dataset is None, the pipel...
python
def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None): """Preprocess data. Produce output that can be used by training efficiently. Args: train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet. If eval_dataset is None, the pipel...
[ "def", "preprocess_async", "(", "train_dataset", ",", "output_dir", ",", "eval_dataset", "=", "None", ",", "checkpoint", "=", "None", ",", "cloud", "=", "None", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilte...
Preprocess data. Produce output that can be used by training efficiently. Args: train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet. If eval_dataset is None, the pipeline will randomly split train_dataset into train/eval set with 7:3 ratio. output_dir: The ...
[ "Preprocess", "data", ".", "Produce", "output", "that", "can", "be", "used", "by", "training", "efficiently", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L25-L52
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_api.py
preprocess
def preprocess(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None): """Blocking version of preprocess_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. """ with warnings.catch_warnings(): warnings.simplefilter("ig...
python
def preprocess(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None): """Blocking version of preprocess_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. """ with warnings.catch_warnings(): warnings.simplefilter("ig...
[ "def", "preprocess", "(", "train_dataset", ",", "output_dir", ",", "eval_dataset", "=", "None", ",", "checkpoint", "=", "None", ",", "cloud", "=", "None", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", ...
Blocking version of preprocess_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value.
[ "Blocking", "version", "of", "preprocess_async", "()", ".", "The", "only", "difference", "is", "that", "it", "blocks", "the", "caller", "until", "the", "job", "finishes", "and", "it", "does", "not", "have", "a", "return", "value", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L55-L63
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_api.py
train_async
def train_async(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None): """Train model. The output can be used for batch prediction or online deployment. Args: input_dir: A directory path containing preprocessed results. Can be local or GCS path. batch_size: size of batch used for train...
python
def train_async(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None): """Train model. The output can be used for batch prediction or online deployment. Args: input_dir: A directory path containing preprocessed results. Can be local or GCS path. batch_size: size of batch used for train...
[ "def", "train_async", "(", "input_dir", ",", "batch_size", ",", "max_steps", ",", "output_dir", ",", "checkpoint", "=", "None", ",", "cloud", "=", "None", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", ...
Train model. The output can be used for batch prediction or online deployment. Args: input_dir: A directory path containing preprocessed results. Can be local or GCS path. batch_size: size of batch used for training. max_steps: number of steps to train. output_dir: The output directory to use. Can be...
[ "Train", "model", ".", "The", "output", "can", "be", "used", "for", "batch", "prediction", "or", "online", "deployment", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L66-L86
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_api.py
train
def train(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None): """Blocking version of train_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. """ with warnings.catch_warnings(): warnings.simplefilter("ignore") ...
python
def train(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None): """Blocking version of train_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. """ with warnings.catch_warnings(): warnings.simplefilter("ignore") ...
[ "def", "train", "(", "input_dir", ",", "batch_size", ",", "max_steps", ",", "output_dir", ",", "checkpoint", "=", "None", ",", "cloud", "=", "None", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", ...
Blocking version of train_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value.
[ "Blocking", "version", "of", "train_async", "()", ".", "The", "only", "difference", "is", "that", "it", "blocks", "the", "caller", "until", "the", "job", "finishes", "and", "it", "does", "not", "have", "a", "return", "value", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L89-L97
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_api.py
predict
def predict(model, image_files, resize=False, show_image=True, cloud=None): """Predict using an model in a local or GCS directory (offline), or a deployed model (online). Args: model: if cloud is None, a local or GCS directory of a trained model. Otherwise, it specifies a deployed model identified by m...
python
def predict(model, image_files, resize=False, show_image=True, cloud=None): """Predict using an model in a local or GCS directory (offline), or a deployed model (online). Args: model: if cloud is None, a local or GCS directory of a trained model. Otherwise, it specifies a deployed model identified by m...
[ "def", "predict", "(", "model", ",", "image_files", ",", "resize", "=", "False", ",", "show_image", "=", "True", ",", "cloud", "=", "None", ")", ":", "print", "(", "'Predicting...'", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warning...
Predict using an model in a local or GCS directory (offline), or a deployed model (online). Args: model: if cloud is None, a local or GCS directory of a trained model. Otherwise, it specifies a deployed model identified by model.version, such as "imagemodel.v1". image_files: The paths to the image fi...
[ "Predict", "using", "an", "model", "in", "a", "local", "or", "GCS", "directory", "(", "offline", ")", "or", "a", "deployed", "model", "(", "online", ")", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L100-L123
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_api.py
batch_predict_async
def batch_predict_async(dataset, model_dir, output_csv=None, output_bq_table=None, cloud=None): """Batch prediction with an offline model. Args: dataset: CsvDataSet or BigQueryDataSet for batch prediction input. Can contain either one column 'image_url', or two columns with another being 'label'. m...
python
def batch_predict_async(dataset, model_dir, output_csv=None, output_bq_table=None, cloud=None): """Batch prediction with an offline model. Args: dataset: CsvDataSet or BigQueryDataSet for batch prediction input. Can contain either one column 'image_url', or two columns with another being 'label'. m...
[ "def", "batch_predict_async", "(", "dataset", ",", "model_dir", ",", "output_csv", "=", "None", ",", "output_bq_table", "=", "None", ",", "cloud", "=", "None", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter...
Batch prediction with an offline model. Args: dataset: CsvDataSet or BigQueryDataSet for batch prediction input. Can contain either one column 'image_url', or two columns with another being 'label'. model_dir: The directory of a trained inception model. Can be local or GCS paths. output_csv: The ...
[ "Batch", "prediction", "with", "an", "offline", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L126-L156
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_api.py
batch_predict
def batch_predict(dataset, model_dir, output_csv=None, output_bq_table=None, cloud=None): """Blocking version of batch_predict_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. """ with warnings.catch_warnings(): warnings.simplefilter("...
python
def batch_predict(dataset, model_dir, output_csv=None, output_bq_table=None, cloud=None): """Blocking version of batch_predict_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value. """ with warnings.catch_warnings(): warnings.simplefilter("...
[ "def", "batch_predict", "(", "dataset", ",", "model_dir", ",", "output_csv", "=", "None", ",", "output_bq_table", "=", "None", ",", "cloud", "=", "None", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "...
Blocking version of batch_predict_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value.
[ "Blocking", "version", "of", "batch_predict_async", "()", ".", "The", "only", "difference", "is", "that", "it", "blocks", "the", "caller", "until", "the", "job", "finishes", "and", "it", "does", "not", "have", "a", "return", "value", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L159-L167
googledatalab/pydatalab
google/datalab/bigquery/_job.py
Job._refresh_state
def _refresh_state(self): """ Get the state of a job. If the job is complete this does nothing; otherwise it gets a refreshed copy of the job resource. """ # TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than # a second ago should we return the cached value? ...
python
def _refresh_state(self): """ Get the state of a job. If the job is complete this does nothing; otherwise it gets a refreshed copy of the job resource. """ # TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than # a second ago should we return the cached value? ...
[ "def", "_refresh_state", "(", "self", ")", ":", "# TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than", "# a second ago should we return the cached value?", "if", "self", ".", "_is_complete", ":", "return", "try", ":", "response", "=", "self", "...
Get the state of a job. If the job is complete this does nothing; otherwise it gets a refreshed copy of the job resource.
[ "Get", "the", "state", "of", "a", "job", ".", "If", "the", "job", "is", "complete", "this", "does", "nothing", ";", "otherwise", "it", "gets", "a", "refreshed", "copy", "of", "the", "job", "resource", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_job.py#L43-L70
googledatalab/pydatalab
datalab/stackdriver/commands/_monitoring.py
monitoring
def monitoring(line, cell=None): """Implements the monitoring cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell. """ parser = datalab.utils.commands.CommandParser(prog='monitoring', description=( 'Execute various Monitorin...
python
def monitoring(line, cell=None): """Implements the monitoring cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell. """ parser = datalab.utils.commands.CommandParser(prog='monitoring', description=( 'Execute various Monitorin...
[ "def", "monitoring", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'monitoring'", ",", "description", "=", "(", "'Execute various Monitoring-related operations. ...
Implements the monitoring cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
[ "Implements", "the", "monitoring", "cell", "magic", "for", "ipython", "notebooks", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L27-L73
googledatalab/pydatalab
datalab/stackdriver/commands/_monitoring.py
_list_metric_descriptors
def _list_metric_descriptors(args, _): """Lists the metric descriptors in the project.""" project_id = args['project'] pattern = args['type'] or '*' descriptors = gcm.MetricDescriptors(project_id=project_id) dataframe = descriptors.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
python
def _list_metric_descriptors(args, _): """Lists the metric descriptors in the project.""" project_id = args['project'] pattern = args['type'] or '*' descriptors = gcm.MetricDescriptors(project_id=project_id) dataframe = descriptors.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
[ "def", "_list_metric_descriptors", "(", "args", ",", "_", ")", ":", "project_id", "=", "args", "[", "'project'", "]", "pattern", "=", "args", "[", "'type'", "]", "or", "'*'", "descriptors", "=", "gcm", ".", "MetricDescriptors", "(", "project_id", "=", "pro...
Lists the metric descriptors in the project.
[ "Lists", "the", "metric", "descriptors", "in", "the", "project", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L76-L82
googledatalab/pydatalab
datalab/stackdriver/commands/_monitoring.py
_list_resource_descriptors
def _list_resource_descriptors(args, _): """Lists the resource descriptors in the project.""" project_id = args['project'] pattern = args['type'] or '*' descriptors = gcm.ResourceDescriptors(project_id=project_id) dataframe = descriptors.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
python
def _list_resource_descriptors(args, _): """Lists the resource descriptors in the project.""" project_id = args['project'] pattern = args['type'] or '*' descriptors = gcm.ResourceDescriptors(project_id=project_id) dataframe = descriptors.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
[ "def", "_list_resource_descriptors", "(", "args", ",", "_", ")", ":", "project_id", "=", "args", "[", "'project'", "]", "pattern", "=", "args", "[", "'type'", "]", "or", "'*'", "descriptors", "=", "gcm", ".", "ResourceDescriptors", "(", "project_id", "=", ...
Lists the resource descriptors in the project.
[ "Lists", "the", "resource", "descriptors", "in", "the", "project", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L85-L91
googledatalab/pydatalab
datalab/stackdriver/commands/_monitoring.py
_list_groups
def _list_groups(args, _): """Lists the groups in the project.""" project_id = args['project'] pattern = args['name'] or '*' groups = gcm.Groups(project_id=project_id) dataframe = groups.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
python
def _list_groups(args, _): """Lists the groups in the project.""" project_id = args['project'] pattern = args['name'] or '*' groups = gcm.Groups(project_id=project_id) dataframe = groups.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
[ "def", "_list_groups", "(", "args", ",", "_", ")", ":", "project_id", "=", "args", "[", "'project'", "]", "pattern", "=", "args", "[", "'name'", "]", "or", "'*'", "groups", "=", "gcm", ".", "Groups", "(", "project_id", "=", "project_id", ")", "datafram...
Lists the groups in the project.
[ "Lists", "the", "groups", "in", "the", "project", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L94-L100
googledatalab/pydatalab
datalab/stackdriver/commands/_monitoring.py
_render_dataframe
def _render_dataframe(dataframe): """Helper to render a dataframe as an HTML table.""" data = dataframe.to_dict(orient='records') fields = dataframe.columns.tolist() return IPython.core.display.HTML( datalab.utils.commands.HtmlBuilder.render_table(data, fields))
python
def _render_dataframe(dataframe): """Helper to render a dataframe as an HTML table.""" data = dataframe.to_dict(orient='records') fields = dataframe.columns.tolist() return IPython.core.display.HTML( datalab.utils.commands.HtmlBuilder.render_table(data, fields))
[ "def", "_render_dataframe", "(", "dataframe", ")", ":", "data", "=", "dataframe", ".", "to_dict", "(", "orient", "=", "'records'", ")", "fields", "=", "dataframe", ".", "columns", ".", "tolist", "(", ")", "return", "IPython", ".", "core", ".", "display", ...
Helper to render a dataframe as an HTML table.
[ "Helper", "to", "render", "a", "dataframe", "as", "an", "HTML", "table", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L103-L108
googledatalab/pydatalab
google/datalab/utils/commands/_job.py
html_job_status
def html_job_status(job_name, job_type, refresh_interval, html_on_running, html_on_success): """create html representation of status of a job (long running operation). Args: job_name: the full name of the job. job_type: type of job. Can be 'local' or 'cloud'. refresh_interval: how often should the clie...
python
def html_job_status(job_name, job_type, refresh_interval, html_on_running, html_on_success): """create html representation of status of a job (long running operation). Args: job_name: the full name of the job. job_type: type of job. Can be 'local' or 'cloud'. refresh_interval: how often should the clie...
[ "def", "html_job_status", "(", "job_name", ",", "job_type", ",", "refresh_interval", ",", "html_on_running", ",", "html_on_success", ")", ":", "_HTML_TEMPLATE", "=", "\"\"\"\n <div class=\"jobstatus\" id=\"%s\">\n </div>\n <script>\n require(['datalab/job', 'datalab/ele...
create html representation of status of a job (long running operation). Args: job_name: the full name of the job. job_type: type of job. Can be 'local' or 'cloud'. refresh_interval: how often should the client refresh status. html_on_running: additional html that the job view needs to include on job ...
[ "create", "html", "representation", "of", "status", "of", "a", "job", "(", "long", "running", "operation", ")", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_job.py#L34-L57
googledatalab/pydatalab
google/datalab/utils/commands/_job.py
_get_job_status
def _get_job_status(line): """magic used as an endpoint for client to get job status. %_get_job_status <name> Returns: A JSON object of the job status. """ try: args = line.strip().split() job_name = args[0] job = None if job_name in _local_jobs: job = _local_jobs[job_name] ...
python
def _get_job_status(line): """magic used as an endpoint for client to get job status. %_get_job_status <name> Returns: A JSON object of the job status. """ try: args = line.strip().split() job_name = args[0] job = None if job_name in _local_jobs: job = _local_jobs[job_name] ...
[ "def", "_get_job_status", "(", "line", ")", ":", "try", ":", "args", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "job_name", "=", "args", "[", "0", "]", "job", "=", "None", "if", "job_name", "in", "_local_jobs", ":", "job", "=", ...
magic used as an endpoint for client to get job status. %_get_job_status <name> Returns: A JSON object of the job status.
[ "magic", "used", "as", "an", "endpoint", "for", "client", "to", "get", "job", "status", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_job.py#L61-L89
googledatalab/pydatalab
google/datalab/storage/_object.py
ObjectMetadata.updated_on
def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s else None
python
def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s else None
[ "def", "updated_on", "(", "self", ")", ":", "s", "=", "self", ".", "_info", ".", "get", "(", "'updated'", ",", "None", ")", "return", "dateutil", ".", "parser", ".", "parse", "(", "s", ")", "if", "s", "else", "None" ]
The updated timestamp of the object as a datetime.datetime.
[ "The", "updated", "timestamp", "of", "the", "object", "as", "a", "datetime", ".", "datetime", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L69-L72
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.delete
def delete(self, wait_for_deletion=True): """Deletes this object from its bucket. Args: wait_for_deletion: If True, we poll until this object no longer appears in objects.list operations for this bucket before returning. Raises: Exception if there was an error deleting the object. ...
python
def delete(self, wait_for_deletion=True): """Deletes this object from its bucket. Args: wait_for_deletion: If True, we poll until this object no longer appears in objects.list operations for this bucket before returning. Raises: Exception if there was an error deleting the object. ...
[ "def", "delete", "(", "self", ",", "wait_for_deletion", "=", "True", ")", ":", "if", "self", ".", "exists", "(", ")", ":", "try", ":", "self", ".", "_api", ".", "objects_delete", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ")", "except", ...
Deletes this object from its bucket. Args: wait_for_deletion: If True, we poll until this object no longer appears in objects.list operations for this bucket before returning. Raises: Exception if there was an error deleting the object.
[ "Deletes", "this", "object", "from", "its", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L147-L172
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.metadata
def metadata(self): """Retrieves metadata about the object. Returns: An ObjectMetadata instance with information about this object. Raises: Exception if there was an error requesting the object's metadata. """ if self._info is None: try: self._info = self._api.objects_get(...
python
def metadata(self): """Retrieves metadata about the object. Returns: An ObjectMetadata instance with information about this object. Raises: Exception if there was an error requesting the object's metadata. """ if self._info is None: try: self._info = self._api.objects_get(...
[ "def", "metadata", "(", "self", ")", ":", "if", "self", ".", "_info", "is", "None", ":", "try", ":", "self", ".", "_info", "=", "self", ".", "_api", ".", "objects_get", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ")", "except", "Exceptio...
Retrieves metadata about the object. Returns: An ObjectMetadata instance with information about this object. Raises: Exception if there was an error requesting the object's metadata.
[ "Retrieves", "metadata", "about", "the", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L175-L188
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.read_stream
def read_stream(self, start_offset=0, byte_count=None): """Reads the content of this object as text. Args: start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text content within the object. Raises: ...
python
def read_stream(self, start_offset=0, byte_count=None): """Reads the content of this object as text. Args: start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text content within the object. Raises: ...
[ "def", "read_stream", "(", "self", ",", "start_offset", "=", "0", ",", "byte_count", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_api", ".", "object_download", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ",", "start_offset", "...
Reads the content of this object as text. Args: start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text content within the object. Raises: Exception if there was an error requesting the object's conten...
[ "Reads", "the", "content", "of", "this", "object", "as", "text", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L190-L205
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.read_lines
def read_lines(self, max_lines=None): """Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if the...
python
def read_lines(self, max_lines=None): """Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if the...
[ "def", "read_lines", "(", "self", ",", "max_lines", "=", "None", ")", ":", "if", "max_lines", "is", "None", ":", "return", "self", ".", "read_stream", "(", ")", ".", "split", "(", "'\\n'", ")", "max_to_read", "=", "self", ".", "metadata", ".", "size", ...
Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if there was an error requesting the object's conte...
[ "Reads", "the", "content", "of", "this", "object", "as", "text", "and", "return", "a", "list", "of", "lines", "up", "to", "some", "max", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L217-L243
googledatalab/pydatalab
datalab/data/_csv.py
Csv.sample_to
def sample_to(self, count, skip_header_rows, strategy, target): """Sample rows from GCS or local file and save results to target file. Args: count: number of rows to sample. If strategy is "BIGQUERY", it is used as approximate number. skip_header_rows: whether to skip first row when reading from so...
python
def sample_to(self, count, skip_header_rows, strategy, target): """Sample rows from GCS or local file and save results to target file. Args: count: number of rows to sample. If strategy is "BIGQUERY", it is used as approximate number. skip_header_rows: whether to skip first row when reading from so...
[ "def", "sample_to", "(", "self", ",", "count", ",", "skip_header_rows", ",", "strategy", ",", "target", ")", ":", "# TODO(qimingj) Add unit test", "# Read data from source into DataFrame.", "if", "sys", ".", "version_info", ".", "major", ">", "2", ":", "xrange", "...
Sample rows from GCS or local file and save results to target file. Args: count: number of rows to sample. If strategy is "BIGQUERY", it is used as approximate number. skip_header_rows: whether to skip first row when reading from source. strategy: can be "LOCAL" or "BIGQUERY". If local, the sampl...
[ "Sample", "rows", "from", "GCS", "or", "local", "file", "and", "save", "results", "to", "target", "file", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_csv.py#L129-L183
googledatalab/pydatalab
google/datalab/utils/facets/base_feature_statistics_generator.py
BaseFeatureStatisticsGenerator.ProtoFromTfRecordFiles
def ProtoFromTfRecordFiles(self, files, max_entries=10000, features=None, is_sequence=False, iterator_options=None): """Creates a feature statistics proto from a set of TF...
python
def ProtoFromTfRecordFiles(self, files, max_entries=10000, features=None, is_sequence=False, iterator_options=None): """Creates a feature statistics proto from a set of TF...
[ "def", "ProtoFromTfRecordFiles", "(", "self", ",", "files", ",", "max_entries", "=", "10000", ",", "features", "=", "None", ",", "is_sequence", "=", "False", ",", "iterator_options", "=", "None", ")", ":", "datasets", "=", "[", "]", "for", "entry", "in", ...
Creates a feature statistics proto from a set of TFRecord files. Args: files: A list of dicts describing files for each dataset for the proto. Each entry contains a 'path' field with the path to the TFRecord file on disk and a 'name' field to identify the dataset in th...
[ "Creates", "a", "feature", "statistics", "proto", "from", "a", "set", "of", "TFRecord", "files", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_feature_statistics_generator.py#L39-L72
googledatalab/pydatalab
google/datalab/utils/facets/base_feature_statistics_generator.py
BaseFeatureStatisticsGenerator._ParseExample
def _ParseExample(self, example_features, example_feature_lists, entries, index): """Parses data from an example, populating a dictionary of feature values. Args: example_features: A map of strings to tf.Features from the example. example_feature_lists: A map of strings to tf.Fe...
python
def _ParseExample(self, example_features, example_feature_lists, entries, index): """Parses data from an example, populating a dictionary of feature values. Args: example_features: A map of strings to tf.Features from the example. example_feature_lists: A map of strings to tf.Fe...
[ "def", "_ParseExample", "(", "self", ",", "example_features", ",", "example_feature_lists", ",", "entries", ",", "index", ")", ":", "features_seen", "=", "set", "(", ")", "for", "feature_list", ",", "is_feature", "in", "zip", "(", "[", "example_features", ",",...
Parses data from an example, populating a dictionary of feature values. Args: example_features: A map of strings to tf.Features from the example. example_feature_lists: A map of strings to tf.FeatureLists from the example. entries: A dictionary of all features parsed thus far and arrays o...
[ "Parses", "data", "from", "an", "example", "populating", "a", "dictionary", "of", "feature", "values", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_feature_statistics_generator.py#L74-L160
googledatalab/pydatalab
google/datalab/utils/facets/base_feature_statistics_generator.py
BaseFeatureStatisticsGenerator._GetEntries
def _GetEntries(self, paths, max_entries, iterator_from_file, is_sequence=False): """Extracts examples into a dictionary of feature values. Args: paths: A list of the paths to the files to parse. max_entries: The maximum number...
python
def _GetEntries(self, paths, max_entries, iterator_from_file, is_sequence=False): """Extracts examples into a dictionary of feature values. Args: paths: A list of the paths to the files to parse. max_entries: The maximum number...
[ "def", "_GetEntries", "(", "self", ",", "paths", ",", "max_entries", ",", "iterator_from_file", ",", "is_sequence", "=", "False", ")", ":", "entries", "=", "{", "}", "index", "=", "0", "for", "filepath", "in", "paths", ":", "reader", "=", "iterator_from_fi...
Extracts examples into a dictionary of feature values. Args: paths: A list of the paths to the files to parse. max_entries: The maximum number of examples to load. iterator_from_file: A method that takes a file path string and returns an iterator to the examples in that file. is_s...
[ "Extracts", "examples", "into", "a", "dictionary", "of", "feature", "values", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_feature_statistics_generator.py#L162-L200
googledatalab/pydatalab
google/datalab/utils/facets/base_feature_statistics_generator.py
BaseFeatureStatisticsGenerator._GetTfRecordEntries
def _GetTfRecordEntries(self, path, max_entries, is_sequence, iterator_options): """Extracts TFRecord examples into a dictionary of feature values. Args: path: The path to the TFRecord file(s). max_entries: The maximum number of examples to load. is_sequence: True if...
python
def _GetTfRecordEntries(self, path, max_entries, is_sequence, iterator_options): """Extracts TFRecord examples into a dictionary of feature values. Args: path: The path to the TFRecord file(s). max_entries: The maximum number of examples to load. is_sequence: True if...
[ "def", "_GetTfRecordEntries", "(", "self", ",", "path", ",", "max_entries", ",", "is_sequence", ",", "iterator_options", ")", ":", "return", "self", ".", "_GetEntries", "(", "[", "path", "]", ",", "max_entries", ",", "partial", "(", "tf", ".", "python_io", ...
Extracts TFRecord examples into a dictionary of feature values. Args: path: The path to the TFRecord file(s). max_entries: The maximum number of examples to load. is_sequence: True if the input data from 'path' are tf.SequenceExamples, False if tf.Examples. Defaults to false. ite...
[ "Extracts", "TFRecord", "examples", "into", "a", "dictionary", "of", "feature", "values", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_feature_statistics_generator.py#L202-L223
googledatalab/pydatalab
datalab/storage/_api.py
Api.buckets_insert
def buckets_insert(self, bucket, project_id=None): """Issues a request to create a new bucket. Args: bucket: the name of the bucket. project_id: the project to use when inserting the bucket. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error ...
python
def buckets_insert(self, bucket, project_id=None): """Issues a request to create a new bucket. Args: bucket: the name of the bucket. project_id: the project to use when inserting the bucket. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error ...
[ "def", "buckets_insert", "(", "self", ",", "bucket", ",", "project_id", "=", "None", ")", ":", "args", "=", "{", "'project'", ":", "project_id", "if", "project_id", "else", "self", ".", "_project_id", "}", "data", "=", "{", "'name'", ":", "bucket", "}", ...
Issues a request to create a new bucket. Args: bucket: the name of the bucket. project_id: the project to use when inserting the bucket. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error performing the operation.
[ "Issues", "a", "request", "to", "create", "a", "new", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L54-L69
googledatalab/pydatalab
datalab/storage/_api.py
Api.objects_copy
def objects_copy(self, source_bucket, source_key, target_bucket, target_key): """Updates the metadata associated with an object. Args: source_bucket: the name of the bucket containing the source object. source_key: the key of the source object being copied. target_bucket: the name of the buck...
python
def objects_copy(self, source_bucket, source_key, target_bucket, target_key): """Updates the metadata associated with an object. Args: source_bucket: the name of the bucket containing the source object. source_key: the key of the source object being copied. target_bucket: the name of the buck...
[ "def", "objects_copy", "(", "self", ",", "source_bucket", ",", "source_key", ",", "target_bucket", ",", "target_key", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_OBJECT_COPY_PATH", "%", "(", "source_bucket", ",", "Api", ".", "_es...
Updates the metadata associated with an object. Args: source_bucket: the name of the bucket containing the source object. source_key: the key of the source object being copied. target_bucket: the name of the bucket that will contain the copied object. target_key: the key of the copied objec...
[ "Updates", "the", "metadata", "associated", "with", "an", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L165-L180
googledatalab/pydatalab
datalab/storage/_api.py
Api.objects_delete
def objects_delete(self, bucket, key): """Deletes the specified object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._...
python
def objects_delete(self, bucket, key): """Deletes the specified object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._...
[ "def", "objects_delete", "(", "self", ",", "bucket", ",", "key", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_OBJECT_PATH", "%", "(", "bucket", ",", "Api", ".", "_escape_key", "(", "key", ")", ")", ")", "datalab", ".", "ut...
Deletes the specified object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. Raises: Exception if there is an error performing the operation.
[ "Deletes", "the", "specified", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L182-L193
googledatalab/pydatalab
datalab/storage/_api.py
Api.objects_get
def objects_get(self, bucket, key, projection='noAcl'): """Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. projection: the projection of the object to retrieve. Returns: A parsed object inf...
python
def objects_get(self, bucket, key, projection='noAcl'): """Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. projection: the projection of the object to retrieve. Returns: A parsed object inf...
[ "def", "objects_get", "(", "self", ",", "bucket", ",", "key", ",", "projection", "=", "'noAcl'", ")", ":", "args", "=", "{", "}", "if", "projection", "is", "not", "None", ":", "args", "[", "'projection'", "]", "=", "projection", "url", "=", "Api", "....
Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. projection: the projection of the object to retrieve. Returns: A parsed object information dictionary. Raises: Exception if there is an...
[ "Issues", "a", "request", "to", "retrieve", "information", "about", "an", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L195-L212
googledatalab/pydatalab
datalab/storage/_api.py
Api.verify_permitted_to_read
def verify_permitted_to_read(gs_path): """Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read. """ # TODO(qimingj): Storage APIs need to be modified to allo...
python
def verify_permitted_to_read(gs_path): """Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read. """ # TODO(qimingj): Storage APIs need to be modified to allo...
[ "def", "verify_permitted_to_read", "(", "gs_path", ")", ":", "# TODO(qimingj): Storage APIs need to be modified to allow absence of project", "# or credential on Items. When that happens we can move the function", "# to Items class.", "from", ".", "import", "_bu...
Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read.
[ "Check", "if", "the", "user", "has", "permissions", "to", "read", "from", "the", "given", "path", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L270-L299
googledatalab/pydatalab
datalab/bigquery/_query_job.py
QueryJob.wait
def wait(self, timeout=None): """ Wait for the job to complete, or a timeout to happen. This is more efficient than the version in the base Job class, in that we can use a call that blocks for the poll duration rather than a sleep. That means we shouldn't block unnecessarily long and can also pol...
python
def wait(self, timeout=None): """ Wait for the job to complete, or a timeout to happen. This is more efficient than the version in the base Job class, in that we can use a call that blocks for the poll duration rather than a sleep. That means we shouldn't block unnecessarily long and can also pol...
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "poll", "=", "30", "while", "not", "self", ".", "_is_complete", ":", "try", ":", "query_result", "=", "self", ".", "_api", ".", "jobs_query_results", "(", "self", ".", "_job_id", ",", ...
Wait for the job to complete, or a timeout to happen. This is more efficient than the version in the base Job class, in that we can use a call that blocks for the poll duration rather than a sleep. That means we shouldn't block unnecessarily long and can also poll less. Args: timeout: how ...
[ "Wait", "for", "the", "job", "to", "complete", "or", "a", "timeout", "to", "happen", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query_job.py#L63-L99
googledatalab/pydatalab
datalab/bigquery/_query_job.py
QueryJob.results
def results(self): """ Get the table used for the results of the query. If the query is incomplete, this blocks. Raises: Exception if we timed out waiting for results or the query failed. """ self.wait() if self.failed: raise Exception('Query failed: %s' % str(self.errors)) return s...
python
def results(self): """ Get the table used for the results of the query. If the query is incomplete, this blocks. Raises: Exception if we timed out waiting for results or the query failed. """ self.wait() if self.failed: raise Exception('Query failed: %s' % str(self.errors)) return s...
[ "def", "results", "(", "self", ")", ":", "self", ".", "wait", "(", ")", "if", "self", ".", "failed", ":", "raise", "Exception", "(", "'Query failed: %s'", "%", "str", "(", "self", ".", "errors", ")", ")", "return", "self", ".", "_table" ]
Get the table used for the results of the query. If the query is incomplete, this blocks. Raises: Exception if we timed out waiting for results or the query failed.
[ "Get", "the", "table", "used", "for", "the", "results", "of", "the", "query", ".", "If", "the", "query", "is", "incomplete", "this", "blocks", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query_job.py#L102-L111
googledatalab/pydatalab
google/datalab/stackdriver/monitoring/_metric.py
MetricDescriptors.list
def list(self, pattern='*'): """Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of Metri...
python
def list(self, pattern='*'): """Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of Metri...
[ "def", "list", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "if", "self", ".", "_descriptors", "is", "None", ":", "self", ".", "_descriptors", "=", "self", ".", "_client", ".", "list_metric_descriptors", "(", "filter_string", "=", "self", ".", "_fi...
Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of MetricDescriptor objects that match the f...
[ "Returns", "a", "list", "of", "metric", "descriptors", "that", "match", "the", "filters", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_metric.py#L45-L60
googledatalab/pydatalab
google/datalab/stackdriver/monitoring/_metric.py
MetricDescriptors.as_dataframe
def as_dataframe(self, pattern='*', max_rows=None): """Creates a pandas dataframe from the descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*/cpu/load_??m"``. ...
python
def as_dataframe(self, pattern='*', max_rows=None): """Creates a pandas dataframe from the descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*/cpu/load_??m"``. ...
[ "def", "as_dataframe", "(", "self", ",", "pattern", "=", "'*'", ",", "max_rows", "=", "None", ")", ":", "data", "=", "[", "]", "for", "i", ",", "metric", "in", "enumerate", "(", "self", ".", "list", "(", "pattern", ")", ")", ":", "if", "max_rows", ...
Creates a pandas dataframe from the descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*/cpu/load_??m"``. max_rows: The maximum number of descriptors to return...
[ "Creates", "a", "pandas", "dataframe", "from", "the", "descriptors", "that", "match", "the", "filters", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_metric.py#L62-L84
googledatalab/pydatalab
datalab/data/_utils.py
get_default_query_from_module
def get_default_query_from_module(module): """ Given a %%sql module return the default (last) query for the module. Args: module: the %%sql module. Returns: The default query associated with this module. """ if isinstance(module, types.ModuleType): return module.__dict__.get(_SQL_MODULE_LAST, No...
python
def get_default_query_from_module(module): """ Given a %%sql module return the default (last) query for the module. Args: module: the %%sql module. Returns: The default query associated with this module. """ if isinstance(module, types.ModuleType): return module.__dict__.get(_SQL_MODULE_LAST, No...
[ "def", "get_default_query_from_module", "(", "module", ")", ":", "if", "isinstance", "(", "module", ",", "types", ".", "ModuleType", ")", ":", "return", "module", ".", "__dict__", ".", "get", "(", "_SQL_MODULE_LAST", ",", "None", ")", "return", "None" ]
Given a %%sql module return the default (last) query for the module. Args: module: the %%sql module. Returns: The default query associated with this module.
[ "Given", "a", "%%sql", "module", "return", "the", "default", "(", "last", ")", "query", "for", "the", "module", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_utils.py#L27-L38
googledatalab/pydatalab
datalab/data/_utils.py
_next_token
def _next_token(sql): """ This is a basic tokenizer for our limited purposes. It splits a SQL statement up into a series of segments, where a segment is one of: - identifiers - left or right parentheses - multi-line comments - single line comments - white-space sequences - string literals - consecutiv...
python
def _next_token(sql): """ This is a basic tokenizer for our limited purposes. It splits a SQL statement up into a series of segments, where a segment is one of: - identifiers - left or right parentheses - multi-line comments - single line comments - white-space sequences - string literals - consecutiv...
[ "def", "_next_token", "(", "sql", ")", ":", "i", "=", "0", "# We use def statements here to make the logic more clear. The start_* functions return", "# true if i is the index of the start of that construct, while the end_* functions", "# return true if i point to the first character beyond th...
This is a basic tokenizer for our limited purposes. It splits a SQL statement up into a series of segments, where a segment is one of: - identifiers - left or right parentheses - multi-line comments - single line comments - white-space sequences - string literals - consecutive strings of characters that...
[ "This", "is", "a", "basic", "tokenizer", "for", "our", "limited", "purposes", ".", "It", "splits", "a", "SQL", "statement", "up", "into", "a", "series", "of", "segments", "where", "a", "segment", "is", "one", "of", ":", "-", "identifiers", "-", "left", ...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_utils.py#L41-L137
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_dataframe
def _from_dataframe(dataframe, default_type='STRING'): """ Infer a BigQuery table schema from a Pandas dataframe. Note that if you don't explicitly set the types of the columns in the dataframe, they may be of a type that forces coercion to STRING, so even though the fields in the dataframe themse...
python
def _from_dataframe(dataframe, default_type='STRING'): """ Infer a BigQuery table schema from a Pandas dataframe. Note that if you don't explicitly set the types of the columns in the dataframe, they may be of a type that forces coercion to STRING, so even though the fields in the dataframe themse...
[ "def", "_from_dataframe", "(", "dataframe", ",", "default_type", "=", "'STRING'", ")", ":", "type_mapping", "=", "{", "'i'", ":", "'INTEGER'", ",", "'b'", ":", "'BOOLEAN'", ",", "'f'", ":", "'FLOAT'", ",", "'O'", ":", "'STRING'", ",", "'S'", ":", "'STRIN...
Infer a BigQuery table schema from a Pandas dataframe. Note that if you don't explicitly set the types of the columns in the dataframe, they may be of a type that forces coercion to STRING, so even though the fields in the dataframe themselves may be numeric, the type in the derived schema may not be....
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "Pandas", "dataframe", ".", "Note", "that", "if", "you", "don", "t", "explicitly", "set", "the", "types", "of", "the", "columns", "in", "the", "dataframe", "they", "may", "be", "of", "a", "type", ...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L92-L124
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_dict_record
def _from_dict_record(data): """ Infer a BigQuery table schema from a dictionary. If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types. Ideally this will be an OrderedDict but it is not required. Args: data: The dict to infer a schema from. Re...
python
def _from_dict_record(data): """ Infer a BigQuery table schema from a dictionary. If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types. Ideally this will be an OrderedDict but it is not required. Args: data: The dict to infer a schema from. Re...
[ "def", "_from_dict_record", "(", "data", ")", ":", "return", "[", "Schema", ".", "_get_field_entry", "(", "name", ",", "value", ")", "for", "name", ",", "value", "in", "list", "(", "data", ".", "items", "(", ")", ")", "]" ]
Infer a BigQuery table schema from a dictionary. If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types. Ideally this will be an OrderedDict but it is not required. Args: data: The dict to infer a schema from. Returns: A list of dictionaries conta...
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "dictionary", ".", "If", "the", "dictionary", "has", "entries", "that", "are", "in", "turn", "OrderedDicts", "these", "will", "be", "turned", "into", "RECORD", "types", ".", "Ideally", "this", "will",...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L164-L176
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_list_record
def _from_list_record(data): """ Infer a BigQuery table schema from a list of values. Args: data: The list of values. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ return [Schema._get_...
python
def _from_list_record(data): """ Infer a BigQuery table schema from a list of values. Args: data: The list of values. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ return [Schema._get_...
[ "def", "_from_list_record", "(", "data", ")", ":", "return", "[", "Schema", ".", "_get_field_entry", "(", "'Column%d'", "%", "(", "i", "+", "1", ")", ",", "value", ")", "for", "i", ",", "value", "in", "enumerate", "(", "data", ")", "]" ]
Infer a BigQuery table schema from a list of values. Args: data: The list of values. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema.
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "list", "of", "values", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L179-L189
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_record
def _from_record(data): """ Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements is used. For a list, the field names are simply 'Column1', 'Column2', etc. Args: data: The list of fields or dictionary. Returns: A list of dictionaries containing fi...
python
def _from_record(data): """ Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements is used. For a list, the field names are simply 'Column1', 'Column2', etc. Args: data: The list of fields or dictionary. Returns: A list of dictionaries containing fi...
[ "def", "_from_record", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "return", "Schema", ".", "_from_dict_record", "(", "data", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "return", "Schema", ".", "_f...
Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements is used. For a list, the field names are simply 'Column1', 'Column2', etc. Args: data: The list of fields or dictionary. Returns: A list of dictionaries containing field 'name' and 'type' entries, suita...
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "list", "of", "fields", "or", "a", "dictionary", ".", "The", "typeof", "the", "elements", "is", "used", ".", "For", "a", "list", "the", "field", "names", "are", "simply", "Column1", "Column2", "et...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L192-L208
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema.from_data
def from_data(source): """Infers a table/view schema from its JSON representation, a list of records, or a Pandas dataframe. Args: source: the Pandas Dataframe, a dictionary representing a record, a list of heterogeneous data (record) or homogeneous data (list of records) from which to i...
python
def from_data(source): """Infers a table/view schema from its JSON representation, a list of records, or a Pandas dataframe. Args: source: the Pandas Dataframe, a dictionary representing a record, a list of heterogeneous data (record) or homogeneous data (list of records) from which to i...
[ "def", "from_data", "(", "source", ")", ":", "if", "isinstance", "(", "source", ",", "pandas", ".", "DataFrame", ")", ":", "bq_schema", "=", "Schema", ".", "_from_dataframe", "(", "source", ")", "elif", "isinstance", "(", "source", ",", "list", ")", ":",...
Infers a table/view schema from its JSON representation, a list of records, or a Pandas dataframe. Args: source: the Pandas Dataframe, a dictionary representing a record, a list of heterogeneous data (record) or homogeneous data (list of records) from which to infer the schema, or ...
[ "Infers", "a", "table", "/", "view", "schema", "from", "its", "JSON", "representation", "a", "list", "of", "records", "or", "a", "Pandas", "dataframe", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L230-L279
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema.find
def find(self, name): """ Get the index of a field in the flattened list given its (fully-qualified) name. Args: name: the fully-qualified name of the field. Returns: The index of the field, if found; else -1. """ for i in range(0, len(self)): if self[i].name == name: retu...
python
def find(self, name): """ Get the index of a field in the flattened list given its (fully-qualified) name. Args: name: the fully-qualified name of the field. Returns: The index of the field, if found; else -1. """ for i in range(0, len(self)): if self[i].name == name: retu...
[ "def", "find", "(", "self", ",", "name", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ")", ")", ":", "if", "self", "[", "i", "]", ".", "name", "==", "name", ":", "return", "i", "return", "-", "1" ]
Get the index of a field in the flattened list given its (fully-qualified) name. Args: name: the fully-qualified name of the field. Returns: The index of the field, if found; else -1.
[ "Get", "the", "index", "of", "a", "field", "in", "the", "flattened", "list", "given", "its", "(", "fully", "-", "qualified", ")", "name", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L308-L319
googledatalab/pydatalab
datalab/utils/commands/_commands.py
CommandParser.create_args
def create_args(line, namespace): """ Expand any meta-variable references in the argument list. """ args = [] # Using shlex.split handles quotes args and escape characters. for arg in shlex.split(line): if not arg: continue if arg[0] == '$': var_name = arg[1:] if var...
python
def create_args(line, namespace): """ Expand any meta-variable references in the argument list. """ args = [] # Using shlex.split handles quotes args and escape characters. for arg in shlex.split(line): if not arg: continue if arg[0] == '$': var_name = arg[1:] if var...
[ "def", "create_args", "(", "line", ",", "namespace", ")", ":", "args", "=", "[", "]", "# Using shlex.split handles quotes args and escape characters.", "for", "arg", "in", "shlex", ".", "split", "(", "line", ")", ":", "if", "not", "arg", ":", "continue", "if",...
Expand any meta-variable references in the argument list.
[ "Expand", "any", "meta", "-", "variable", "references", "in", "the", "argument", "list", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_commands.py#L49-L64
googledatalab/pydatalab
datalab/utils/commands/_commands.py
CommandParser.parse
def parse(self, line, namespace=None): """Parses a line into a dictionary of arguments, expanding meta-variables from a namespace. """ try: if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns args = CommandParser.create_args(line, namespace) return self.pa...
python
def parse(self, line, namespace=None): """Parses a line into a dictionary of arguments, expanding meta-variables from a namespace. """ try: if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns args = CommandParser.create_args(line, namespace) return self.pa...
[ "def", "parse", "(", "self", ",", "line", ",", "namespace", "=", "None", ")", ":", "try", ":", "if", "namespace", "is", "None", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "namespace", "=", "ipy", ".", "user_ns", "args", "=", "CommandPa...
Parses a line into a dictionary of arguments, expanding meta-variables from a namespace.
[ "Parses", "a", "line", "into", "a", "dictionary", "of", "arguments", "expanding", "meta", "-", "variables", "from", "a", "namespace", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_commands.py#L66-L76
googledatalab/pydatalab
datalab/utils/commands/_commands.py
CommandParser.subcommand
def subcommand(self, name, help): """Creates a parser for a sub-command. """ if self._subcommands is None: self._subcommands = self.add_subparsers(help='commands') return self._subcommands.add_parser(name, description=help, help=help)
python
def subcommand(self, name, help): """Creates a parser for a sub-command. """ if self._subcommands is None: self._subcommands = self.add_subparsers(help='commands') return self._subcommands.add_parser(name, description=help, help=help)
[ "def", "subcommand", "(", "self", ",", "name", ",", "help", ")", ":", "if", "self", ".", "_subcommands", "is", "None", ":", "self", ".", "_subcommands", "=", "self", ".", "add_subparsers", "(", "help", "=", "'commands'", ")", "return", "self", ".", "_s...
Creates a parser for a sub-command.
[ "Creates", "a", "parser", "for", "a", "sub", "-", "command", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_commands.py#L78-L82
googledatalab/pydatalab
datalab/utils/commands/_utils.py
render_dictionary
def render_dictionary(data, headers=None): """ Return a dictionary list formatted as a HTML table. Args: data: the dictionary list headers: the keys in the dictionary to use as table columns, in order. """ return IPython.core.display.HTML(_html.HtmlBuilder.render_table(data, headers))
python
def render_dictionary(data, headers=None): """ Return a dictionary list formatted as a HTML table. Args: data: the dictionary list headers: the keys in the dictionary to use as table columns, in order. """ return IPython.core.display.HTML(_html.HtmlBuilder.render_table(data, headers))
[ "def", "render_dictionary", "(", "data", ",", "headers", "=", "None", ")", ":", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "_html", ".", "HtmlBuilder", ".", "render_table", "(", "data", ",", "headers", ")", ")" ]
Return a dictionary list formatted as a HTML table. Args: data: the dictionary list headers: the keys in the dictionary to use as table columns, in order.
[ "Return", "a", "dictionary", "list", "formatted", "as", "a", "HTML", "table", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L63-L70
googledatalab/pydatalab
datalab/utils/commands/_utils.py
render_text
def render_text(text, preformatted=False): """ Return text formatted as a HTML Args: text: the text to render preformatted: whether the text should be rendered as preformatted """ return IPython.core.display.HTML(_html.HtmlBuilder.render_text(text, preformatted))
python
def render_text(text, preformatted=False): """ Return text formatted as a HTML Args: text: the text to render preformatted: whether the text should be rendered as preformatted """ return IPython.core.display.HTML(_html.HtmlBuilder.render_text(text, preformatted))
[ "def", "render_text", "(", "text", ",", "preformatted", "=", "False", ")", ":", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "_html", ".", "HtmlBuilder", ".", "render_text", "(", "text", ",", "preformatted", ")", ")" ]
Return text formatted as a HTML Args: text: the text to render preformatted: whether the text should be rendered as preformatted
[ "Return", "text", "formatted", "as", "a", "HTML" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L73-L80
googledatalab/pydatalab
datalab/utils/commands/_utils.py
get_field_list
def get_field_list(fields, schema): """ Convert a field list spec into a real list of field names. For tables, we return only the top-level non-RECORD fields as Google charts can't handle nested data. """ # If the fields weren't supplied get them from the schema. if isinstance(fields, list): re...
python
def get_field_list(fields, schema): """ Convert a field list spec into a real list of field names. For tables, we return only the top-level non-RECORD fields as Google charts can't handle nested data. """ # If the fields weren't supplied get them from the schema. if isinstance(fields, list): re...
[ "def", "get_field_list", "(", "fields", ",", "schema", ")", ":", "# If the fields weren't supplied get them from the schema.", "if", "isinstance", "(", "fields", ",", "list", ")", ":", "return", "fields", "if", "isinstance", "(", "fields", ",", "basestring", ")", ...
Convert a field list spec into a real list of field names. For tables, we return only the top-level non-RECORD fields as Google charts can't handle nested data.
[ "Convert", "a", "field", "list", "spec", "into", "a", "real", "list", "of", "field", "names", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L83-L96
googledatalab/pydatalab
datalab/utils/commands/_utils.py
_get_cols
def _get_cols(fields, schema): """ Get column metadata for Google Charts based on field list and schema. """ typemap = { 'STRING': 'string', 'INT64': 'number', 'INTEGER': 'number', 'FLOAT': 'number', 'FLOAT64': 'number', 'BOOL': 'boolean', 'BOOLEAN': 'boolean', 'DATE': 'date', 'T...
python
def _get_cols(fields, schema): """ Get column metadata for Google Charts based on field list and schema. """ typemap = { 'STRING': 'string', 'INT64': 'number', 'INTEGER': 'number', 'FLOAT': 'number', 'FLOAT64': 'number', 'BOOL': 'boolean', 'BOOLEAN': 'boolean', 'DATE': 'date', 'T...
[ "def", "_get_cols", "(", "fields", ",", "schema", ")", ":", "typemap", "=", "{", "'STRING'", ":", "'string'", ",", "'INT64'", ":", "'number'", ",", "'INTEGER'", ":", "'number'", ",", "'FLOAT'", ":", "'number'", ",", "'FLOAT64'", ":", "'number'", ",", "'B...
Get column metadata for Google Charts based on field list and schema.
[ "Get", "column", "metadata", "for", "Google", "Charts", "based", "on", "field", "list", "and", "schema", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L99-L125
googledatalab/pydatalab
datalab/utils/commands/_utils.py
_get_data_from_empty_list
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles empty lists. """ fields = get_field_list(fields, schema) return {'cols': _get_cols(fields, schema), 'rows': []}, 0
python
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles empty lists. """ fields = get_field_list(fields, schema) return {'cols': _get_cols(fields, schema), 'rows': []}, 0
[ "def", "_get_data_from_empty_list", "(", "source", ",", "fields", "=", "'*'", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "fields", "=", "get_field_list", "(", "fields", ",", "schema", ")", "return", "...
Helper function for _get_data that handles empty lists.
[ "Helper", "function", "for", "_get_data", "that", "handles", "empty", "lists", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L128-L131
googledatalab/pydatalab
datalab/utils/commands/_utils.py
_get_data_from_table
def _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles BQ Tables. """ if not source.exists(): return _get_data_from_empty_list(source, fields, first_row, count) if schema is None: schema = source.schema fields = get_field_list(fie...
python
def _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles BQ Tables. """ if not source.exists(): return _get_data_from_empty_list(source, fields, first_row, count) if schema is None: schema = source.schema fields = get_field_list(fie...
[ "def", "_get_data_from_table", "(", "source", ",", "fields", "=", "'*'", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "if", "not", "source", ".", "exists", "(", ")", ":", "return", "_get_data_from_empty...
Helper function for _get_data that handles BQ Tables.
[ "Helper", "function", "for", "_get_data", "that", "handles", "BQ", "Tables", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L176-L185
googledatalab/pydatalab
datalab/utils/commands/_utils.py
get_data
def get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): """ A utility function to get a subset of data from a Table, Query, Pandas dataframe or List. Args: source: the source of the data. Can be a Table, Pandas DataFrame, List of dictionaries or lists, or a string, in which case...
python
def get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None): """ A utility function to get a subset of data from a Table, Query, Pandas dataframe or List. Args: source: the source of the data. Can be a Table, Pandas DataFrame, List of dictionaries or lists, or a string, in which case...
[ "def", "get_data", "(", "source", ",", "fields", "=", "'*'", ",", "env", "=", "None", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "if", "env",...
A utility function to get a subset of data from a Table, Query, Pandas dataframe or List. Args: source: the source of the data. Can be a Table, Pandas DataFrame, List of dictionaries or lists, or a string, in which case it is expected to be the name of a table in BQ. fields: a list of fields that we ...
[ "A", "utility", "function", "to", "get", "a", "subset", "of", "data", "from", "a", "Table", "Query", "Pandas", "dataframe", "or", "List", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L188-L244
googledatalab/pydatalab
datalab/utils/commands/_utils.py
handle_magic_line
def handle_magic_line(line, cell, parser, namespace=None): """ Helper function for handling magic command lines given a parser with handlers set. """ args = parser.parse(line, namespace) if args: try: return args.func(vars(args), cell) except Exception as e: sys.stderr.write(str(e)) sys....
python
def handle_magic_line(line, cell, parser, namespace=None): """ Helper function for handling magic command lines given a parser with handlers set. """ args = parser.parse(line, namespace) if args: try: return args.func(vars(args), cell) except Exception as e: sys.stderr.write(str(e)) sys....
[ "def", "handle_magic_line", "(", "line", ",", "cell", ",", "parser", ",", "namespace", "=", "None", ")", ":", "args", "=", "parser", ".", "parse", "(", "line", ",", "namespace", ")", "if", "args", ":", "try", ":", "return", "args", ".", "func", "(", ...
Helper function for handling magic command lines given a parser with handlers set.
[ "Helper", "function", "for", "handling", "magic", "command", "lines", "given", "a", "parser", "with", "handlers", "set", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L247-L257
googledatalab/pydatalab
datalab/utils/commands/_utils.py
expand_var
def expand_var(v, env): """ If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env. """ if len(v...
python
def expand_var(v, env): """ If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env. """ if len(v...
[ "def", "expand_var", "(", "v", ",", "env", ")", ":", "if", "len", "(", "v", ")", "==", "0", ":", "return", "v", "# Using len() and v[0] instead of startswith makes this Unicode-safe.", "if", "v", "[", "0", "]", "==", "'$'", ":", "v", "=", "v", "[", "1", ...
If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env.
[ "If", "v", "is", "a", "variable", "reference", "(", "for", "example", ":", "$myvar", ")", "replace", "it", "using", "the", "supplied", "env", "dictionary", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L260-L281
googledatalab/pydatalab
datalab/utils/commands/_utils.py
replace_vars
def replace_vars(config, env): """ Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env. """ if isinstance(config,...
python
def replace_vars(config, env): """ Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env. """ if isinstance(config,...
[ "def", "replace_vars", "(", "config", ",", "env", ")", ":", "if", "isinstance", "(", "config", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "list", "(", "config", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ...
Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env.
[ "Replace", "variable", "references", "in", "config", "using", "the", "supplied", "env", "dictionary", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L284-L310
googledatalab/pydatalab
datalab/utils/commands/_utils.py
parse_config
def parse_config(config, env, as_dict=True): """ Parse a config from a magic cell body. This could be JSON or YAML. We turn it into a Python dictionary then recursively replace any variable references using the supplied env dictionary. """ if config is None: return None stripped = config.strip(...
python
def parse_config(config, env, as_dict=True): """ Parse a config from a magic cell body. This could be JSON or YAML. We turn it into a Python dictionary then recursively replace any variable references using the supplied env dictionary. """ if config is None: return None stripped = config.strip(...
[ "def", "parse_config", "(", "config", ",", "env", ",", "as_dict", "=", "True", ")", ":", "if", "config", "is", "None", ":", "return", "None", "stripped", "=", "config", ".", "strip", "(", ")", "if", "len", "(", "stripped", ")", "==", "0", ":", "con...
Parse a config from a magic cell body. This could be JSON or YAML. We turn it into a Python dictionary then recursively replace any variable references using the supplied env dictionary.
[ "Parse", "a", "config", "from", "a", "magic", "cell", "body", ".", "This", "could", "be", "JSON", "or", "YAML", ".", "We", "turn", "it", "into", "a", "Python", "dictionary", "then", "recursively", "replace", "any", "variable", "references", "using", "the",...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L313-L333
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config
def validate_config(config, required_keys, optional_keys=None): """ Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys...
python
def validate_config(config, required_keys, optional_keys=None): """ Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys...
[ "def", "validate_config", "(", "config", ",", "required_keys", ",", "optional_keys", "=", "None", ")", ":", "if", "optional_keys", "is", "None", ":", "optional_keys", "=", "[", "]", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", ...
Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys: the names of the keys that the config can have. Raises: Excep...
[ "Validate", "a", "config", "dictionary", "to", "make", "sure", "it", "includes", "all", "required", "keys", "and", "does", "not", "include", "any", "unexpected", "keys", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L336-L357
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config_must_have
def validate_config_must_have(config, required_keys): """ Validate a config dictionary to make sure it has all of the specified keys Args: config: the config to validate. required_keys: the list of possible keys that config must include. Raises: Exception if the config does not have any of them. "...
python
def validate_config_must_have(config, required_keys): """ Validate a config dictionary to make sure it has all of the specified keys Args: config: the config to validate. required_keys: the list of possible keys that config must include. Raises: Exception if the config does not have any of them. "...
[ "def", "validate_config_must_have", "(", "config", ",", "required_keys", ")", ":", "missing_keys", "=", "set", "(", "required_keys", ")", "-", "set", "(", "config", ")", "if", "len", "(", "missing_keys", ")", ">", "0", ":", "raise", "Exception", "(", "'Inv...
Validate a config dictionary to make sure it has all of the specified keys Args: config: the config to validate. required_keys: the list of possible keys that config must include. Raises: Exception if the config does not have any of them.
[ "Validate", "a", "config", "dictionary", "to", "make", "sure", "it", "has", "all", "of", "the", "specified", "keys" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L360-L372
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config_has_one_of
def validate_config_has_one_of(config, one_of_keys): """ Validate a config dictionary to make sure it has one and only one key in one_of_keys. Args: config: the config to validate. one_of_keys: the list of possible keys that config can have one and only one. Raises: Exception if the config doe...
python
def validate_config_has_one_of(config, one_of_keys): """ Validate a config dictionary to make sure it has one and only one key in one_of_keys. Args: config: the config to validate. one_of_keys: the list of possible keys that config can have one and only one. Raises: Exception if the config doe...
[ "def", "validate_config_has_one_of", "(", "config", ",", "one_of_keys", ")", ":", "intersection", "=", "set", "(", "config", ")", ".", "intersection", "(", "one_of_keys", ")", "if", "len", "(", "intersection", ")", ">", "1", ":", "raise", "Exception", "(", ...
Validate a config dictionary to make sure it has one and only one key in one_of_keys. Args: config: the config to validate. one_of_keys: the list of possible keys that config can have one and only one. Raises: Exception if the config does not have any of them, or multiple of them.
[ "Validate", "a", "config", "dictionary", "to", "make", "sure", "it", "has", "one", "and", "only", "one", "key", "in", "one_of_keys", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L375-L390
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config_value
def validate_config_value(value, possible_values): """ Validate a config value to make sure it is one of the possible values. Args: value: the config value to validate. possible_values: the possible values the value can be Raises: Exception if the value is not one of possible values. """ if valu...
python
def validate_config_value(value, possible_values): """ Validate a config value to make sure it is one of the possible values. Args: value: the config value to validate. possible_values: the possible values the value can be Raises: Exception if the value is not one of possible values. """ if valu...
[ "def", "validate_config_value", "(", "value", ",", "possible_values", ")", ":", "if", "value", "not", "in", "possible_values", ":", "raise", "Exception", "(", "'Invalid config value \"%s\". Possible values are '", "'%s'", "%", "(", "value", ",", "', '", ".", "join",...
Validate a config value to make sure it is one of the possible values. Args: value: the config value to validate. possible_values: the possible values the value can be Raises: Exception if the value is not one of possible values.
[ "Validate", "a", "config", "value", "to", "make", "sure", "it", "is", "one", "of", "the", "possible", "values", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L393-L405
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_gcs_path
def validate_gcs_path(path, require_object): """ Check whether a given path is a valid GCS path. Args: path: the config to check. require_object: if True, the path has to be an object path but not bucket path. Raises: Exception if the path is invalid """ bucket, key = datalab.storage._bucket.par...
python
def validate_gcs_path(path, require_object): """ Check whether a given path is a valid GCS path. Args: path: the config to check. require_object: if True, the path has to be an object path but not bucket path. Raises: Exception if the path is invalid """ bucket, key = datalab.storage._bucket.par...
[ "def", "validate_gcs_path", "(", "path", ",", "require_object", ")", ":", "bucket", ",", "key", "=", "datalab", ".", "storage", ".", "_bucket", ".", "parse_name", "(", "path", ")", "if", "bucket", "is", "None", ":", "raise", "Exception", "(", "'Invalid GCS...
Check whether a given path is a valid GCS path. Args: path: the config to check. require_object: if True, the path has to be an object path but not bucket path. Raises: Exception if the path is invalid
[ "Check", "whether", "a", "given", "path", "is", "a", "valid", "GCS", "path", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L421-L435
googledatalab/pydatalab
datalab/utils/commands/_utils.py
parse_control_options
def parse_control_options(controls, variable_defaults=None): """ Parse a set of control options. Args: controls: The dictionary of control options. variable_defaults: If the controls are for a Query with variables, then this is the default variable values defined in the Query module. The options in...
python
def parse_control_options(controls, variable_defaults=None): """ Parse a set of control options. Args: controls: The dictionary of control options. variable_defaults: If the controls are for a Query with variables, then this is the default variable values defined in the Query module. The options in...
[ "def", "parse_control_options", "(", "controls", ",", "variable_defaults", "=", "None", ")", ":", "controls_html", "=", "''", "control_defaults", "=", "{", "}", "control_ids", "=", "[", "]", "div_id", "=", "_html", ".", "Html", ".", "next_id", "(", ")", "i...
Parse a set of control options. Args: controls: The dictionary of control options. variable_defaults: If the controls are for a Query with variables, then this is the default variable values defined in the Query module. The options in the controls parameter can override these but if a variabl...
[ "Parse", "a", "set", "of", "control", "options", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L438-L550
googledatalab/pydatalab
datalab/utils/commands/_utils.py
profile_df
def profile_df(df): """ Generate a profile of data in a dataframe. Args: df: the Pandas dataframe. """ # The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect. # TODO(gram): strip it out rather than this kludge. return IPython.core.display.HTML( pandas_profiling.Pro...
python
def profile_df(df): """ Generate a profile of data in a dataframe. Args: df: the Pandas dataframe. """ # The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect. # TODO(gram): strip it out rather than this kludge. return IPython.core.display.HTML( pandas_profiling.Pro...
[ "def", "profile_df", "(", "df", ")", ":", "# The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect.", "# TODO(gram): strip it out rather than this kludge.", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "pandas_profiling", ".",...
Generate a profile of data in a dataframe. Args: df: the Pandas dataframe.
[ "Generate", "a", "profile", "of", "data", "in", "a", "dataframe", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L675-L684
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
_assert_gcs_files
def _assert_gcs_files(files): """Check files starts wtih gs://. Args: files: string to file path, or list of file paths. """ if sys.version_info.major > 2: string_type = (str, bytes) # for python 3 compatibility else: string_type = basestring # noqa if isinstance(files, string_type): fi...
python
def _assert_gcs_files(files): """Check files starts wtih gs://. Args: files: string to file path, or list of file paths. """ if sys.version_info.major > 2: string_type = (str, bytes) # for python 3 compatibility else: string_type = basestring # noqa if isinstance(files, string_type): fi...
[ "def", "_assert_gcs_files", "(", "files", ")", ":", "if", "sys", ".", "version_info", ".", "major", ">", "2", ":", "string_type", "=", "(", "str", ",", "bytes", ")", "# for python 3 compatibility", "else", ":", "string_type", "=", "basestring", "# noqa", "if...
Check files starts wtih gs://. Args: files: string to file path, or list of file paths.
[ "Check", "files", "starts", "wtih", "gs", ":", "//", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L67-L84
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
_package_to_staging
def _package_to_staging(staging_package_url): """Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS path. """ import google.datalab.ml as ml # Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file ...
python
def _package_to_staging(staging_package_url): """Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS path. """ import google.datalab.ml as ml # Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file ...
[ "def", "_package_to_staging", "(", "staging_package_url", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "# Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file", "package_root", "=", "os", ".", "path", ".", "abs...
Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS path.
[ "Repackage", "this", "package", "from", "local", "installed", "location", "and", "copy", "it", "to", "GCS", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L87-L105
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
_wait_and_kill
def _wait_and_kill(pid_to_wait, pids_to_kill): """ Helper function. Wait for a process to finish if it exists, and then try to kill a list of processes. Used by local_train Args: pid_to_wait: the process to wait for. pids_to_kill: a list of processes to kill after the process of pid_to_...
python
def _wait_and_kill(pid_to_wait, pids_to_kill): """ Helper function. Wait for a process to finish if it exists, and then try to kill a list of processes. Used by local_train Args: pid_to_wait: the process to wait for. pids_to_kill: a list of processes to kill after the process of pid_to_...
[ "def", "_wait_and_kill", "(", "pid_to_wait", ",", "pids_to_kill", ")", ":", "# cloud workers don't have psutil", "import", "psutil", "if", "psutil", ".", "pid_exists", "(", "pid_to_wait", ")", ":", "psutil", ".", "Process", "(", "pid", "=", "pid_to_wait", ")", "...
Helper function. Wait for a process to finish if it exists, and then try to kill a list of processes. Used by local_train Args: pid_to_wait: the process to wait for. pids_to_kill: a list of processes to kill after the process of pid_to_wait finishes.
[ "Helper", "function", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L108-L129
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
analyze
def analyze(output_dir, dataset, cloud=False, project_id=None): """Blocking version of analyze_async. See documentation of analyze_async.""" job = analyze_async( output_dir=output_dir, dataset=dataset, cloud=cloud, project_id=project_id) job.wait() print('Analyze: ' + str(job.state))
python
def analyze(output_dir, dataset, cloud=False, project_id=None): """Blocking version of analyze_async. See documentation of analyze_async.""" job = analyze_async( output_dir=output_dir, dataset=dataset, cloud=cloud, project_id=project_id) job.wait() print('Analyze: ' + str(job.state))
[ "def", "analyze", "(", "output_dir", ",", "dataset", ",", "cloud", "=", "False", ",", "project_id", "=", "None", ")", ":", "job", "=", "analyze_async", "(", "output_dir", "=", "output_dir", ",", "dataset", "=", "dataset", ",", "cloud", "=", "cloud", ",",...
Blocking version of analyze_async. See documentation of analyze_async.
[ "Blocking", "version", "of", "analyze_async", ".", "See", "documentation", "of", "analyze_async", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L136-L144
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
analyze_async
def analyze_async(output_dir, dataset, cloud=False, project_id=None): """Analyze data locally or in the cloud with BigQuery. Produce analysis used by training. This can take a while, even for small datasets. For small datasets, it may be faster to use local_analysis. Args: output_dir: The output directory...
python
def analyze_async(output_dir, dataset, cloud=False, project_id=None): """Analyze data locally or in the cloud with BigQuery. Produce analysis used by training. This can take a while, even for small datasets. For small datasets, it may be faster to use local_analysis. Args: output_dir: The output directory...
[ "def", "analyze_async", "(", "output_dir", ",", "dataset", ",", "cloud", "=", "False", ",", "project_id", "=", "None", ")", ":", "import", "google", ".", "datalab", ".", "utils", "as", "du", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warn...
Analyze data locally or in the cloud with BigQuery. Produce analysis used by training. This can take a while, even for small datasets. For small datasets, it may be faster to use local_analysis. Args: output_dir: The output directory to use. dataset: only CsvDataSet is supported currently. cloud: If...
[ "Analyze", "data", "locally", "or", "in", "the", "cloud", "with", "BigQuery", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L147-L168
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
train_async
def train_async(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps=5000, num_epochs=None, train_batch_size=100, eval_batch_size=16, ...
python
def train_async(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps=5000, num_epochs=None, train_batch_size=100, eval_batch_size=16, ...
[ "def", "train_async", "(", "train_dataset", ",", "eval_dataset", ",", "analysis_dir", ",", "output_dir", ",", "features", ",", "model_type", ",", "max_steps", "=", "5000", ",", "num_epochs", "=", "None", ",", "train_batch_size", "=", "100", ",", "eval_batch_size...
Train model locally or in the cloud. Local Training: Args: train_dataset: CsvDataSet eval_dataset: CsvDataSet analysis_dir: The output directory from local_analysis output_dir: Output directory of training. features: file path or features object. Example: { "col_A": {"trans...
[ "Train", "model", "locally", "or", "in", "the", "cloud", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L216-L360
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
cloud_train
def cloud_train(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps, num_epochs, train_batch_size, eval_batch_size, min_eval_...
python
def cloud_train(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps, num_epochs, train_batch_size, eval_batch_size, min_eval_...
[ "def", "cloud_train", "(", "train_dataset", ",", "eval_dataset", ",", "analysis_dir", ",", "output_dir", ",", "features", ",", "model_type", ",", "max_steps", ",", "num_epochs", ",", "train_batch_size", ",", "eval_batch_size", ",", "min_eval_frequency", ",", "top_n"...
Train model using CloudML. See local_train() for a description of the args. Args: config: A CloudTrainingConfig object. job_name: Training job name. A default will be picked if None.
[ "Train", "model", "using", "CloudML", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L456-L543
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
predict
def predict(data, training_dir=None, model_name=None, model_version=None, cloud=False): """Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name ...
python
def predict(data, training_dir=None, model_name=None, model_version=None, cloud=False): """Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name ...
[ "def", "predict", "(", "data", ",", "training_dir", "=", "None", ",", "model_name", "=", "None", ",", "model_version", "=", "None", ",", "cloud", "=", "False", ")", ":", "if", "cloud", ":", "if", "not", "model_version", "or", "not", "model_name", ":", ...
Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name model_version: depoyed model version cloud: bool. If False, does local prediction and ...
[ "Runs", "prediction", "locally", "or", "on", "the", "cloud", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L550-L592
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
local_predict
def local_predict(training_dir, data): """Runs local prediction on the prediction graph. Runs local prediction and returns the result in a Pandas DataFrame. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Input data should fully match the schem...
python
def local_predict(training_dir, data): """Runs local prediction on the prediction graph. Runs local prediction and returns the result in a Pandas DataFrame. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Input data should fully match the schem...
[ "def", "local_predict", "(", "training_dir", ",", "data", ")", ":", "# from . import predict as predict_module", "from", ".", "prediction", "import", "predict", "as", "predict_module", "# Save the instances to a file, call local batch prediction, and return it", "tmp_dir", "=", ...
Runs local prediction on the prediction graph. Runs local prediction and returns the result in a Pandas DataFrame. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Input data should fully match the schema that was used at training, except the targ...
[ "Runs", "local", "prediction", "on", "the", "prediction", "graph", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L595-L668
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
cloud_predict
def cloud_predict(model_name, model_version, data): """Use Online prediction. Runs online prediction in the cloud and prints the results to the screen. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Args: model_name: deployed model name ...
python
def cloud_predict(model_name, model_version, data): """Use Online prediction. Runs online prediction in the cloud and prints the results to the screen. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Args: model_name: deployed model name ...
[ "def", "cloud_predict", "(", "model_name", ",", "model_version", ",", "data", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "# write the df to csv.", "string_buffe...
Use Online prediction. Runs online prediction in the cloud and prints the results to the screen. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Args: model_name: deployed model name model_version: depoyed model version data: List of...
[ "Use", "Online", "prediction", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L671-L715
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
batch_predict
def batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Blocking versoin of batch_predict. See documentation of batch_prediction_async. """ job = batch_predict_async( training_dir=t...
python
def batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Blocking versoin of batch_predict. See documentation of batch_prediction_async. """ job = batch_predict_async( training_dir=t...
[ "def", "batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", "=", "16", ",", "shard_files", "=", "True", ",", "output_format", "=", "'csv'", ",", "cloud", "=", "False", ")", ":", "job", "=", ...
Blocking versoin of batch_predict. See documentation of batch_prediction_async.
[ "Blocking", "versoin", "of", "batch_predict", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L722-L739
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
batch_predict_async
def batch_predict_async(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Local and cloud batch prediction. Args: training_dir: The output folder of training. prediction_input_file: csv file pattern to a fil...
python
def batch_predict_async(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Local and cloud batch prediction. Args: training_dir: The output folder of training. prediction_input_file: csv file pattern to a fil...
[ "def", "batch_predict_async", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", "=", "16", ",", "shard_files", "=", "True", ",", "output_format", "=", "'csv'", ",", "cloud", "=", "False", ")", ":", "import", ...
Local and cloud batch prediction. Args: training_dir: The output folder of training. prediction_input_file: csv file pattern to a file. File must be on GCS if running cloud prediction output_dir: output location to save the results. Must be a GSC path if running cloud prediction. mode...
[ "Local", "and", "cloud", "batch", "prediction", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L742-L777
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
local_batch_predict
def local_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format): """See batch_predict""" # from . import predict as predict_module from .prediction import predict as predict_module if mode == 'evaluation': model_dir = os.path.jo...
python
def local_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format): """See batch_predict""" # from . import predict as predict_module from .prediction import predict as predict_module if mode == 'evaluation': model_dir = os.path.jo...
[ "def", "local_batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", ",", "shard_files", ",", "output_format", ")", ":", "# from . import predict as predict_module", "from", ".", "prediction", "import", "pre...
See batch_predict
[ "See", "batch_predict" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L780-L807
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
cloud_batch_predict
def cloud_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format): """See batch_predict""" # from . import predict as predict_module from .prediction import predict as predict_module if mode == 'evaluation': model_dir = os.path.jo...
python
def cloud_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format): """See batch_predict""" # from . import predict as predict_module from .prediction import predict as predict_module if mode == 'evaluation': model_dir = os.path.jo...
[ "def", "cloud_batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", ",", "shard_files", ",", "output_format", ")", ":", "# from . import predict as predict_module", "from", ".", "prediction", "import", "pre...
See batch_predict
[ "See", "batch_predict" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L810-L842
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
parse_arguments
def parse_arguments(argv): """Parse command line arguments. Args: argv: includes the script's name. Returns: argparse object """ parser = argparse.ArgumentParser( description='Runs Prediction inside a beam or Dataflow job.') # cloud options parser.add_argument('--project-id', ...
python
def parse_arguments(argv): """Parse command line arguments. Args: argv: includes the script's name. Returns: argparse object """ parser = argparse.ArgumentParser( description='Runs Prediction inside a beam or Dataflow job.') # cloud options parser.add_argument('--project-id', ...
[ "def", "parse_arguments", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Runs Prediction inside a beam or Dataflow job.'", ")", "# cloud options", "parser", ".", "add_argument", "(", "'--project-id'", ",", "help", "...
Parse command line arguments. Args: argv: includes the script's name. Returns: argparse object
[ "Parse", "command", "line", "arguments", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L30-L109
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
make_prediction_pipeline
def make_prediction_pipeline(pipeline, args): """Builds the prediction pipeline. Reads the csv files, prepends a ',' if the target column is missing, run prediction, and then prints the formated results to a file. Args: pipeline: the pipeline args: command line args """ # DF bug: DF does not work...
python
def make_prediction_pipeline(pipeline, args): """Builds the prediction pipeline. Reads the csv files, prepends a ',' if the target column is missing, run prediction, and then prints the formated results to a file. Args: pipeline: the pipeline args: command line args """ # DF bug: DF does not work...
[ "def", "make_prediction_pipeline", "(", "pipeline", ",", "args", ")", ":", "# DF bug: DF does not work with unicode strings", "predicted_values", ",", "errors", "=", "(", "pipeline", "|", "'Read CSV Files'", ">>", "beam", ".", "io", ".", "ReadFromText", "(", "str", ...
Builds the prediction pipeline. Reads the csv files, prepends a ',' if the target column is missing, run prediction, and then prints the formated results to a file. Args: pipeline: the pipeline args: command line args
[ "Builds", "the", "prediction", "pipeline", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L349-L373
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
RunGraphDoFn.process
def process(self, element): """Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF graph. """ import collections import apache_beam as beam num_in_batch = 0 try: assert self._session is not None feed_dict = collectio...
python
def process(self, element): """Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF graph. """ import collections import apache_beam as beam num_in_batch = 0 try: assert self._session is not None feed_dict = collectio...
[ "def", "process", "(", "self", ",", "element", ")", ":", "import", "collections", "import", "apache_beam", "as", "beam", "num_in_batch", "=", "0", "try", ":", "assert", "self", ".", "_session", "is", "not", "None", "feed_dict", "=", "collections", ".", "de...
Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF graph.
[ "Run", "batch", "prediciton", "on", "a", "TF", "graph", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L165-L218
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
CSVCoder.encode
def encode(self, tf_graph_predictions): """Encodes the graph json prediction into csv. Args: tf_graph_predictions: python dict. Returns: csv string. """ row = [] for col in self._header: row.append(str(tf_graph_predictions[col])) return ','.join(row)
python
def encode(self, tf_graph_predictions): """Encodes the graph json prediction into csv. Args: tf_graph_predictions: python dict. Returns: csv string. """ row = [] for col in self._header: row.append(str(tf_graph_predictions[col])) return ','.join(row)
[ "def", "encode", "(", "self", ",", "tf_graph_predictions", ")", ":", "row", "=", "[", "]", "for", "col", "in", "self", ".", "_header", ":", "row", ".", "append", "(", "str", "(", "tf_graph_predictions", "[", "col", "]", ")", ")", "return", "','", "."...
Encodes the graph json prediction into csv. Args: tf_graph_predictions: python dict. Returns: csv string.
[ "Encodes", "the", "graph", "json", "prediction", "into", "csv", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L251-L264
googledatalab/pydatalab
google/datalab/stackdriver/monitoring/_query_metadata.py
QueryMetadata.as_dataframe
def as_dataframe(self, max_rows=None): """Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and me...
python
def as_dataframe(self, max_rows=None): """Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and me...
[ "def", "as_dataframe", "(", "self", ",", "max_rows", "=", "None", ")", ":", "max_rows", "=", "len", "(", "self", ".", "_timeseries_list", ")", "if", "max_rows", "is", "None", "else", "max_rows", "headers", "=", "[", "{", "'resource'", ":", "ts", ".", "...
Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and metric labels. Each row in this dataframe correspo...
[ "Creates", "a", "pandas", "dataframe", "from", "the", "query", "metadata", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_query_metadata.py#L53-L92
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
get_train_eval_files
def get_train_eval_files(input_dir): """Get preprocessed training and eval files.""" data_dir = _get_latest_data_dir(input_dir) train_pattern = os.path.join(data_dir, 'train*.tfrecord.gz') eval_pattern = os.path.join(data_dir, 'eval*.tfrecord.gz') train_files = file_io.get_matching_files(train_pattern) eval...
python
def get_train_eval_files(input_dir): """Get preprocessed training and eval files.""" data_dir = _get_latest_data_dir(input_dir) train_pattern = os.path.join(data_dir, 'train*.tfrecord.gz') eval_pattern = os.path.join(data_dir, 'eval*.tfrecord.gz') train_files = file_io.get_matching_files(train_pattern) eval...
[ "def", "get_train_eval_files", "(", "input_dir", ")", ":", "data_dir", "=", "_get_latest_data_dir", "(", "input_dir", ")", "train_pattern", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'train*.tfrecord.gz'", ")", "eval_pattern", "=", "os", ".", ...
Get preprocessed training and eval files.
[ "Get", "preprocessed", "training", "and", "eval", "files", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L53-L60
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
get_labels
def get_labels(input_dir): """Get a list of labels from preprocessed output dir.""" data_dir = _get_latest_data_dir(input_dir) labels_file = os.path.join(data_dir, 'labels') with file_io.FileIO(labels_file, 'r') as f: labels = f.read().rstrip().split('\n') return labels
python
def get_labels(input_dir): """Get a list of labels from preprocessed output dir.""" data_dir = _get_latest_data_dir(input_dir) labels_file = os.path.join(data_dir, 'labels') with file_io.FileIO(labels_file, 'r') as f: labels = f.read().rstrip().split('\n') return labels
[ "def", "get_labels", "(", "input_dir", ")", ":", "data_dir", "=", "_get_latest_data_dir", "(", "input_dir", ")", "labels_file", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'labels'", ")", "with", "file_io", ".", "FileIO", "(", "labels_file", ...
Get a list of labels from preprocessed output dir.
[ "Get", "a", "list", "of", "labels", "from", "preprocessed", "output", "dir", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L63-L69
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
read_examples
def read_examples(input_files, batch_size, shuffle, num_epochs=None): """Creates readers and queues for reading example protos.""" files = [] for e in input_files: for path in e.split(','): files.extend(file_io.get_matching_files(path)) thread_count = multiprocessing.cpu_count() # The minimum numbe...
python
def read_examples(input_files, batch_size, shuffle, num_epochs=None): """Creates readers and queues for reading example protos.""" files = [] for e in input_files: for path in e.split(','): files.extend(file_io.get_matching_files(path)) thread_count = multiprocessing.cpu_count() # The minimum numbe...
[ "def", "read_examples", "(", "input_files", ",", "batch_size", ",", "shuffle", ",", "num_epochs", "=", "None", ")", ":", "files", "=", "[", "]", "for", "e", "in", "input_files", ":", "for", "path", "in", "e", ".", "split", "(", "','", ")", ":", "file...
Creates readers and queues for reading example protos.
[ "Creates", "readers", "and", "queues", "for", "reading", "example", "protos", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L72-L117
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
override_if_not_in_args
def override_if_not_in_args(flag, argument, args): """Checks if flags is in args, and if not it adds the flag to args.""" if flag not in args: args.extend([flag, argument])
python
def override_if_not_in_args(flag, argument, args): """Checks if flags is in args, and if not it adds the flag to args.""" if flag not in args: args.extend([flag, argument])
[ "def", "override_if_not_in_args", "(", "flag", ",", "argument", ",", "args", ")", ":", "if", "flag", "not", "in", "args", ":", "args", ".", "extend", "(", "[", "flag", ",", "argument", "]", ")" ]
Checks if flags is in args, and if not it adds the flag to args.
[ "Checks", "if", "flags", "is", "in", "args", "and", "if", "not", "it", "adds", "the", "flag", "to", "args", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L120-L123
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
loss
def loss(loss_value): """Calculates aggregated mean loss.""" total_loss = tf.Variable(0.0, False) loss_count = tf.Variable(0, False) total_loss_update = tf.assign_add(total_loss, loss_value) loss_count_update = tf.assign_add(loss_count, 1) loss_op = total_loss / tf.cast(loss_count, tf.float32) return [tot...
python
def loss(loss_value): """Calculates aggregated mean loss.""" total_loss = tf.Variable(0.0, False) loss_count = tf.Variable(0, False) total_loss_update = tf.assign_add(total_loss, loss_value) loss_count_update = tf.assign_add(loss_count, 1) loss_op = total_loss / tf.cast(loss_count, tf.float32) return [tot...
[ "def", "loss", "(", "loss_value", ")", ":", "total_loss", "=", "tf", ".", "Variable", "(", "0.0", ",", "False", ")", "loss_count", "=", "tf", ".", "Variable", "(", "0", ",", "False", ")", "total_loss_update", "=", "tf", ".", "assign_add", "(", "total_l...
Calculates aggregated mean loss.
[ "Calculates", "aggregated", "mean", "loss", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L126-L133
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
accuracy
def accuracy(logits, labels): """Calculates aggregated accuracy.""" is_correct = tf.nn.in_top_k(logits, labels, 1) correct = tf.reduce_sum(tf.cast(is_correct, tf.int32)) incorrect = tf.reduce_sum(tf.cast(tf.logical_not(is_correct), tf.int32)) correct_count = tf.Variable(0, False) incorrect_count = tf.Variab...
python
def accuracy(logits, labels): """Calculates aggregated accuracy.""" is_correct = tf.nn.in_top_k(logits, labels, 1) correct = tf.reduce_sum(tf.cast(is_correct, tf.int32)) incorrect = tf.reduce_sum(tf.cast(tf.logical_not(is_correct), tf.int32)) correct_count = tf.Variable(0, False) incorrect_count = tf.Variab...
[ "def", "accuracy", "(", "logits", ",", "labels", ")", ":", "is_correct", "=", "tf", ".", "nn", ".", "in_top_k", "(", "logits", ",", "labels", ",", "1", ")", "correct", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "cast", "(", "is_correct", ",", "t...
Calculates aggregated accuracy.
[ "Calculates", "aggregated", "accuracy", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L136-L147