idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
48,900 | 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 . |
48,901 | 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 . |
48,902 | 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 . |
48,903 | 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 . |
48,904 | 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 . |
48,905 | 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 . |
48,906 | 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 . |
48,907 | 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 . |
48,908 | 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 . |
48,909 | 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 . |
48,910 | 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 . |
48,911 | 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 . |
48,912 | 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 . |
48,913 | 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 . |
48,914 | 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 . |
48,915 | 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 . |
48,916 | 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 |
48,917 | 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 . |
48,918 | 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 . |
48,919 | 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 . |
48,920 | 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 . |
48,921 | 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 . |
48,922 | 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 . |
48,923 | 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 . |
48,924 | 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 . |
48,925 | 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 . |
48,926 | 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 . |
48,927 | 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 . |
48,928 | 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 . |
48,929 | 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 . |
48,930 | 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 . |
48,931 | 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 . |
48,932 | 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 . |
48,933 | 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 . |
48,934 | 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 . |
48,935 | def _make_tabular_predict_fn ( self , labels , instance , categories ) : def _predict_fn ( np_instance ) : df = pd . DataFrame ( np_instance , columns = ( self . _categorical_columns + self . _numeric_columns ) ) for col_name , col_categories in zip ( self . _categorical_columns , categories ) : df [ col_name ] = df [ ... | Create a predict_fn that can be used by LIME tabular explainer . |
48,936 | def explain_tabular ( self , trainset , labels , instance , num_features = 5 , kernel_width = 3 ) : from lime . lime_tabular import LimeTabularExplainer if isinstance ( instance , six . string_types ) : instance = next ( csv . DictReader ( [ instance ] , fieldnames = self . _headers ) ) categories = self . _get_unique_... | Explain categorical and numeric features for a prediction . |
48,937 | def explain_text ( self , labels , instance , column_name = None , num_features = 10 , num_samples = 5000 ) : from lime . lime_text import LimeTextExplainer if len ( self . _text_columns ) > 1 and not column_name : raise ValueError ( 'There are multiple text columns in the input of the model. ' + 'Please specify "colum... | Explain a text field of a prediction . |
48,938 | def explain_image ( self , labels , instance , column_name = None , num_features = 100000 , num_samples = 300 , batch_size = 200 , hide_color = 0 ) : from lime . lime_image import LimeImageExplainer if len ( self . _image_columns ) > 1 and not column_name : raise ValueError ( 'There are multiple image columns in the in... | Explain an image of a prediction . |
48,939 | def probe_image ( self , labels , instance , column_name = None , num_scaled_images = 50 , top_percent = 10 ) : if len ( self . _image_columns ) > 1 and not column_name : raise ValueError ( 'There are multiple image columns in the input of the model. ' + 'Please specify "column_name".' ) elif column_name and column_nam... | Get pixel importance of the image . |
48,940 | def get_model_details ( self , model_name ) : full_name = model_name if not model_name . startswith ( 'projects/' ) : full_name = ( 'projects/%s/models/%s' % ( self . _project_id , model_name ) ) return self . _api . projects ( ) . models ( ) . get ( name = full_name ) . execute ( ) | Get details of the specified model from CloudML Service . |
48,941 | def create ( self , model_name ) : body = { 'name' : model_name } parent = 'projects/' + self . _project_id return self . _api . projects ( ) . models ( ) . create ( body = body , parent = parent ) . execute ( ) | Create a model . |
48,942 | def list ( self , count = 10 ) : import IPython data = [ ] for _ , model in zip ( range ( count ) , self . get_iterator ( ) ) : element = { 'name' : model [ 'name' ] } if 'defaultVersion' in model : version_short_name = model [ 'defaultVersion' ] [ 'name' ] . split ( '/' ) [ - 1 ] element [ 'defaultVersion' ] = version... | List models under the current project in a table view . |
48,943 | def get_version_details ( self , version_name ) : name = ( '%s/versions/%s' % ( self . _full_model_name , version_name ) ) return self . _api . projects ( ) . models ( ) . versions ( ) . get ( name = name ) . execute ( ) | Get details of a version . |
48,944 | def deploy ( self , version_name , path , runtime_version = None ) : if not path . startswith ( 'gs://' ) : raise Exception ( 'Invalid path. Only Google Cloud Storage path (gs://...) is accepted.' ) if not datalab . storage . Object . from_url ( os . path . join ( path , 'export.meta' ) ) . exists ( ) and not datalab .... | Deploy a model version to the cloud . |
48,945 | def delete ( self , version_name ) : name = ( '%s/versions/%s' % ( self . _full_model_name , version_name ) ) response = self . _api . projects ( ) . models ( ) . versions ( ) . delete ( name = name ) . execute ( ) if 'name' not in response : raise Exception ( 'Invalid response from service. "name" is not found.' ) _ut... | Delete a version of model . |
48,946 | def predict ( self , version_name , data ) : full_version_name = ( '%s/versions/%s' % ( self . _full_model_name , version_name ) ) request = self . _api . projects ( ) . predict ( body = { 'instances' : data } , name = full_version_name ) request . headers [ 'user-agent' ] = 'GoogleCloudDataLab/1.0' result = request . ... | Get prediction results from features instances . |
48,947 | def list ( self ) : import IPython data = [ { 'name' : version [ 'name' ] . split ( ) [ - 1 ] , 'deploymentUri' : version [ 'deploymentUri' ] , 'createTime' : version [ 'createTime' ] } for version in self . get_iterator ( ) ] IPython . display . display ( datalab . utils . commands . render_dictionary ( data , [ 'name... | List versions under the current model in a table view . |
48,948 | def create_feature_map ( features , feature_indices , output_dir ) : feature_map = [ ] for name , info in feature_indices : transform_name = features [ name ] [ 'transform' ] source_column = features [ name ] [ 'source_column' ] if transform_name in [ IDENTITY_TRANSFORM , SCALE_TRANSFORM ] : feature_map . append ( ( in... | Returns feature_map about the transformed features . |
48,949 | def create ( self , query ) : if isinstance ( query , _query . Query ) : query = query . sql try : response = self . _table . _api . tables_insert ( self . _table . name , query = query ) except Exception as e : raise e if 'selfLink' in response : return self raise Exception ( "View %s could not be created as it alread... | Creates the view with the specified query . |
48,950 | def sample ( self , fields = None , count = 5 , sampling = None , use_cache = True , dialect = None , billing_tier = None ) : return self . _table . sample ( fields = fields , count = count , sampling = sampling , use_cache = use_cache , dialect = dialect , billing_tier = billing_tier ) | Retrieves a sampling of data from the view . |
48,951 | def update ( self , friendly_name = None , description = None , query = None ) : self . _table . _load_info ( ) if query is not None : if isinstance ( query , _query . Query ) : query = query . sql self . _table . _info [ 'view' ] = { 'query' : query } self . _table . update ( friendly_name = friendly_name , descriptio... | Selectively updates View information . |
48,952 | def results ( self , use_cache = True , dialect = None , billing_tier = None ) : return self . _materialization . results ( use_cache = use_cache , dialect = dialect , billing_tier = billing_tier ) | Materialize the view synchronously . |
48,953 | def execute_async ( self , table_name = None , table_mode = 'create' , use_cache = True , priority = 'high' , allow_large_results = False , dialect = None , billing_tier = None ) : return self . _materialization . execute_async ( table_name = table_name , table_mode = table_mode , use_cache = use_cache , priority = pri... | Materialize the View asynchronously . |
48,954 | def get_notebook_item ( name ) : env = notebook_environment ( ) return google . datalab . utils . get_item ( env , name ) | Get an item from the IPython environment . |
48,955 | def _get_data_from_list_of_dicts ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : if schema is None : schema = google . datalab . bigquery . Schema . from_data ( source ) fields = get_field_list ( fields , schema ) gen = source [ first_row : first_row + count ] if count >= 0 else source rows = ... | Helper function for _get_data that handles lists of dicts . |
48,956 | def _get_data_from_list_of_lists ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : if schema is None : schema = google . datalab . bigquery . Schema . from_data ( source ) fields = get_field_list ( fields , schema ) gen = source [ first_row : first_row + count ] if count >= 0 else source cols = ... | Helper function for _get_data that handles lists of lists . |
48,957 | def _get_data_from_dataframe ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : if schema is None : schema = google . datalab . bigquery . Schema . from_data ( source ) fields = get_field_list ( fields , schema ) rows = [ ] if count < 0 : count = len ( source . index ) df_slice = source . reset_i... | Helper function for _get_data that handles Pandas DataFrames . |
48,958 | def parse_config_for_selected_keys ( content , keys ) : config_items = { key : None for key in keys } if not content : return config_items , content stripped = content . strip ( ) if len ( stripped ) == 0 : return { } , None elif stripped [ 0 ] == '{' : config = json . loads ( content ) else : config = yaml . load ( co... | Parse a config from a magic cell body for selected config keys . |
48,959 | def chart_html ( driver_name , chart_type , source , chart_options = None , fields = '*' , refresh_interval = 0 , refresh_data = None , control_defaults = None , control_ids = None , schema = None ) : div_id = _html . Html . next_id ( ) controls_html = '' if control_defaults is None : control_defaults = { } if control_... | Return HTML for a chart . |
48,960 | def default ( fields = None , count = 5 ) : projection = Sampling . _create_projection ( fields ) return lambda sql : 'SELECT %s FROM (%s) LIMIT %d' % ( projection , sql , count ) | Provides a simple default sampling strategy which limits the result set by a count . |
48,961 | def sorted ( field_name , ascending = True , fields = None , count = 5 ) : if field_name is None : raise Exception ( 'Sort field must be specified' ) direction = '' if ascending else ' DESC' projection = Sampling . _create_projection ( fields ) return lambda sql : 'SELECT %s FROM (%s) ORDER BY %s%s LIMIT %d' % ( projec... | Provides a sampling strategy that picks from an ordered set of rows . |
48,962 | def hashed ( field_name , percent , fields = None , count = 0 ) : if field_name is None : raise Exception ( 'Hash field must be specified' ) def _hashed_sampling ( sql ) : projection = Sampling . _create_projection ( fields ) sql = 'SELECT %s FROM (%s) WHERE MOD(ABS(FARM_FINGERPRINT(CAST(%s AS STRING))), 100) < %d' % (... | Provides a sampling strategy based on hashing and selecting a percentage of data . |
48,963 | def random ( percent , fields = None , count = 0 ) : def _random_sampling ( sql ) : projection = Sampling . _create_projection ( fields ) sql = 'SELECT %s FROM (%s) WHERE rand() < %f' % ( projection , sql , ( float ( percent ) / 100.0 ) ) if count != 0 : sql = '%s LIMIT %d' % ( sql , count ) return sql return _random_s... | Provides a sampling strategy that picks a semi - random set of rows . |
48,964 | def _auto ( method , fields , count , percent , key_field , ascending ) : if method == 'limit' : return Sampling . default ( fields = fields , count = count ) elif method == 'random' : return Sampling . random ( fields = fields , percent = percent , count = count ) elif method == 'hashed' : return Sampling . hashed ( f... | Construct a sampling function according to the provided sampling technique provided all its needed fields are passed as arguments |
48,965 | def _to_query_json ( self ) : return { 'quote' : self . _quote , 'fieldDelimiter' : self . _delimiter , 'encoding' : self . _encoding . upper ( ) , 'skipLeadingRows' : self . _skip_leading_rows , 'allowQuotedNewlines' : self . _allow_quoted_newlines , 'allowJaggedRows' : self . _allow_jagged_rows } | Return the options as a dictionary to be used as JSON in a query job . |
48,966 | def jobs_insert_load ( self , source , table_name , append = False , overwrite = False , create = False , source_format = 'CSV' , field_delimiter = ',' , allow_jagged_rows = False , allow_quoted_newlines = False , encoding = 'UTF-8' , ignore_unknown_values = False , max_bad_records = 0 , quote = '"' , skip_leading_rows... | Issues a request to load data from GCS to a BQ table |
48,967 | def jobs_get ( self , job_id , project_id = None ) : if project_id is None : project_id = self . _project_id url = Api . _ENDPOINT + ( Api . _JOBS_PATH % ( project_id , job_id ) ) return datalab . utils . Http . request ( url , credentials = self . _credentials ) | Issues a request to retrieve information about a job . |
48,968 | def datasets_insert ( self , dataset_name , friendly_name = None , description = None ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % ( dataset_name . project_id , '' ) ) data = { 'kind' : 'bigquery#dataset' , 'datasetReference' : { 'projectId' : dataset_name . project_id , 'datasetId' : dataset_name . dataset_id ... | Issues a request to create a dataset . |
48,969 | def datasets_delete ( self , dataset_name , delete_contents ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % dataset_name ) args = { } if delete_contents : args [ 'deleteContents' ] = True return datalab . utils . Http . request ( url , method = 'DELETE' , args = args , credentials = self . _credentials , raw_respo... | Issues a request to delete a dataset . |
48,970 | def datasets_update ( self , dataset_name , dataset_info ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % dataset_name ) return datalab . utils . Http . request ( url , method = 'PUT' , data = dataset_info , credentials = self . _credentials ) | Updates the Dataset info . |
48,971 | def datasets_get ( self , dataset_name ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % dataset_name ) return datalab . utils . Http . request ( url , credentials = self . _credentials ) | Issues a request to retrieve information about a dataset . |
48,972 | def datasets_list ( self , project_id = None , max_results = 0 , page_token = None ) : if project_id is None : project_id = self . _project_id url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % ( project_id , '' ) ) args = { } if max_results != 0 : args [ 'maxResults' ] = max_results if page_token is not None : args [ 'p... | Issues a request to list the datasets in the project . |
48,973 | def tables_get ( self , table_name ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) return datalab . utils . Http . request ( url , credentials = self . _credentials ) | Issues a request to retrieve information about a table . |
48,974 | def tables_insert ( self , table_name , schema = None , query = None , friendly_name = None , description = None ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % ( table_name . project_id , table_name . dataset_id , '' , '' ) ) data = { 'kind' : 'bigquery#table' , 'tableReference' : { 'projectId' : table_name . proje... | Issues a request to create a table or view in the specified dataset with the specified id . A schema must be provided to create a Table or a query must be provided to create a View . |
48,975 | def tabledata_insert_all ( self , table_name , rows ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) + "/insertAll" data = { 'kind' : 'bigquery#tableDataInsertAllRequest' , 'rows' : rows } return datalab . utils . Http . request ( url , data = data , credentials = self . _credentials ) | Issues a request to insert data into a table . |
48,976 | def tabledata_list ( self , table_name , start_index = None , max_results = None , page_token = None ) : url = Api . _ENDPOINT + ( Api . _TABLEDATA_PATH % table_name ) args = { } if start_index : args [ 'startIndex' ] = start_index if max_results : args [ 'maxResults' ] = max_results if page_token is not None : args [ ... | Retrieves the contents of a table . |
48,977 | def table_delete ( self , table_name ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) return datalab . utils . Http . request ( url , method = 'DELETE' , credentials = self . _credentials , raw_response = True ) | Issues a request to delete a table . |
48,978 | def table_extract ( self , table_name , destination , format = 'CSV' , compress = True , field_delimiter = ',' , print_header = True ) : url = Api . _ENDPOINT + ( Api . _JOBS_PATH % ( table_name . project_id , '' ) ) if isinstance ( destination , basestring ) : destination = [ destination ] data = { 'kind' : 'bigquery#... | Exports the table to GCS . |
48,979 | def table_update ( self , table_name , table_info ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) return datalab . utils . Http . request ( url , method = 'PUT' , data = table_info , credentials = self . _credentials ) | Updates the Table info . |
48,980 | def extract_archive ( archive_path , dest ) : if not os . path . isdir ( dest ) : os . makedirs ( dest ) try : tmpfolder = None if ( not tf . gfile . Exists ( archive_path ) ) or tf . gfile . IsDirectory ( archive_path ) : raise ValueError ( 'archive path %s is not a file' % archive_path ) if archive_path . startswith ... | Extract a local or GCS archive file to a folder . |
48,981 | def preprocess ( train_dataset , output_dir , eval_dataset , checkpoint , pipeline_option ) : import apache_beam as beam import google . datalab . utils from . import _preprocess if checkpoint is None : checkpoint = _util . _DEFAULT_CHECKPOINT_GSURL job_name = ( 'preprocess-image-classification-' + datetime . datetime ... | Preprocess data in Cloud with DataFlow . |
48,982 | def train ( input_dir , batch_size , max_steps , output_dir , checkpoint , cloud_train_config ) : import google . datalab . ml as ml if checkpoint is None : checkpoint = _util . _DEFAULT_CHECKPOINT_GSURL staging_package_url = _util . repackage_to_staging ( output_dir ) job_args = { 'input_dir' : input_dir , 'max_steps'... | Train model in the cloud with CloudML trainer service . |
48,983 | def from_table ( table , fields = None ) : if fields is None : fields = '*' elif isinstance ( fields , list ) : fields = ',' . join ( fields ) return Query ( 'SELECT %s FROM %s' % ( fields , table . _repr_sql_ ( ) ) ) | Return a Query for the given Table object |
48,984 | def _expanded_sql ( self , sampling = None ) : udfs = [ ] subqueries = [ ] expanded_sql = '' def _recurse_subqueries ( query ) : if query . _subqueries : for subquery in query . _subqueries : _recurse_subqueries ( subquery [ 1 ] ) subqueries . extend ( [ s for s in query . _subqueries if s not in subqueries ] ) if quer... | Get the expanded SQL of this object including all subqueries UDFs and external datasources |
48,985 | def run_and_monitor ( args , pid_to_wait , std_out_filter_fn = None , cwd = None ) : monitor_process = None try : p = subprocess . Popen ( args , cwd = cwd , env = os . environ , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) pids_to_kill = [ p . pid ] script = ( 'import %s;%s._wait_and_kill(%s, %s)' % ( _... | Start a process and have it depend on another specified process . |
48,986 | def created_on ( self ) : timestamp = self . _info . get ( 'creationTime' ) return _parser . Parser . parse_timestamp ( timestamp ) | The creation timestamp . |
48,987 | def expires_on ( self ) : timestamp = self . _info . get ( 'expirationTime' , None ) if timestamp is None : return None return _parser . Parser . parse_timestamp ( timestamp ) | The timestamp for when the table will expire or None if unknown . |
48,988 | def modified_on ( self ) : timestamp = self . _info . get ( 'lastModifiedTime' ) return _parser . Parser . parse_timestamp ( timestamp ) | The timestamp for when the table was last modified . |
48,989 | def _load_info ( self ) : if self . _info is None : try : self . _info = self . _api . tables_get ( self . _name_parts ) except Exception as e : raise e | Loads metadata about this table . |
48,990 | def exists ( self ) : try : info = self . _api . tables_get ( self . _name_parts ) except google . datalab . utils . RequestException as e : if e . status == 404 : return False raise e except Exception as e : raise e self . _info = info return True | Checks if the table exists . |
48,991 | def delete ( self ) : try : self . _api . table_delete ( self . _name_parts ) except google . datalab . utils . RequestException : pass except Exception as e : raise e return not self . exists ( ) | Delete the table . |
48,992 | def create ( self , schema , overwrite = False ) : if overwrite and self . exists ( ) : self . delete ( ) if not isinstance ( schema , _schema . Schema ) : schema = _schema . Schema ( schema ) try : response = self . _api . tables_insert ( self . _name_parts , schema = schema . _bq_schema ) except Exception as e : rais... | Create the table with the specified schema . |
48,993 | def _init_job_from_response ( self , response ) : job = None if response and 'jobReference' in response : job = _job . Job ( job_id = response [ 'jobReference' ] [ 'jobId' ] , context = self . _context ) return job | Helper function to create a Job instance from a response . |
48,994 | def extract_async ( self , destination , format = 'csv' , csv_delimiter = None , csv_header = True , compress = False ) : format = format . upper ( ) if format == 'JSON' : format = 'NEWLINE_DELIMITED_JSON' if format == 'CSV' and csv_delimiter is None : csv_delimiter = ',' try : response = self . _api . table_extract ( ... | Starts a job to export the table to GCS . |
48,995 | def extract ( self , destination , format = 'csv' , csv_delimiter = None , csv_header = True , compress = False ) : job = self . extract_async ( destination , format = format , csv_delimiter = csv_delimiter , csv_header = csv_header , compress = compress ) if job is not None : job . wait ( ) return job | Exports the table to GCS ; blocks until complete . |
48,996 | def load_async ( self , source , mode = 'create' , source_format = 'csv' , csv_options = None , ignore_unknown_values = False , max_bad_records = 0 ) : if source_format == 'csv' : source_format = 'CSV' elif source_format == 'json' : source_format = 'NEWLINE_DELIMITED_JSON' else : raise Exception ( "Invalid source forma... | Starts importing a table from GCS and return a Future . |
48,997 | def load ( self , source , mode = 'create' , source_format = 'csv' , csv_options = None , ignore_unknown_values = False , max_bad_records = 0 ) : job = self . load_async ( source , mode = mode , source_format = source_format , csv_options = csv_options , ignore_unknown_values = ignore_unknown_values , max_bad_records =... | Load the table from GCS . |
48,998 | def _get_row_fetcher ( self , start_row = 0 , max_rows = None , page_size = _DEFAULT_PAGE_SIZE ) : if not start_row : start_row = 0 elif start_row < 0 : if self . length >= 0 : start_row += self . length else : raise Exception ( 'Cannot use negative indices for table of unknown length' ) schema = self . schema . _bq_sc... | Get a function that can retrieve a page of rows . |
48,999 | def schema ( self ) : if not self . _schema : try : self . _load_info ( ) self . _schema = _schema . Schema ( self . _info [ 'schema' ] [ 'fields' ] ) except KeyError : raise Exception ( 'Unexpected table response: missing schema' ) return self . _schema | Retrieves the schema of the table . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.