text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _preprocess_individuals(self, individuals): """Preprocess DEAP individuals before pipeline evaluation. Parameters individuals: a list of DEAP individual One ...
# update self._pbar.total if not (self.max_time_mins is None) and not self._pbar.disable and self._pbar.total <= self._pbar.n: self._pbar.total += self._lambda # Check we do not evaluate twice the same individual in one pass. _, unique_individual_indices = np.unique([str(ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_evaluated_individuals_(self, result_score_list, eval_individuals_str, operator_counts, stats_dicts): """Update self.evaluated_individuals_ and error ...
for result_score, individual_str in zip(result_score_list, eval_individuals_str): if type(result_score) in [float, np.float64, np.float32]: self.evaluated_individuals_[individual_str] = self._combine_individual_stats(operator_counts[individual_str], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_pbar(self, pbar_num=1, pbar_msg=None): """Update self._pbar and error message during pipeline evaluation. Parameters pbar_num: int How many pipelines...
if not isinstance(self._pbar, type(None)): if self.verbosity > 2 and pbar_msg is not None: self._pbar.write(pbar_msg, file=self._file) if not self._pbar.disable: self._pbar.update(pbar_num)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _random_mutation_operator(self, individual, allow_shrink=True): """Perform a replacement, insertion, or shrink mutation on an individual. Parameters individu...
if self.tree_structure: mutation_techniques = [ partial(gp.mutInsert, pset=self._pset), partial(mutNodeReplacement, pset=self._pset) ] # We can't shrink pipelines with only one primitive, so we only add it if we find more primitives. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_grow_safe(self, pset, min_, max_, type_=None): """Generate an expression where each leaf might have a different depth between min_ and max_. Parameters ...
def condition(height, depth, type_): """Stop when the depth is equal to height or when a node should be a terminal.""" return type_ not in self.ret_types or depth == height return self._generate(pset, min_, max_, condition, type_)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _operator_count(self, individual): """Count the number of pipeline operators as a measure of pipeline complexity. Parameters individual: list A grown tree wi...
operator_count = 0 for i in range(len(individual)): node = individual[i] if type(node) is deap.gp.Primitive and node.name != 'CombineDFs': operator_count += 1 return operator_count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_val(self, val, result_score_list): """Update values in the list of result scores and self._pbar during pipeline evaluation. Parameters val: float or ...
self._update_pbar() if val == 'Timeout': self._update_pbar(pbar_msg=('Skipped pipeline #{0} due to time out. ' 'Continuing to the next pipeline.'.format(self._pbar.n))) result_score_list.append(-float('inf')) else: resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate(self, pset, min_, max_, condition, type_=None): """Generate a Tree as a list of lists. The tree is build from the root to the leaves, and it stop g...
if type_ is None: type_ = pset.ret expr = [] height = np.random.randint(min_, max_) stack = [(0, type_)] while len(stack) != 0: depth, type_ = stack.pop() # We've added a type_ parameter to the condition function if condition(heig...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, X): """Select categorical features and transform them using OneHotEncoder. Parameters X: numpy ndarray, {n_samples, n_components} New data, w...
selected = auto_select_categorical_features(X, threshold=self.threshold) X_sel, _, n_selected, _ = _X_selected(X, selected) if n_selected == 0: # No features selected. raise ValueError('No categorical feature was found!') else: ohe = OneHotEncoder(ca...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, X): """Select continuous features and transform them using PCA. Parameters X: numpy ndarray, {n_samples, n_components} New data, where n_samp...
selected = auto_select_categorical_features(X, threshold=self.threshold) _, X_sel, n_selected, _ = _X_selected(X, selected) if n_selected == 0: # No features selected. raise ValueError('No continuous feature was found!') else: pca = PCA(svd_solver=se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit(self, X, y=None, **fit_params): """Fit the StackingEstimator meta-transformer. Parameters X: array-like of shape (n_samples, n_features) The training inp...
self.estimator.fit(X, y, **fit_params) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, X, y=None): """Transform data by adding two virtual features. Parameters X: numpy ndarray, {n_samples, n_components} New data, where n_sample...
X = check_array(X) n_features = X.shape[1] X_transformed = np.copy(X) non_zero_vector = np.count_nonzero(X_transformed, axis=1) non_zero = np.reshape(non_zero_vector, (-1, 1)) zero_col = np.reshape(n_features - non_zero_vector, (-1, 1)) X_transformed = np.hsta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def source_decode(sourcecode, verbose=0): """Decode operator source and import operator class. Parameters sourcecode: string a string of operator source (e.g 'sk...
tmp_path = sourcecode.split('.') op_str = tmp_path.pop() import_str = '.'.join(tmp_path) try: if sourcecode.startswith('tpot.'): exec('from {} import {}'.format(import_str[4:], op_str)) else: exec('from {} import {}'.format(import_str, op_str)) op_obj = e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_sample_weight(pipeline_steps, sample_weight=None): """Recursively iterates through all objects in the pipeline and sets sample weight. Parameters pipelin...
sample_weight_dict = {} if not isinstance(sample_weight, type(None)): for (pname, obj) in pipeline_steps: if inspect.getargspec(obj.fit).args.count('sample_weight'): step_sw = pname + '__sample_weight' sample_weight_dict[step_sw] = sample_weight if sampl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def positive_integer(value): """Ensure that the provided value is a positive integer. Parameters value: int The number to evaluate Returns ------- value: int Ret...
try: value = int(value) except Exception: raise argparse.ArgumentTypeError('Invalid int value: \'{}\''.format(value)) if value < 0: raise argparse.ArgumentTypeError('Invalid positive int value: \'{}\''.format(value)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_scoring_function(scoring_func): """ converts mymodule.myfunc in the myfunc object itself so tpot receives a scoring function """
if scoring_func and ("." in scoring_func): try: module_name, func_name = scoring_func.rsplit('.', 1) module_path = os.getcwd() sys.path.insert(0, module_path) scoring_func = getattr(import_module(module_name), func_name) sys.path.pop(0) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tpot_driver(args): """Perform a TPOT run."""
if args.VERBOSITY >= 2: _print_args(args) input_data = _read_data_file(args) features = input_data.drop(args.TARGET_NAME, axis=1) training_features, testing_features, training_target, testing_target = \ train_test_split(features, input_data[args.TARGET_NAME], random_state=args.RANDOM_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit(self, X, y=None): """Fit FeatureSetSelector for feature selection Parameters X: array-like of shape (n_samples, n_features) The training input samples. y...
subset_df = pd.read_csv(self.subset_list, header=0, index_col=0) if isinstance(self.sel_subset, int): self.sel_subset_name = subset_df.index[self.sel_subset] elif isinstance(self.sel_subset, str): self.sel_subset_name = self.sel_subset else: # list or tuple ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, X): """Make subset after fit Parameters X: numpy ndarray, {n_samples, n_features} New data, where n_samples is the number of samples and n_fe...
if isinstance(X, pd.DataFrame): X_transformed = X[self.feat_list].values elif isinstance(X, np.ndarray): X_transformed = X[:, self.feat_list_idx] return X_transformed.astype(np.float64)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick_two_individuals_eligible_for_crossover(population): """Pick two individuals from the population which can do crossover, that is, they share a primitive....
primitives_by_ind = [set([node.name for node in ind if isinstance(node, gp.Primitive)]) for ind in population] pop_as_str = [str(ind) for ind in population] eligible_pairs = [(i, i+1+j) for i, ind1_prims in enumerate(primitives_by_ind) for j, ind2_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutate_random_individual(population, toolbox): """Picks a random individual from the population, and performs mutation on a copy of it. Parameters population...
idx = np.random.randint(0,len(population)) ind = population[idx] ind, = toolbox.mutate(ind) del ind.fitness.values return ind
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_name(opname, operators): """Return operator class instance by name. Parameters opname: str Name of the sklearn class that belongs to a TPOT operator o...
ret_op_classes = [op for op in operators if op.__name__ == opname] if len(ret_op_classes) == 0: raise TypeError('Cannot found operator {} in operator dictionary'.format(opname)) elif len(ret_op_classes) > 1: raise ValueError( 'Found duplicate operators {} in operator dictionary...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expr_to_tree(ind, pset): """Convert the unstructured DEAP pipeline into a tree data-structure. Parameters ind: deap.creator.Individual The pipeline that is b...
def prim_to_list(prim, args): if isinstance(prim, deap.gp.Terminal): if prim.name in pset.context: return pset.context[prim.name] else: return prim.value return [prim.name] + args tree = [] stack = [] for node in ind: sta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_pipeline_code(pipeline_tree, operators): """Generate code specific to the construction of the sklearn Pipeline. Parameters pipeline_tree: list List ...
steps = _process_operator(pipeline_tree, operators) pipeline_text = "make_pipeline(\n{STEPS}\n)".format(STEPS=_indent(",\n".join(steps), 4)) return pipeline_text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_export_pipeline_code(pipeline_tree, operators): """Generate code specific to the construction of the sklearn Pipeline for export_pipeline. Parameter...
steps = _process_operator(pipeline_tree, operators) # number of steps in a pipeline num_step = len(steps) if num_step > 1: pipeline_text = "make_pipeline(\n{STEPS}\n)".format(STEPS=_indent(",\n".join(steps), 4)) # only one operator (root = True) else: pipeline_text = "{STEPS}".f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _indent(text, amount): """Indent a multiline string by some number of spaces. Parameters text: str The text to be indented amount: int The number of spaces t...
indentation = amount * ' ' return indentation + ('\n' + indentation).join(text.split('\n'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """Get the next value in the page."""
item = six.next(self._item_iter) result = self._item_to_value(self._parent, item) # Since we've successfully got the next value from the # iterator, we update the number of remaining. self._remaining -= 1 return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _verify_params(self): """Verifies the parameters don't use any reserved parameter. Raises: ValueError: If a reserved parameter is used. """
reserved_in_use = self._RESERVED_PARAMS.intersection(self.extra_params) if reserved_in_use: raise ValueError("Using a reserved parameter", reserved_in_use)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_query_params(self): """Getter for query parameters for the next request. Returns: dict: A dictionary of query parameters. """
result = {} if self.next_page_token is not None: result[self._PAGE_TOKEN] = self.next_page_token if self.max_results is not None: result[self._MAX_RESULTS] = self.max_results - self.num_results result.update(self.extra_params) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _has_next_page(self): """Determines whether or not there are more pages with results. Returns: bool: Whether the iterator has more pages. """
if self.page_number == 0: return True if self.max_results is not None: if self.num_results >= self.max_results: return False # Note: intentionally a falsy check instead of a None check. The RPC # can return an empty string indicating no more pag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(cls, left, right): """ Main comparison function for all Firestore types. @return -1 is left < right, 0 if left == right, otherwise 1 """
# First compare the types. leftType = TypeOrder.from_value(left).value rightType = TypeOrder.from_value(right).value if leftType != rightType: if leftType < rightType: return -1 return 1 value_type = left.WhichOneof("value_type") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_batch_annotate_images( self, requests, output_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, me...
# Wrap the transport method to add retry and timeout logic. if "async_batch_annotate_images" not in self._inner_api_calls: self._inner_api_calls[ "async_batch_annotate_images" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.async_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_ipython_extension(ipython): """Called by IPython when this module is loaded as an IPython extension."""
from google.cloud.bigquery.magics import _cell_magic ipython.register_magic_function( _cell_magic, magic_kind="cell", magic_name="bigquery" )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _request(http, project, method, data, base_url): """Make a request over the Http transport to the Cloud Datastore API. :type http: :class:`requests.Session` ...
headers = { "Content-Type": "application/x-protobuf", "User-Agent": connection_module.DEFAULT_USER_AGENT, connection_module.CLIENT_INFO_HEADER: _CLIENT_INFO, } api_url = build_api_url(project, method, base_url) response = http.request(url=api_url, method="POST", headers=headers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rpc(http, project, method, base_url, request_pb, response_pb_cls): """Make a protobuf RPC request. :type http: :class:`requests.Session` :param http: HTTP o...
req_data = request_pb.SerializeToString() response = _request(http, project, method, req_data, base_url) return response_pb_cls.FromString(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_api_url(project, method, base_url): """Construct the URL for a particular API call. This method is used internally to come up with the URL to use when ...
return API_URL_TEMPLATE.format( api_base=base_url, api_version=API_VERSION, project=project, method=method )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup(self, project_id, keys, read_options=None): """Perform a ``lookup`` request. :type project_id: str :param project_id: The project to connect to. This ...
request_pb = _datastore_pb2.LookupRequest( project_id=project_id, read_options=read_options, keys=keys ) return _rpc( self.client._http, project_id, "lookup", self.client._base_url, request_pb, _datastore_pb2.Lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_query( self, project_id, partition_id, read_options=None, query=None, gql_query=None ): """Perform a ``runQuery`` request. :type project_id: str :param p...
request_pb = _datastore_pb2.RunQueryRequest( project_id=project_id, partition_id=partition_id, read_options=read_options, query=query, gql_query=gql_query, ) return _rpc( self.client._http, project_id, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def begin_transaction(self, project_id, transaction_options=None): """Perform a ``beginTransaction`` request. :type project_id: str :param project_id: The projec...
request_pb = _datastore_pb2.BeginTransactionRequest() return _rpc( self.client._http, project_id, "beginTransaction", self.client._base_url, request_pb, _datastore_pb2.BeginTransactionResponse, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit(self, project_id, mode, mutations, transaction=None): """Perform a ``commit`` request. :type project_id: str :param project_id: The project to connect...
request_pb = _datastore_pb2.CommitRequest( project_id=project_id, mode=mode, transaction=transaction, mutations=mutations, ) return _rpc( self.client._http, project_id, "commit", self.client._base_ur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollback(self, project_id, transaction): """Perform a ``rollback`` request. :type project_id: str :param project_id: The project to connect to. This is usual...
request_pb = _datastore_pb2.RollbackRequest( project_id=project_id, transaction=transaction ) # Response is empty (i.e. no fields) but we return it anyway. return _rpc( self.client._http, project_id, "rollback", self.client._ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allocate_ids(self, project_id, keys): """Perform an ``allocateIds`` request. :type project_id: str :param project_id: The project to connect to. This is usua...
request_pb = _datastore_pb2.AllocateIdsRequest(keys=keys) return _rpc( self.client._http, project_id, "allocateIds", self.client._base_url, request_pb, _datastore_pb2.AllocateIdsResponse, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_row_request( table_name, start_key=None, end_key=None, filter_=None, limit=None, end_inclusive=False, app_profile_id=None, row_set=None, ): """Create...
request_kwargs = {"table_name": table_name} if (start_key is not None or end_key is not None) and row_set is not None: raise ValueError("Row range and row set cannot be " "set simultaneously") if filter_ is not None: request_kwargs["filter"] = filter_.to_pb() if limit is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mutate_rows_request(table_name, rows, app_profile_id=None): """Creates a request to mutate rows in a table. :type table_name: str :param table_name: The nam...
request_pb = data_messages_v2_pb2.MutateRowsRequest( table_name=table_name, app_profile_id=app_profile_id ) mutations_count = 0 for row in rows: _check_row_table_name(table_name, row) _check_row_type(row) mutations = row._get_mutations() request_pb.entries.add(ro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_row_table_name(table_name, row): """Checks that a row belongs to a table. :type table_name: str :param table_name: The name of the table. :type row: :...
if row.table is not None and row.table.name != table_name: raise TableMismatchError( "Row %s is a part of %s table. Current table: %s" % (row.row_key, row.table.name, table_name) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """Table name used in requests. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_table_name] :end-before: [END bi...
project = self._instance._client.project instance_id = self._instance.instance_id table_client = self._instance._client.table_data_client return table_client.table_path( project=project, instance=instance_id, table=self.table_id )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def row(self, row_key, filter_=None, append=False): """Factory to create a row associated with this table. For example: .. literalinclude:: snippets_table.py :st...
if append and filter_ is not None: raise ValueError("At most one of filter_ and append can be set") if append: return AppendRow(row_key, self) elif filter_ is not None: return ConditionalRow(row_key, self, filter_=filter_) else: return Dir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, initial_split_keys=[], column_families={}): """Creates this table. For example: .. literalinclude:: snippets_table.py :start-after: [START bigta...
table_client = self._instance._client.table_admin_client instance_name = self._instance.name families = { id: ColumnFamily(id, self, rule).to_pb() for (id, rule) in column_families.items() } table = admin_messages_v2_pb2.Table(column_families=families) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists(self): """Check whether the table exists. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_check_table_exists] :end-be...
table_client = self._instance._client.table_admin_client try: table_client.get_table(name=self.name, view=VIEW_NAME_ONLY) return True except NotFound: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """Delete this table. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_delete_table] :end-before: [END bigtable...
table_client = self._instance._client.table_admin_client table_client.delete_table(name=self.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_column_families(self): """List the column families owned by this table. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable...
table_client = self._instance._client.table_admin_client table_pb = table_client.get_table(self.name) result = {} for column_family_id, value_pb in table_pb.column_families.items(): gc_rule = _gc_rule_from_pb(value_pb.gc_rule) column_family = self.column_family(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cluster_states(self): """List the cluster states owned by this table. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_ge...
REPLICATION_VIEW = enums.Table.View.REPLICATION_VIEW table_client = self._instance._client.table_admin_client table_pb = table_client.get_table(self.name, view=REPLICATION_VIEW) return { cluster_id: ClusterState(value_pb.replication_state) for cluster_id, value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_row(self, row_key, filter_=None): """Read a single row from this table. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable...
row_set = RowSet() row_set.add_row_key(row_key) result_iter = iter(self.read_rows(filter_=filter_, row_set=row_set)) row = next(result_iter, None) if next(result_iter, None) is not None: raise ValueError("More than one row was returned.") return row
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutate_rows(self, rows, retry=DEFAULT_RETRY): """Mutates multiple rows in bulk. For example: .. literalinclude:: snippets_table.py :start-after: [START bigta...
retryable_mutate_rows = _RetryableMutateRowsWorker( self._instance._client, self.name, rows, app_profile_id=self._app_profile_id, timeout=self.mutation_timeout, ) return retryable_mutate_rows(retry=retry)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_row_keys(self): """Read a sample of row keys in the table. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_sample_row...
data_client = self._instance._client.table_data_client response_iterator = data_client.sample_row_keys( self.name, app_profile_id=self._app_profile_id ) return response_iterator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate(self, timeout=None): """Truncate the table For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_truncate_table] :end-bef...
client = self._instance._client table_admin_client = client.table_admin_client if timeout: table_admin_client.drop_row_range( self.name, delete_all_data_from_table=True, timeout=timeout ) else: table_admin_client.drop_row_range( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutations_batcher(self, flush_count=FLUSH_COUNT, max_row_bytes=MAX_ROW_BYTES): """Factory to create a mutation batcher associated with this instance. For exa...
return MutationsBatcher(self, flush_count, max_row_bytes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_mutate_retryable_rows(self): """Mutate all the rows that are eligible for retry. A row is eligible for retry if it has not been tried or if it resulted i...
retryable_rows = [] index_into_all_rows = [] for index, status in enumerate(self.responses_statuses): if self._is_retryable(status): retryable_rows.append(self.rows[index]) index_into_all_rows.append(index) if not retryable_rows: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def heartbeat(self): """Periodically send heartbeats."""
while self._manager.is_active and not self._stop_event.is_set(): self._manager.heartbeat() _LOGGER.debug("Sent heartbeat.") self._stop_event.wait(timeout=self._period) _LOGGER.info("%s exiting.", _HEARTBEAT_WORKER_NAME)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report_error_event( self, project_name, event, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ...
# Wrap the transport method to add retry and timeout logic. if "report_error_event" not in self._inner_api_calls: self._inner_api_calls[ "report_error_event" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.report_error_event, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scalar_to_query_parameter(value, name=None): """Convert a scalar value into a query parameter. :type value: any :param value: A scalar value to convert into ...
parameter_type = None if isinstance(value, bool): parameter_type = "BOOL" elif isinstance(value, numbers.Integral): parameter_type = "INT64" elif isinstance(value, numbers.Real): parameter_type = "FLOAT64" elif isinstance(value, decimal.Decimal): parameter_type = "N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_query_parameters_dict(parameters): """Converts a dictionary of parameter values into query parameters. :type parameters: Mapping[str, Any] :param paramete...
return [ scalar_to_query_parameter(value, name=name) for name, value in six.iteritems(parameters) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_query_parameters(parameters): """Converts DB-API parameter values into query parameters. :type parameters: Mapping[str, Any] or Sequence[Any] :param param...
if parameters is None: return [] if isinstance(parameters, collections_abc.Mapping): return to_query_parameters_dict(parameters) return to_query_parameters_list(parameters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _refresh_grpc(operations_stub, operation_name): """Refresh an operation using a gRPC client. Args: operations_stub (google.longrunning.operations_pb2.Operati...
request_pb = operations_pb2.GetOperationRequest(name=operation_name) return operations_stub.GetOperation(request_pb)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cancel_grpc(operations_stub, operation_name): """Cancel an operation using a gRPC client. Args: operations_stub (google.longrunning.operations_pb2.Operation...
request_pb = operations_pb2.CancelOperationRequest(name=operation_name) operations_stub.CancelOperation(request_pb)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_grpc(operation, operations_stub, result_type, **kwargs): """Create an operation future using a gRPC client. This interacts with the long-running operati...
refresh = functools.partial(_refresh_grpc, operations_stub, operation.name) cancel = functools.partial(_cancel_grpc, operations_stub, operation.name) return Operation(operation, refresh, cancel, result_type, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_gapic(operation, operations_client, result_type, **kwargs): """Create an operation future from a gapic client. This interacts with the long-running oper...
refresh = functools.partial(operations_client.get_operation, operation.name) cancel = functools.partial(operations_client.cancel_operation, operation.name) return Operation(operation, refresh, cancel, result_type, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_result_from_operation(self): """Set the result or exception from the operation if it is complete."""
# This must be done in a lock to prevent the polling thread # and main thread from both executing the completion logic # at the same time. with self._completion_lock: # If the operation isn't complete or if the result has already been # set, do not call set_resul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _refresh_and_update(self): """Refresh the operation and update the result if needed."""
# If the currently cached operation is done, no need to make another # RPC as it will not change once done. if not self._operation.done: self._operation = self._refresh() self._set_result_from_operation()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancelled(self): """True if the operation was cancelled."""
self._refresh_and_update() return ( self._operation.HasField("error") and self._operation.error.code == code_pb2.CANCELLED )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revoke(self, role): """Remove a role from the entity. :type role: str :param role: The role to remove from the entity. """
if role in self.roles: self.roles.remove(role)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_predefined(cls, predefined): """Ensures predefined is in list of predefined json values :type predefined: str :param predefined: name of a predefine...
predefined = cls.PREDEFINED_XML_ACLS.get(predefined, predefined) if predefined and predefined not in cls.PREDEFINED_JSON_ACLS: raise ValueError("Invalid predefined ACL: %s" % (predefined,)) return predefined
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entity_from_dict(self, entity_dict): """Build an _ACLEntity object from a dictionary of data. An entity is a mutable object that represents a list of roles b...
entity = entity_dict["entity"] role = entity_dict["role"] if entity == "allUsers": entity = self.all() elif entity == "allAuthenticatedUsers": entity = self.all_authenticated() elif "-" in entity: entity_type, identifier = entity.split("-",...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_entity(self, entity, default=None): """Gets an entity object from the ACL. :type entity: :class:`_ACLEntity` or string :param entity: The entity to get l...
self._ensure_loaded() return self.entities.get(str(entity), default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_entity(self, entity): """Add an entity to the ACL. :type entity: :class:`_ACLEntity` :param entity: The entity to add to this ACL. """
self._ensure_loaded() self.entities[str(entity)] = entity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entity(self, entity_type, identifier=None): """Factory method for creating an Entity. If an entity with the same type and identifier already exists, this wil...
entity = _ACLEntity(entity_type=entity_type, identifier=identifier) if self.has_entity(entity): entity = self.get_entity(entity) else: self.add_entity(entity) return entity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload(self, client=None): """Reload the ACL data from Cloud Storage. If :attr:`user_project` is set, bills the API request to that project. :type client: :c...
path = self.reload_path client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project self.entities.clear() found = client._connection.api_request( method="GET", path=p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, acl=None, client=None): """Save this ACL for the current bucket. If :attr:`user_project` is set, bills the API request to that project. :type acl:...
if acl is None: acl = self save_to_backend = acl.loaded else: save_to_backend = True if save_to_backend: self._save(acl, None, client)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_predefined(self, predefined, client=None): """Save this ACL for the current bucket using a predefined ACL. If :attr:`user_project` is set, bills the API...
predefined = self.validate_predefined(predefined) self._save(None, predefined, client)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def incident_path(cls, project, incident): """Return a fully-qualified incident string."""
return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}", project=project, incident=incident, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotation_path(cls, project, incident, annotation): """Return a fully-qualified annotation string."""
return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/annotations/{annotation}", project=project, incident=incident, annotation=annotation, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def artifact_path(cls, project, incident, artifact): """Return a fully-qualified artifact string."""
return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/artifacts/{artifact}", project=project, incident=incident, artifact=artifact, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def role_assignment_path(cls, project, incident, role_assignment): """Return a fully-qualified role_assignment string."""
return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/roleAssignments/{role_assignment}", project=project, incident=incident, role_assignment=role_assignment, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscription_path(cls, project, incident, subscription): """Return a fully-qualified subscription string."""
return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/subscriptions/{subscription}", project=project, incident=incident, subscription=subscription, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag_path(cls, project, incident, tag): """Return a fully-qualified tag string."""
return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/tags/{tag}", project=project, incident=incident, tag=tag, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signal_path(cls, project, signal): """Return a fully-qualified signal string."""
return google.api_core.path_template.expand( "projects/{project}/signals/{signal}", project=project, signal=signal )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escalate_incident( self, incident, update_mask=None, subscriptions=None, tags=None, roles=None, artifacts=None, retry=google.api_core.gapic_v1.method.DEFAULT,...
# Wrap the transport method to add retry and timeout logic. if "escalate_incident" not in self._inner_api_calls: self._inner_api_calls[ "escalate_incident" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.escalate_incident, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_shift_handoff( self, parent, recipients, subject, cc=None, notes_content_type=None, notes_content=None, incidents=None, preview_only=None, retry=google.a...
# Wrap the transport method to add retry and timeout logic. if "send_shift_handoff" not in self._inner_api_calls: self._inner_api_calls[ "send_shift_handoff" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.send_shift_handoff, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bigtable_admins(self): """Access to bigtable.admin role memebers For example: .. literalinclude:: snippets.py :start-after: [START bigtable_admins_policy] :e...
result = set() for member in self._bindings.get(BIGTABLE_ADMIN_ROLE, ()): result.add(member) return frozenset(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bigtable_readers(self): """Access to bigtable.reader role memebers For example: .. literalinclude:: snippets.py :start-after: [START bigtable_readers_policy]...
result = set() for member in self._bindings.get(BIGTABLE_READER_ROLE, ()): result.add(member) return frozenset(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bigtable_users(self): """Access to bigtable.user role memebers For example: .. literalinclude:: snippets.py :start-after: [START bigtable_users_policy] :end-...
result = set() for member in self._bindings.get(BIGTABLE_USER_ROLE, ()): result.add(member) return frozenset(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bigtable_viewers(self): """Access to bigtable.viewer role memebers For example: .. literalinclude:: snippets.py :start-after: [START bigtable_viewers_policy]...
result = set() for member in self._bindings.get(BIGTABLE_VIEWER_ROLE, ()): result.add(member) return frozenset(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pb(self): """Render a protobuf message. Returns: google.iam.policy_pb2.Policy: a message to be passed to the ``set_iam_policy`` gRPC API. """
return policy_pb2.Policy( etag=self.etag, version=self.version or 0, bindings=[ policy_pb2.Binding(role=role, members=sorted(self[role])) for role in self ], )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_ddl_statements(value): """Validate DDL Statements used to define database schema. See https://cloud.google.com/spanner/docs/data-definition-language :...
if not all(isinstance(line, six.string_types) for line in value): raise ValueError("Pass a list of strings") if any("create database" in line.lower() for line in value): raise ValueError("Do not pass a 'CREATE DATABASE' statement") return tuple(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_pb(cls, database_pb, instance, pool=None): """Creates an instance of this class from a protobuf. :type database_pb: :class:`google.spanner.v2.spanner_in...
match = _DATABASE_NAME_RE.match(database_pb.name) if match is None: raise ValueError( "Database protobuf name was not in the " "expected format.", database_pb.name, ) if match.group("project") != instance._client.project: raise...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self): """Create this database within its instance Inclues any configured schema assigned to :attr:`ddl_statements`. See https://cloud.google.com/span...
api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) db_name = self.database_id if "-" in db_name: db_name = "`%s`" % (db_name,) future = api.create_database( parent=self._instance.name, create_statement...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists(self): """Test whether this database exists. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin....
api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) try: api.get_database_ddl(self.name, metadata=metadata) except NotFound: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload(self): """Reload this database. Refresh any configured schema into :attr:`ddl_statements`. See https://cloud.google.com/spanner/reference/rpc/google.s...
api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) response = api.get_database_ddl(self.name, metadata=metadata) self._ddl_statements = tuple(response.statements)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_ddl(self, ddl_statements, operation_id=""): """Update DDL for this database. Apply any configured schema from :attr:`ddl_statements`. See https://clou...
client = self._instance._client api = client.database_admin_api metadata = _metadata_with_prefix(self.name) future = api.update_database_ddl( self.name, ddl_statements, operation_id=operation_id, metadata=metadata ) return future
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop(self): """Drop this database. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.Datab...
api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) api.drop_database(self.name, metadata=metadata)