idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
237,700
def monitoring ( line , cell = None ) : parser = datalab . utils . commands . CommandParser ( prog = 'monitoring' , description = ( 'Execute various Monitoring-related operations. Use "%monitoring ' '<command> -h" for help on a specific command.' ) ) list_parser = parser . subcommand ( 'list' , 'List the metrics or res...
Implements the monitoring cell magic for ipython notebooks .
237,701
def _render_dataframe ( dataframe ) : data = dataframe . to_dict ( orient = 'records' ) fields = dataframe . columns . tolist ( ) return IPython . core . display . HTML ( datalab . utils . commands . HtmlBuilder . render_table ( data , fields ) )
Helper to render a dataframe as an HTML table .
237,702
def _get_job_status ( line ) : try : args = line . strip ( ) . split ( ) job_name = args [ 0 ] job = None if job_name in _local_jobs : job = _local_jobs [ job_name ] else : raise Exception ( 'invalid job %s' % job_name ) if job is not None : error = '' if job . fatal_error is None else str ( job . fatal_error ) data = ...
magic used as an endpoint for client to get job status .
237,703
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 .
237,704
def delete ( self , wait_for_deletion = True ) : if self . exists ( ) : try : self . _api . objects_delete ( self . _bucket , self . _key ) except Exception as e : raise e if wait_for_deletion : for _ in range ( _MAX_POLL_ATTEMPTS ) : objects = Objects ( self . _bucket , prefix = self . key , delimiter = '/' , context ...
Deletes this object from its bucket .
237,705
def metadata ( self ) : if self . _info is None : try : self . _info = self . _api . objects_get ( self . _bucket , self . _key ) except Exception as e : raise e return ObjectMetadata ( self . _info ) if self . _info else None
Retrieves metadata about the object .
237,706
def read_stream ( self , start_offset = 0 , byte_count = None ) : try : return self . _api . object_download ( self . _bucket , self . _key , start_offset = start_offset , byte_count = byte_count ) except Exception as e : raise e
Reads the content of this object as text .
237,707
def read_lines ( self , max_lines = None ) : if max_lines is None : return self . read_stream ( ) . split ( '\n' ) max_to_read = self . metadata . size bytes_to_read = min ( 100 * max_lines , self . metadata . size ) while True : content = self . read_stream ( byte_count = bytes_to_read ) lines = content . split ( '\n'...
Reads the content of this object as text and return a list of lines up to some max .
237,708
def sample_to ( self , count , skip_header_rows , strategy , target ) : if sys . version_info . major > 2 : xrange = range if strategy == 'BIGQUERY' : import datalab . bigquery as bq if not self . path . startswith ( 'gs://' ) : raise Exception ( 'Cannot use BIGQUERY if data is not in GCS' ) federated_table = self . _c...
Sample rows from GCS or local file and save results to target file .
237,709
def _ParseExample ( self , example_features , example_feature_lists , entries , index ) : features_seen = set ( ) for feature_list , is_feature in zip ( [ example_features , example_feature_lists ] , [ True , False ] ) : sequence_length = None for feature_name in feature_list : if feature_name not in entries : entries ...
Parses data from an example populating a dictionary of feature values .
237,710
def _GetEntries ( self , paths , max_entries , iterator_from_file , is_sequence = False ) : entries = { } index = 0 for filepath in paths : reader = iterator_from_file ( filepath ) for record in reader : if is_sequence : sequence_example = tf . train . SequenceExample . FromString ( record ) self . _ParseExample ( sequ...
Extracts examples into a dictionary of feature values .
237,711
def _GetTfRecordEntries ( self , path , max_entries , is_sequence , iterator_options ) : return self . _GetEntries ( [ path ] , max_entries , partial ( tf . python_io . tf_record_iterator , options = iterator_options ) , is_sequence )
Extracts TFRecord examples into a dictionary of feature values .
237,712
def buckets_insert ( self , bucket , project_id = None ) : args = { 'project' : project_id if project_id else self . _project_id } data = { 'name' : bucket } url = Api . _ENDPOINT + ( Api . _BUCKET_PATH % '' ) return datalab . utils . Http . request ( url , args = args , data = data , credentials = self . _credentials ...
Issues a request to create a new bucket .
237,713
def objects_delete ( self , bucket , key ) : url = Api . _ENDPOINT + ( Api . _OBJECT_PATH % ( bucket , Api . _escape_key ( key ) ) ) datalab . utils . Http . request ( url , method = 'DELETE' , credentials = self . _credentials , raw_response = True )
Deletes the specified object .
237,714
def list ( self , pattern = '*' ) : if self . _descriptors is None : self . _descriptors = self . _client . list_metric_descriptors ( filter_string = self . _filter_string , type_prefix = self . _type_prefix ) return [ metric for metric in self . _descriptors if fnmatch . fnmatch ( metric . type , pattern ) ]
Returns a list of metric descriptors that match the filters .
237,715
def _from_dataframe ( dataframe , default_type = 'STRING' ) : type_mapping = { 'i' : 'INTEGER' , 'b' : 'BOOLEAN' , 'f' : 'FLOAT' , 'O' : 'STRING' , 'S' : 'STRING' , 'U' : 'STRING' , 'M' : 'TIMESTAMP' } fields = [ ] for column_name , dtype in dataframe . dtypes . iteritems ( ) : fields . append ( { 'name' : column_name ...
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 . Hence it is pruden...
237,716
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 .
237,717
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 .
237,718
def _from_record ( data ) : if isinstance ( data , dict ) : return Schema . _from_dict_record ( data ) elif isinstance ( data , list ) : return Schema . _from_list_record ( data ) else : raise Exception ( 'Cannot create a schema from record %s' % str ( 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 .
237,719
def create_args ( line , namespace ) : args = [ ] for arg in shlex . split ( line ) : if not arg : continue if arg [ 0 ] == '$' : var_name = arg [ 1 : ] if var_name in namespace : args . append ( ( namespace [ var_name ] ) ) else : raise Exception ( 'Undefined variable referenced in command line: %s' % arg ) else : arg...
Expand any meta - variable references in the argument list .
237,720
def parse ( self , line , namespace = None ) : try : if namespace is None : ipy = IPython . get_ipython ( ) namespace = ipy . user_ns args = CommandParser . create_args ( line , namespace ) return self . parse_args ( args ) except Exception as e : print ( str ( e ) ) return None
Parses a line into a dictionary of arguments expanding meta - variables from a namespace .
237,721
def subcommand ( self , name , help ) : if self . _subcommands is None : self . _subcommands = self . add_subparsers ( help = 'commands' ) return self . _subcommands . add_parser ( name , description = help , help = help )
Creates a parser for a sub - command .
237,722
def render_text ( text , preformatted = False ) : return IPython . core . display . HTML ( _html . HtmlBuilder . render_text ( text , preformatted ) )
Return text formatted as a HTML
237,723
def _get_cols ( fields , schema ) : typemap = { 'STRING' : 'string' , 'INT64' : 'number' , 'INTEGER' : 'number' , 'FLOAT' : 'number' , 'FLOAT64' : 'number' , 'BOOL' : 'boolean' , 'BOOLEAN' : 'boolean' , 'DATE' : 'date' , 'TIME' : 'timeofday' , 'DATETIME' : 'datetime' , 'TIMESTAMP' : 'datetime' } cols = [ ] for col in f...
Get column metadata for Google Charts based on field list and schema .
237,724
def _get_data_from_empty_list ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : fields = get_field_list ( fields , schema ) return { 'cols' : _get_cols ( fields , schema ) , 'rows' : [ ] } , 0
Helper function for _get_data that handles empty lists .
237,725
def _get_data_from_table ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : 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 ( fields , schema ) gen = source . range ( first_r...
Helper function for _get_data that handles BQ Tables .
237,726
def replace_vars ( config , env ) : if isinstance ( config , dict ) : for k , v in list ( config . items ( ) ) : if isinstance ( v , dict ) or isinstance ( v , list ) or isinstance ( v , tuple ) : replace_vars ( v , env ) elif isinstance ( v , basestring ) : config [ k ] = expand_var ( v , env ) elif isinstance ( confi...
Replace variable references in config using the supplied env dictionary .
237,727
def parse_config ( config , env , as_dict = True ) : if config is None : return None stripped = config . strip ( ) if len ( stripped ) == 0 : config = { } elif stripped [ 0 ] == '{' : config = json . loads ( config ) else : config = yaml . load ( config ) if as_dict : config = dict ( config ) replace_vars ( config , en...
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 .
237,728
def validate_config ( config , required_keys , optional_keys = None ) : if optional_keys is None : optional_keys = [ ] if not isinstance ( config , dict ) : raise Exception ( 'config is not dict type' ) invalid_keys = set ( config ) - set ( required_keys + optional_keys ) if len ( invalid_keys ) > 0 : raise Exception (...
Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys .
237,729
def validate_config_must_have ( config , required_keys ) : missing_keys = set ( required_keys ) - set ( config ) if len ( missing_keys ) > 0 : raise Exception ( 'Invalid config with missing keys "%s"' % ', ' . join ( missing_keys ) )
Validate a config dictionary to make sure it has all of the specified keys
237,730
def validate_config_has_one_of ( config , one_of_keys ) : intersection = set ( config ) . intersection ( one_of_keys ) if len ( intersection ) > 1 : raise Exception ( 'Only one of the values in "%s" is needed' % ', ' . join ( intersection ) ) if len ( intersection ) == 0 : raise Exception ( 'One of the values in "%s" i...
Validate a config dictionary to make sure it has one and only one key in one_of_keys .
237,731
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 ( e for e in possible_values ) ) )
Validate a config value to make sure it is one of the possible values .
237,732
def validate_gcs_path ( path , require_object ) : bucket , key = datalab . storage . _bucket . parse_name ( path ) if bucket is None : raise Exception ( 'Invalid GCS path "%s"' % path ) if require_object and key is None : raise Exception ( 'It appears the GCS path "%s" is a bucket path but not an object path' % path )
Check whether a given path is a valid GCS path .
237,733
def profile_df ( df ) : return IPython . core . display . HTML ( pandas_profiling . ProfileReport ( df ) . html . replace ( 'bootstrap' , 'nonexistent' ) )
Generate a profile of data in a dataframe .
237,734
def _package_to_staging ( staging_package_url ) : import google . datalab . ml as ml package_root = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '../../' ) ) setup_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , 'master_setup.py' ) ) tar_gz_path = os . p...
Repackage this package from local installed location and copy it to GCS .
237,735
def analyze ( output_dir , dataset , cloud = False , project_id = None ) : job = analyze_async ( output_dir = output_dir , dataset = dataset , cloud = cloud , project_id = project_id ) job . wait ( ) print ( 'Analyze: ' + str ( job . state ) )
Blocking version of analyze_async . See documentation of analyze_async .
237,736
def analyze_async ( output_dir , dataset , cloud = False , project_id = None ) : import google . datalab . utils as du with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) fn = lambda : _analyze ( output_dir , dataset , cloud , project_id ) return du . LambdaJob ( fn , job_id = None )
Analyze data locally or in the cloud with BigQuery .
237,737
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 , layer_sizes , learning_rate , epsilon , job_name , job_name_prefix , config ) : import google . datalab . ml as ml if len ( trai...
Train model using CloudML .
237,738
def predict ( data , training_dir = None , model_name = None , model_version = None , cloud = False ) : if cloud : if not model_version or not model_name : raise ValueError ( 'model_version or model_name is not set' ) if training_dir : raise ValueError ( 'training_dir not needed when cloud is True' ) with warnings . ca...
Runs prediction locally or on the cloud .
237,739
def local_predict ( training_dir , data ) : from . prediction import predict as predict_module tmp_dir = tempfile . mkdtemp ( ) _ , input_file_path = tempfile . mkstemp ( dir = tmp_dir , suffix = '.csv' , prefix = 'input' ) try : if isinstance ( data , pd . DataFrame ) : data . to_csv ( input_file_path , header = False...
Runs local prediction on the prediction graph .
237,740
def cloud_predict ( model_name , model_version , data ) : import google . datalab . ml as ml if isinstance ( data , pd . DataFrame ) : string_buffer = io . StringIO ( ) data . to_csv ( string_buffer , header = None , index = False ) input_data = string_buffer . getvalue ( ) . split ( '\n' ) input_data = [ line for line...
Use Online prediction .
237,741
def batch_predict ( training_dir , prediction_input_file , output_dir , mode , batch_size = 16 , shard_files = True , output_format = 'csv' , cloud = False ) : job = batch_predict_async ( training_dir = training_dir , prediction_input_file = prediction_input_file , output_dir = output_dir , mode = mode , batch_size = b...
Blocking versoin of batch_predict .
237,742
def batch_predict_async ( training_dir , prediction_input_file , output_dir , mode , batch_size = 16 , shard_files = True , output_format = 'csv' , cloud = False ) : import google . datalab . utils as du with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) if cloud : runner_results = cloud_batch_pr...
Local and cloud batch prediction .
237,743
def make_prediction_pipeline ( pipeline , args ) : predicted_values , errors = ( pipeline | 'Read CSV Files' >> beam . io . ReadFromText ( str ( args . predict_data ) , strip_trailing_newlines = True ) | 'Batch Input' >> beam . ParDo ( EmitAsBatchDoFn ( args . batch_size ) ) | 'Run TF Graph on Batches' >> beam . ParDo ...
Builds the prediction pipeline .
237,744
def process ( self , element ) : import collections import apache_beam as beam num_in_batch = 0 try : assert self . _session is not None feed_dict = collections . defaultdict ( list ) for line in element : if line . endswith ( '\n' ) : line = line [ : - 1 ] feed_dict [ self . _input_alias_map . values ( ) [ 0 ] ] . app...
Run batch prediciton on a TF graph .
237,745
def encode ( self , tf_graph_predictions ) : row = [ ] for col in self . _header : row . append ( str ( tf_graph_predictions [ col ] ) ) return ',' . join ( row )
Encodes the graph json prediction into csv .
237,746
def as_dataframe ( self , max_rows = None ) : max_rows = len ( self . _timeseries_list ) if max_rows is None else max_rows headers = [ { 'resource' : ts . resource . _asdict ( ) , 'metric' : ts . metric . _asdict ( ) } for ts in self . _timeseries_list [ : max_rows ] ] if not headers : return pandas . DataFrame ( ) dat...
Creates a pandas dataframe from the query metadata .
237,747
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 . path . join ( data_dir , 'eval*.tfrecord.gz' ) train_files = file_io . get_matching_files ( train_pattern ) eval_files = file_io . get_matching_...
Get preprocessed training and eval files .
237,748
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 , 'r' ) as f : labels = f . read ( ) . rstrip ( ) . split ( '\n' ) return labels
Get a list of labels from preprocessed output dir .
237,749
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 .
237,750
def loss ( loss_value ) : 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 [ total_loss_update ,...
Calculates aggregated mean loss .
237,751
def accuracy ( logits , labels ) : 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 . Var...
Calculates aggregated accuracy .
237,752
def check_dataset ( dataset , mode ) : names = [ x [ 'name' ] for x in dataset . schema ] types = [ x [ 'type' ] for x in dataset . schema ] if mode == 'train' : if ( set ( [ 'image_url' , 'label' ] ) != set ( names ) or any ( t != 'STRING' for t in types ) ) : raise ValueError ( 'Invalid dataset. Expect only "image_ur...
Validate we have a good dataset .
237,753
def get_sources_from_dataset ( p , dataset , mode ) : import apache_beam as beam import csv from google . datalab . ml import CsvDataSet , BigQueryDataSet check_dataset ( dataset , mode ) if type ( dataset ) is CsvDataSet : source_list = [ ] for ii , input_path in enumerate ( dataset . files ) : source_list . append ( ...
get pcollection from dataset .
237,754
def decode_and_resize ( image_str_tensor ) : height = 299 width = 299 channels = 3 image = tf . image . decode_jpeg ( image_str_tensor , channels = channels ) image = tf . expand_dims ( image , 0 ) image = tf . image . resize_bilinear ( image , [ height , width ] , align_corners = False ) image = tf . squeeze ( image ,...
Decodes jpeg string resizes it and returns a uint8 tensor .
237,755
def resize_image ( image_str_tensor ) : image = decode_and_resize ( image_str_tensor ) image = tf . image . encode_jpeg ( image , quality = 100 ) return image
Decodes jpeg string resizes it and re - encode it to jpeg .
237,756
def load_images ( image_files , resize = True ) : images = [ ] for image_file in image_files : with file_io . FileIO ( image_file , 'r' ) as ff : images . append ( ff . read ( ) ) if resize is False : return images image_str_tensor = tf . placeholder ( tf . string , shape = [ None ] ) image = tf . map_fn ( resize_image...
Load images from files and optionally resize it .
237,757
def process_prediction_results ( results , show_image ) : import pandas as pd if ( is_in_IPython ( ) and show_image is True ) : import IPython for image_url , image , label_and_score in results : IPython . display . display_html ( '<p style="font-size:28px">%s(%.5f)</p>' % label_and_score , raw = True ) IPython . displ...
Create DataFrames out of prediction results and display images in IPython if requested .
237,758
def repackage_to_staging ( output_path ) : import google . datalab . ml as ml package_root = os . path . join ( os . path . dirname ( __file__ ) , '../../../' ) setup_py = os . path . join ( os . path . dirname ( __file__ ) , 'setup.py' ) staging_package_url = os . path . join ( output_path , 'staging' , 'image_classif...
Repackage it from local installed location and copy it to GCS .
237,759
def generate_airflow_spec ( name , pipeline_spec ) : task_definitions = '' up_steam_statements = '' parameters = pipeline_spec . get ( 'parameters' ) for ( task_id , task_details ) in sorted ( pipeline_spec [ 'tasks' ] . items ( ) ) : task_def = PipelineGenerator . _get_operator_definition ( task_id , task_details , pa...
Gets the airflow python spec for the Pipeline object .
237,760
def _get_dependency_definition ( task_id , dependencies ) : set_upstream_statements = '' for dependency in dependencies : set_upstream_statements = set_upstream_statements + '{0}.set_upstream({1})' . format ( task_id , dependency ) + '\n' return set_upstream_statements
Internal helper collects all the dependencies of the task and returns the Airflow equivalent python sytax for specifying them .
237,761
def _get_operator_class_name ( task_detail_type ) : task_type_to_operator_prefix_mapping = { 'pydatalab.bq.execute' : ( 'Execute' , 'google.datalab.contrib.bigquery.operators._bq_execute_operator' ) , 'pydatalab.bq.extract' : ( 'Extract' , 'google.datalab.contrib.bigquery.operators._bq_extract_operator' ) , 'pydatalab....
Internal helper gets the name of the Airflow operator class . We maintain this in a map so this method really returns the enum name concatenated with the string Operator .
237,762
def _get_operator_param_name_and_values ( operator_class_name , task_details ) : operator_task_details = task_details . copy ( ) if 'type' in operator_task_details . keys ( ) : del operator_task_details [ 'type' ] if 'up_stream' in operator_task_details . keys ( ) : del operator_task_details [ 'up_stream' ] if ( operat...
Internal helper gets the name of the python parameter for the Airflow operator class . In some cases we do not expose the airflow parameter name in its native form but choose to expose a name that s more standard for Datalab or one that s more friendly . For example Airflow s BigQueryOperator uses bql for the query str...
237,763
def sample ( self , n ) : total = bq . Query ( 'select count(*) from %s' % self . _get_source ( ) ) . execute ( ) . result ( ) [ 0 ] . values ( ) [ 0 ] if n > total : raise ValueError ( 'sample larger than population' ) sampling = bq . Sampling . random ( percent = n * 100.0 / float ( total ) ) if self . _query is not ...
Samples data into a Pandas DataFrame . Note that it calls BigQuery so it will incur cost .
237,764
def size ( self ) : import tensorflow as tf if self . _size is None : self . _size = 0 options = tf . python_io . TFRecordOptions ( tf . python_io . TFRecordCompressionType . GZIP ) for tfexample_file in self . files : self . _size += sum ( 1 for x in tf . python_io . tf_record_iterator ( tfexample_file , options = opt...
The number of instances in the data . If the underlying data source changes it may be outdated .
237,765
def list ( self , pattern = '*' ) : if self . _group_dict is None : self . _group_dict = collections . OrderedDict ( ( group . id , group ) for group in self . _client . list_groups ( ) ) return [ group for group in self . _group_dict . values ( ) if fnmatch . fnmatch ( group . display_name , pattern ) ]
Returns a list of groups that match the filters .
237,766
def as_dataframe ( self , pattern = '*' , max_rows = None ) : data = [ ] for i , group in enumerate ( self . list ( pattern ) ) : if max_rows is not None and i >= max_rows : break parent = self . _group_dict . get ( group . parent_id ) parent_display_name = '' if parent is None else parent . display_name data . append ...
Creates a pandas dataframe from the groups that match the filters .
237,767
def _find_recursive_dependencies ( sql , values , code , resolved_vars , resolving_vars = None ) : dependencies = SqlStatement . _get_dependencies ( sql ) for dependency in dependencies : if dependency in resolved_vars : continue dep = datalab . utils . get_item ( values , dependency ) if isinstance ( dep , types . Mod...
Recursive helper method for expanding variables including transitive dependencies .
237,768
def format ( sql , args = None ) : resolved_vars = { } code = [ ] SqlStatement . _find_recursive_dependencies ( sql , args , code = code , resolved_vars = resolved_vars ) parts = [ ] for ( escape , placeholder , _ , literal ) in SqlStatement . _get_tokens ( sql ) : if escape : parts . append ( '$' ) elif placeholder : ...
Resolve variable references in a query within an environment .
237,769
def _get_dependencies ( sql ) : dependencies = [ ] for ( _ , placeholder , dollar , _ ) in SqlStatement . _get_tokens ( sql ) : if placeholder : variable = placeholder [ 1 : ] if variable not in dependencies : dependencies . append ( variable ) elif dollar : raise Exception ( 'Invalid sql; $ with no following $ or iden...
Return the list of variables referenced in this SQL .
237,770
def pymodule ( line , cell = None ) : parser = _commands . CommandParser . create ( 'pymodule' ) parser . add_argument ( '-n' , '--name' , help = 'the name of the python module to create and import' ) parser . set_defaults ( func = _pymodule_cell ) return _utils . handle_magic_line ( line , cell , parser )
Creates and subsequently auto - imports a python module .
237,771
def compare_datetimes ( d1 , d2 ) : if d1 . tzinfo is None or d1 . tzinfo . utcoffset ( d1 ) is None : d1 = d1 . replace ( tzinfo = pytz . UTC ) if d2 . tzinfo is None or d2 . tzinfo . utcoffset ( d2 ) is None : d2 = d2 . replace ( tzinfo = pytz . UTC ) if d1 < d2 : return - 1 elif d1 > d2 : return 1 return 0
Compares two datetimes safely whether they are timezone - naive or timezone - aware .
237,772
def pick_unused_port ( ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . bind ( ( 'localhost' , 0 ) ) addr , port = s . getsockname ( ) s . close ( ) return port
get an unused port on the VM .
237,773
def is_http_running_on ( port ) : try : conn = httplib . HTTPConnection ( '127.0.0.1:' + str ( port ) ) conn . connect ( ) conn . close ( ) return True except Exception : return False
Check if an http server runs on a given port .
237,774
def save_project_id ( project_id ) : try : subprocess . call ( [ 'gcloud' , 'config' , 'set' , 'project' , project_id ] ) except : config_file = os . path . join ( get_config_dir ( ) , 'config.json' ) config = { } if os . path . exists ( config_file ) : with open ( config_file ) as f : config = json . loads ( f . read ...
Save project id to config file .
237,775
def get_default_project_id ( ) : try : proc = subprocess . Popen ( [ 'gcloud' , 'config' , 'list' , '--format' , 'value(core.project)' ] , stdout = subprocess . PIPE ) stdout , _ = proc . communicate ( ) value = stdout . strip ( ) if proc . poll ( ) == 0 and value : if isinstance ( value , six . string_types ) : return...
Get default project id from config or environment var .
237,776
def _construct_context_for_args ( args ) : global_default_context = google . datalab . Context . default ( ) config = { } for key in global_default_context . config : config [ key ] = global_default_context . config [ key ] billing_tier_arg = args . get ( 'billing' , None ) if billing_tier_arg : config [ 'bigquery_bill...
Construct a new Context for the parsed arguments .
237,777
def python_portable_string ( string , encoding = 'utf-8' ) : if isinstance ( string , six . string_types ) : return string if six . PY3 : return string . decode ( encoding ) raise ValueError ( 'Unsupported type %s' % str ( type ( string ) ) )
Converts bytes into a string type .
237,778
def _storage_list_buckets ( project , pattern ) : data = [ { 'Bucket' : 'gs://' + bucket . name , 'Created' : bucket . metadata . created_on } for bucket in datalab . storage . Buckets ( project_id = project ) if fnmatch . fnmatch ( bucket . name , pattern ) ] return datalab . utils . commands . render_dictionary ( dat...
List all storage buckets that match a pattern .
237,779
def _storage_list_keys ( bucket , pattern ) : data = [ { 'Name' : item . metadata . name , 'Type' : item . metadata . content_type , 'Size' : item . metadata . size , 'Updated' : item . metadata . updated_on } for item in _storage_get_keys ( bucket , pattern ) ] return datalab . utils . commands . render_dictionary ( d...
List all storage keys in a specified bucket that match a pattern .
237,780
def tables_list ( self , dataset_name , max_results = 0 , page_token = None ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % ( dataset_name . project_id , dataset_name . dataset_id , '' , '' ) ) args = { } if max_results != 0 : args [ 'maxResults' ] = max_results if page_token is not None : args [ 'pageToken' ] = pag...
Issues a request to retrieve a list of tables .
237,781
def _bag_of_words ( x ) : def _bow ( x ) : return tf . SparseTensor ( indices = x . indices , values = tf . to_float ( tf . ones_like ( x . values ) ) , dense_shape = x . dense_shape ) return _bow ( x )
Computes bag of words weights
237,782
def csv_header_and_defaults ( features , schema , stats , keep_target ) : target_name = get_target_name ( features ) if keep_target and not target_name : raise ValueError ( 'Cannot find target transform' ) csv_header = [ ] record_defaults = [ ] for col in schema : if not keep_target and col [ 'name' ] == target_name : ...
Gets csv header and default lists .
237,783
def build_csv_serving_tensors_for_transform_step ( analysis_path , features , schema , stats , keep_target ) : csv_header , record_defaults = csv_header_and_defaults ( features , schema , stats , keep_target ) placeholder = tf . placeholder ( dtype = tf . string , shape = ( None , ) , name = 'csv_input_placeholder' ) t...
Builds a serving function starting from raw csv .
237,784
def build_csv_serving_tensors_for_training_step ( analysis_path , features , schema , stats , keep_target ) : transformed_features , _ , placeholder_dict = build_csv_serving_tensors_for_transform_step ( analysis_path = analysis_path , features = features , schema = schema , stats = stats , keep_target = keep_target ) t...
Builds a serving function starting from raw csv used at model export time .
237,785
def build_csv_transforming_training_input_fn ( schema , features , stats , analysis_output_dir , raw_data_file_pattern , training_batch_size , num_epochs = None , randomize_input = False , min_after_dequeue = 1 , reader_num_threads = 1 , allow_smaller_final_batch = True ) : def raw_training_input_fn ( ) : if isinstance...
Creates training input_fn that reads raw csv data and applies transforms .
237,786
def build_tfexample_transfored_training_input_fn ( schema , features , analysis_output_dir , raw_data_file_pattern , training_batch_size , num_epochs = None , randomize_input = False , min_after_dequeue = 1 , reader_num_threads = 1 , allow_smaller_final_batch = True ) : def transformed_training_input_fn ( ) : if isinst...
Creates training input_fn that reads transformed tf . example files .
237,787
def image_feature_engineering ( features , feature_tensors_dict ) : engineered_features = { } for name , feature_tensor in six . iteritems ( feature_tensors_dict ) : if name in features and features [ name ] [ 'transform' ] == IMAGE_TRANSFORM : with tf . name_scope ( name , 'Wx_plus_b' ) : hidden = tf . contrib . layer...
Add a hidden layer on image features .
237,788
def read_vocab_file ( file_path ) : with file_io . FileIO ( file_path , 'r' ) as f : vocab_pd = pd . read_csv ( f , header = None , names = [ 'vocab' , 'count' ] , dtype = str , na_filter = False ) vocab = vocab_pd [ 'vocab' ] . tolist ( ) ex_count = vocab_pd [ 'count' ] . astype ( int ) . tolist ( ) return vocab , ex_...
Reads a vocab file to memeory .
237,789
def _to_query_json ( self ) : json = { 'compression' : 'GZIP' if self . _compressed else 'NONE' , 'ignoreUnknownValues' : self . _ignore_unknown_values , 'maxBadRecords' : self . _max_bad_records , 'sourceFormat' : self . _bq_source_format , 'sourceUris' : self . _source , } if self . _source_format == 'csv' and self ....
Return the table as a dictionary to be used as JSON in a query job .
237,790
def load_ipython_extension ( shell ) : def _request ( self , uri , method = "GET" , body = None , headers = None , redirections = _httplib2 . DEFAULT_MAX_REDIRECTS , connection_type = None ) : if headers is None : headers = { } headers [ 'user-agent' ] = 'GoogleCloudDataLab/1.0' return _orig_request ( self , uri , meth...
Called when the extension is loaded .
237,791
def _get_sql_args ( parser , args = None ) : overrides = None if args is None : tokens = [ ] elif isinstance ( args , basestring ) : command_line = ' ' . join ( args . split ( '\n' ) ) tokens = shlex . split ( command_line ) elif isinstance ( args , dict ) : overrides = args tokens = [ ] else : tokens = args args = { }...
Parse a set of %%sql arguments or get the default value of the arguments .
237,792
def get_sql_statement_with_environment ( item , args = None ) : if isinstance ( item , basestring ) : item = _sql_statement . SqlStatement ( item ) elif not isinstance ( item , _sql_statement . SqlStatement ) : item = SqlModule . get_default_query_from_module ( item ) if not item : raise Exception ( 'Expected a SQL sta...
Given a SQLStatement string or module plus command line args or a dictionary return a SqlStatement and final dictionary for variable resolution .
237,793
def expand ( sql , args = None ) : sql , args = SqlModule . get_sql_statement_with_environment ( sql , args ) return _sql_statement . SqlStatement . format ( sql . _sql , args )
Expand a SqlStatement query string or SqlModule with a set of arguments .
237,794
def parse_dataset_name ( name , project_id = None ) : _project_id = _dataset_id = None if isinstance ( name , basestring ) : m = re . match ( _ABS_DATASET_NAME_PATTERN , name , re . IGNORECASE ) if m is not None : _project_id , _dataset_id = m . groups ( ) else : m = re . match ( _REL_DATASET_NAME_PATTERN , name ) if m...
Parses a dataset name into its individual parts .
237,795
def parse_table_name ( name , project_id = None , dataset_id = None ) : _project_id = _dataset_id = _table_id = _decorator = None if isinstance ( name , basestring ) : m = re . match ( _ABS_TABLE_NAME_PATTERN , name , re . IGNORECASE ) if m is not None : _project_id , _dataset_id , _table_id , _decorator = m . groups (...
Parses a table name into its individual parts .
237,796
def _make_text_predict_fn ( self , labels , instance , column_to_explain ) : def _predict_fn ( perturbed_text ) : predict_input = [ ] for x in perturbed_text : instance_copy = dict ( instance ) instance_copy [ column_to_explain ] = x predict_input . append ( instance_copy ) df = _local_predict . get_prediction_results ...
Create a predict_fn that can be used by LIME text explainer .
237,797
def _make_image_predict_fn ( self , labels , instance , column_to_explain ) : def _predict_fn ( perturbed_image ) : predict_input = [ ] for x in perturbed_image : instance_copy = dict ( instance ) instance_copy [ column_to_explain ] = Image . fromarray ( x ) predict_input . append ( instance_copy ) df = _local_predict ...
Create a predict_fn that can be used by LIME image explainer .
237,798
def _get_unique_categories ( self , df ) : categories = [ ] for col in self . _categorical_columns : categocial = pd . Categorical ( df [ col ] ) col_categories = list ( map ( str , categocial . categories ) ) col_categories . append ( '_UNKNOWN' ) categories . append ( col_categories ) return categories
Get all categories for each categorical columns from training data .
237,799
def _preprocess_data_for_tabular_explain ( self , df , categories ) : df = df . copy ( ) for col in list ( df . columns ) : if col not in ( self . _categorical_columns + self . _numeric_columns ) : del df [ col ] for col_name , col_categories in zip ( self . _categorical_columns , categories ) : df [ col_name ] = df [ ...
Get preprocessed training set in numpy array and categorical names from raw training data .