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 reload(self): """Reload the metadata for this cluster"""
app_profile_pb = self.instance_admin_client.get_app_profile(self.name) # NOTE: _update_from_pb does not check that the project and # app_profile ID on the response match the request. self._update_from_pb(app_profile_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 exists(self): """Check whether the AppProfile already exists. :rtype: bool :returns: True if the AppProfile exists, else False. """
try: self.instance_admin_client.get_app_profile(self.name) return True # NOTE: There could be other exceptions that are returned to the user. 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 create(self, ignore_warnings=None): """Create this AppProfile. .. note:: Uses the ``instance`` and ``app_profile_id`` on the current :class:`AppProfile` in a...
return self.from_pb( self.instance_admin_client.create_app_profile( parent=self._instance.name, app_profile_id=self.app_profile_id, app_profile=self._to_pb(), ignore_warnings=ignore_warnings, ), self._instance, ...
<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(self, ignore_warnings=None): """Update this app_profile. .. note:: Update any or all of the following values: ``routing_policy_type`` ``description`` ...
update_mask_pb = field_mask_pb2.FieldMask() if self.description is not None: update_mask_pb.paths.append("description") if self.routing_policy_type == RoutingPolicyType.ANY: update_mask_pb.paths.append("multi_cluster_routing_use_any") else: update_m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sink_path(cls, project, sink): """Return a fully-qualified sink string."""
return google.api_core.path_template.expand( "projects/{project}/sinks/{sink}", project=project, sink=sink )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exclusion_path(cls, project, exclusion): """Return a fully-qualified exclusion string."""
return google.api_core.path_template.expand( "projects/{project}/exclusions/{exclusion}", project=project, exclusion=exclusion, )
<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_sink( self, parent, sink, unique_writer_identity=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ...
# Wrap the transport method to add retry and timeout logic. if "create_sink" not in self._inner_api_calls: self._inner_api_calls[ "create_sink" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_sink, default_re...
<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_exclusion( self, parent, exclusion, 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 "create_exclusion" not in self._inner_api_calls: self._inner_api_calls[ "create_exclusion" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_exclusion, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_value_pb(value_pb, field_type): """Convert a Value protobuf to cell data. :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: ...
if value_pb.HasField("null_value"): return None if field_type.code == type_pb2.STRING: result = value_pb.string_value elif field_type.code == type_pb2.BYTES: result = value_pb.string_value.encode("utf8") elif field_type.code == type_pb2.BOOL: result = value_pb.bool_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 _parse_list_value_pbs(rows, row_type): """Convert a list of ListValue protobufs into a list of list of cell data. :type rows: list of :class:`~google.protobu...
result = [] for row in rows: row_data = [] for value_pb, field in zip(row.values, row_type.fields): row_data.append(_parse_value_pb(value_pb, field.type)) result.append(row_data) 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 export_assets( self, parent, output_config, read_time=None, asset_types=None, content_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google...
# Wrap the transport method to add retry and timeout logic. if "export_assets" not in self._inner_api_calls: self._inner_api_calls[ "export_assets" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_assets, defa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_get_assets_history( self, parent, content_type, read_time_window, asset_names=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_co...
# Wrap the transport method to add retry and timeout logic. if "batch_get_assets_history" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_assets_history" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_ass...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _avro_schema(read_session): """Extract and parse Avro schema from a read session. Args: read_session ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadSes...
json_schema = json.loads(read_session.avro_schema.schema) column_names = tuple((field["name"] for field in json_schema["fields"])) return fastavro.parse_schema(json_schema), column_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _avro_rows(block, avro_schema): """Parse all rows in a stream block. Args: block ( \ ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \ ): A bl...
blockio = six.BytesIO(block.avro_rows.serialized_binary_rows) while True: # Loop in a while loop because schemaless_reader can only read # a single record. try: # TODO: Parse DATETIME into datetime.datetime (no timezone), # instead of as a string. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_stream_position(position): """Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]):...
if isinstance(position, types.StreamPosition): output = types.StreamPosition() output.CopyFrom(position) return output return types.StreamPosition(**position)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reconnect(self): """Reconnect to the ReadRows stream using the most recent offset."""
self._wrapped = self._client.read_rows( _copy_stream_position(self._position), **self._read_rows_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 pages(self): """A generator of all pages in the stream. Returns: types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]: A generator of page...
# Each page is an iterator of rows. But also has num_items, remaining, # and to_dataframe. avro_schema, column_names = _avro_schema(self._read_session) for block in self._reader: self._status = block.status yield ReadRowsPage(avro_schema, column_names, block)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_block(self): """Parse metadata and rows from the block only once."""
if self._iter_rows is not None: return rows = _avro_rows(self._block, self._avro_schema) self._num_items = self._block.avro_rows.row_count self._remaining = self._block.avro_rows.row_count self._iter_rows = iter(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 next(self): """Get the next row in the page."""
self._parse_block() if self._remaining > 0: self._remaining -= 1 return six.next(self._iter_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 instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string."""
return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, )
<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_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata...
# Wrap the transport method to add retry and timeout logic. if "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, ...
<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_instance( self, instance, field_mask, 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 "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_config_path(cls, project, scan_config): """Return a fully-qualified scan_config string."""
return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}", project=project, scan_config=scan_config, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_run_path(cls, project, scan_config, scan_run): """Return a fully-qualified scan_run string."""
return google.api_core.path_template.expand( "projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}", project=project, scan_config=scan_config, scan_run=scan_run, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Make a copy of this client. Copies the local data stored as simple types but does not copy the current state of any open connections with the ...
return self.__class__( project=self.project, credentials=self._credentials, user_agent=self.user_agent, )
<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_instance_configs(self, page_size=None, page_token=None): """List available instance configurations for the client's project. .. _RPC docs: https://cloud...
metadata = _metadata_with_prefix(self.project_name) path = "projects/%s" % (self.project,) page_iter = self.instance_admin_api.list_instance_configs( path, page_size=page_size, metadata=metadata ) page_iter.next_page_token = page_token page_iter.item_to_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 list_instances(self, filter_="", page_size=None, page_token=None): """List instances for the client's project. See https://cloud.google.com/spanner/reference...
metadata = _metadata_with_prefix(self.project_name) path = "projects/%s" % (self.project,) page_iter = self.instance_admin_api.list_instances( path, page_size=page_size, metadata=metadata ) page_iter.item_to_value = self._item_to_instance page_iter.next_page_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _should_retry(exc): """Predicate for determining when to retry. We retry if and only if the 'reason' is 'backendError' or 'rateLimitExceeded'. """
if not hasattr(exc, "errors"): return False if len(exc.errors) == 0: # Check for unstructured error returns, e.g. from GFE return isinstance(exc, _UNSTRUCTURED_RETRYABLE_TYPES) reason = exc.errors[0]["reason"] return reason in _RETRYABLE_REASONS
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entry_from_resource(resource, client, loggers): """Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry r...
if "textPayload" in resource: return TextEntry.from_api_repr(resource, client, loggers) if "jsonPayload" in resource: return StructEntry.from_api_repr(resource, client, loggers) if "protoPayload" in resource: return ProtobufEntry.from_api_repr(resource, client, loggers) retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_metadata_server(metadata_key): """Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-me...
url = METADATA_URL + metadata_key try: response = requests.get(url, headers=METADATA_HEADERS) if response.status_code == requests.codes.ok: return response.text except requests.exceptions.RequestException: # Ignore the exception, connection failed means the attribute ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_eval(*args, **kwargs): """ Wrapper around deprecated function. """
# Inside function to avoid circular import from cleverhans.evaluation import batch_eval as new_batch_eval warnings.warn("batch_eval has moved to cleverhans.evaluation. " "batch_eval will be removed from utils_tf on or after " "2019-03-09.") return new_batch_eval(*args, **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 get_available_gpus(): """ Returns a list of string names of all available GPUs """
local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip_by_value(t, clip_value_min, clip_value_max, name=None): """ A wrapper for clip_by_value that casts the clipping range if needed. """
def cast_clip(clip): """ Cast clipping range argument if needed. """ if t.dtype in (tf.float32, tf.float64): if hasattr(clip, 'dtype'): # Convert to tf dtype in case this is a numpy dtype clip_dtype = tf.as_dtype(clip.dtype) if clip_dtype != t.dtype: return tf....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mul(a, b): """ A wrapper around tf multiplication that does more automatic casting of the input. """
def multiply(a, b): """Multiplication""" return a * b return op_with_scalar_cast(a, b, multiply)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def div(a, b): """ A wrapper around tf division that does more automatic casting of the input. """
def divide(a, b): """Division""" return a / b return op_with_scalar_cast(a, b, divide)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_single_batch_images_internal(self, batch_id, client_batch): """Helper method to write images from single batch into datastore."""
client = self._datastore_client batch_key = client.key(self._entity_kind_batches, batch_id) for img_id, img in iteritems(self._data[batch_id]['images']): img_entity = client.entity( client.key(self._entity_kind_images, img_id, parent=batch_key)) for k, v in iteritems(img): img...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_to_datastore(self): """Writes all image batches to the datastore."""
client = self._datastore_client with client.no_transact_batch() as client_batch: for batch_id, batch_data in iteritems(self._data): batch_key = client.key(self._entity_kind_batches, batch_id) batch_entity = client.entity(batch_key) for k, v in iteritems(batch_data): if k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_single_batch_images_to_datastore(self, batch_id): """Writes only images from one batch to the datastore."""
client = self._datastore_client with client.no_transact_batch() as client_batch: self._write_single_batch_images_internal(batch_id, client_batch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_from_datastore(self): """Initializes batches by reading from the datastore."""
self._data = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_batches): batch_id = entity.key.flat_path[-1] self._data[batch_id] = dict(entity) self._data[batch_id]['images'] = {} for entity in self._datastore_client.query_fetch( kind=self._entit...
<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_batch(self, batch_id, batch_properties=None): """Adds batch with give ID and list of properties."""
if batch_properties is None: batch_properties = {} if not isinstance(batch_properties, dict): raise ValueError('batch_properties has to be dict, however it was: ' + str(type(batch_properties))) self._data[batch_id] = batch_properties.copy() self._data[batch_id]['image...
<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_image(self, batch_id, image_id, image_properties=None): """Adds image to given batch."""
if batch_id not in self._data: raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id)) if image_properties is None: image_properties = {} if not isinstance(image_properties, dict): raise ValueError('image_properties has to be dict, however it was: ' + ...
<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_image_list(self, skip_image_ids=None): """Reads list of dataset images from the datastore."""
if skip_image_ids is None: skip_image_ids = [] images = self._storage_client.list_blobs( prefix=os.path.join('dataset', self._dataset_name) + '/') zip_files = [i for i in images if i.endswith('.zip')] if len(zip_files) == 1: # we have a zip archive with images zip_name = zip_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 init_from_storage_write_to_datastore(self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None): """Initializes dataset batches fr...
if allowed_epsilon is None: allowed_epsilon = copy.copy(DEFAULT_EPSILON) # init dataset batches from data in storage self._dataset_batches = {} # read all blob names from storage images = self._read_image_list(skip_image_ids) if max_num_images: images = images[:max_num_images] 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 init_from_dataset_and_submissions_write_to_datastore( self, dataset_batches, attack_submission_ids): """Init list of adversarial batches from dataset batches...
batches_x_attacks = itertools.product(dataset_batches.data.keys(), attack_submission_ids) for idx, (dataset_batch_id, attack_id) in enumerate(batches_x_attacks): adv_batch_id = ADVERSARIAL_BATCH_ID_PATTERN.format(idx) self.add_batch(adv_batch_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 count_generated_adv_examples(self): """Returns total number of all generated adversarial examples."""
result = {} for v in itervalues(self.data): s_id = v['submission_id'] result[s_id] = result.get(s_id, 0) + len(v['images']) 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 create_logger(name): """ Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter. """
base = logging.getLogger("cleverhans") if len(base.handlers) == 0: ch = logging.StreamHandler() formatter = logging.Formatter('[%(levelname)s %(asctime)s %(name)s] ' + '%(message)s') ch.setFormatter(formatter) base.addHandler(ch) return base
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deterministic_dict(normal_dict): """ Returns a version of `normal_dict` whose iteration order is always the same """
out = OrderedDict() for key in sorted(normal_dict.keys()): out[key] = normal_dict[key] return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell_call(command, **kwargs): """Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is o...
# Regular expression to find instances of '${NAME}' in a string CMD_VARIABLE_RE = re.compile('^\\$\\{(\\w+)\\}$') command = list(command) for i in range(len(command)): m = CMD_VARIABLE_RE.match(command[i]) if m: var_id = m.group(1) if var_id in kwargs: command[i] = kwargs[var_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 deep_copy(numpy_dict): """ Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them. """
out = {} for key in numpy_dict: out[key] = numpy_dict[key].copy() return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET,...
# Set TF random seed to improve reproducibility tf.set_random_seed(20181014) set_log_level(logging.INFO) sess = tf.Session() with sess.as_default(): model = load(filepath) assert len(model.get_params()) > 0 factory = model.dataset_factory factory.kwargs['train_start'] = train_start factory.kwar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs): """ Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, ha...
assert len(inputs) == len(outputs), ( 'Inputs and outputs should have the same number of elements.') inputs[0].update(g0_inputs) outputs[0].update(g0_inputs) # Copy g0_inputs forward for i in range(1, len(inputs)): # Create the graph for i'th step of attack device_name = input...
<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_device(self, device_name): """ Set the device before the next fprop to create a new graph on the specified device. """
device_name = unify_device_name(device_name) self.device_name = device_name for layer in self.layers: layer.device_name = device_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 set_input_shape_ngpu(self, new_input_shape): """ Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_sh...
assert self.device_name, "Device name has not been set." device_name = self.device_name if self.input_shape is None: # First time setting the input shape self.input_shape = [None] + [int(d) for d in list(new_input_shape)] if device_name in self.params_device: # There is a copy of we...
<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_sync_ops(self, host_device): """Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `ho...
sync_ops = [] host_params = self.params_device[host_device] for device, params in (self.params_device).iteritems(): if device == host_device: continue for k in self.params_names: if isinstance(params[k], tf.Variable): sync_ops += [tf.assign(params[k], host_params[k])] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterate_with_exp_backoff(base_iter, max_num_tries=6, max_backoff=300.0, start_backoff=4.0, backoff_multiplier=2.0, frac_random_backoff=0.25): """Iterate with...
try_number = 0 if hasattr(base_iter, '__iter__'): base_iter = iter(base_iter) while True: try: yield next(base_iter) try_number = 0 except StopIteration: break except TooManyRequests as e: logging.warning('TooManyRequests error: %s', tb.format_exc()) if try_number >=...
<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_blobs(self, prefix=''): """Lists names of all blobs by their prefix."""
return [b.name for b in self.bucket.list_blobs(prefix=prefix)]
<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): """Rolls back pending mutations. Keep in mind that NoTransactionBatch splits all mutations into smaller batches and commit them as soon as mu...
try: if self._cur_batch: self._cur_batch.rollback() except ValueError: # ignore "Batch must be in progress to rollback" error pass self._cur_batch = None self._num_mutations = 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 put(self, entity): """Adds mutation of the entity to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutatio...
self._cur_batch.put(entity) self._num_mutations += 1 if self._num_mutations >= MAX_MUTATIONS_IN_BATCH: self.commit() self.begin()
<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, key): """Adds deletion of the entity with given key to the mutation buffer. If mutation buffer reaches its capacity then this method commit all ...
self._cur_batch.delete(key) self._num_mutations += 1 if self._num_mutations >= MAX_MUTATIONS_IN_BATCH: self.commit() self.begin()
<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(self, key, transaction=None): """Retrieves an entity given its key."""
return self._client.get(key, transaction=transaction)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sudo_remove_dirtree(dir_name): """Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to clean...
try: subprocess.check_output(['sudo', 'rm', '-rf', dir_name]) except subprocess.CalledProcessError as e: raise WorkerError('Can''t remove directory {0}'.format(dir_name), 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 main(args): """Main function which runs worker."""
title = '## Starting evaluation of round {0} ##'.format(args.round_name) logging.info('\n' + '#' * len(title) + '\n' + '#' * len(title) + '\n' + '##' + ' ' * (len(title)-2) + '##' + '\n' + title + '\n' + '#' * len(title) + '\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 temp_copy_extracted_submission(self): """Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory....
tmp_copy_dir = os.path.join(self.submission_dir, 'tmp_copy') shell_call(['cp', '-R', os.path.join(self.extracted_submission_dir), tmp_copy_dir]) return tmp_copy_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 run_without_time_limit(self, cmd): """Runs docker command without time limit. Args: cmd: list with the command line arguments which are passed to docker bina...
cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd logging.info('Docker command: %s', ' '.join(cmd)) start_time = time.time() retval = subprocess.call(cmd) elapsed_time_sec = int(time.time() - start_time) logging.info('Elapsed time of attack: %d', elapsed_time_sec) logging.info('Dock...
<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_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT): """Runs docker command and enforces time limit. Args: cmd: list with the command line argum...
if time_limit < 0: return self.run_without_time_limit(cmd) container_name = str(uuid.uuid4()) cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME, '--detach', '--name', container_name] + cmd logging.info('Docker command: %s', ' '.join(cmd)) logging.info('Time limit %d seconds', time...
<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(self, input_dir, output_file_path): """Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of ...
logging.info('Running defense %s', self.submission_id) tmp_run_dir = self.temp_copy_extracted_submission() output_dir = os.path.dirname(output_file_path) output_filename = os.path.basename(output_file_path) cmd = ['--network=none', '-m=24g', '--cpus=3.75', '-v', '{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 read_dataset_metadata(self): """Read `dataset_meta` field from bucket"""
if self.dataset_meta: return shell_call(['gsutil', 'cp', 'gs://' + self.storage_client.bucket_name + '/' + 'dataset/' + self.dataset_name + '_dataset.csv', LOCAL_DATASET_METADATA_FILE]) with open(LOCAL_DATASET_METADATA_FILE, 'r') as f: self.datase...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_attacks_data(self): """Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, ...
if self.attacks_data_initialized: return # init data from datastore self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() # copy dataset locally if not os.path.exists(LOCAL_DATASET_DIR): os.makedirs(LOCAL_DATASET...
<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_attack_work(self, work_id): """Runs one attack work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed tim...
adv_batch_id = ( self.attack_work.work[work_id]['output_adversarial_batch_id']) adv_batch = self.adv_batches[adv_batch_id] dataset_batch_id = adv_batch['dataset_batch_id'] submission_id = adv_batch['submission_id'] epsilon = self.dataset_batches[dataset_batch_id]['epsilon'] logging.info...
<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_attacks(self): """Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it. """
logging.info('******** Start evaluation of attacks ********') prev_submission_id = None while True: # wait until work is available self.attack_work.read_all_from_datastore() if not self.attack_work.work: logging.info('Work is not populated, waiting...') time.sleep(SLEEP_TI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_defense_data(self): """Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized: return logging.info('Fetching defense data from datastore') # init data from datastore self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() # read dataset metadata self.read_data...
<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_defense_work(self, work_id): """Runs one defense work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed t...
class_batch_id = ( self.defense_work.work[work_id]['output_classification_batch_id']) class_batch = self.class_batches.read_batch_from_datastore(class_batch_id) adversarial_batch_id = class_batch['adversarial_batch_id'] submission_id = class_batch['submission_id'] cloud_result_path = class_...
<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_defenses(self): """Method which evaluates all defense work. In a loop this method queries not completed defense work, picks one defense work and runs it....
logging.info('******** Start evaluation of defenses ********') prev_submission_id = None need_reload_work = True while True: # wait until work is available if need_reload_work: if self.num_defense_shards: shard_with_work = self.defense_work.read_undone_from_datastore( ...
<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_work(self): """Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR): sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR) self.run_attacks() self.run_defenses()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_graph(self, fixed, feedable, x_val, hash_key): """ Construct the graph required to run the attack through generate_np. :param fixed: Structural ele...
# try our very best to create a TF placeholder for each of the # feedable keyword arguments, and check the types are one of # the allowed types class_name = str(self.__class__).split(".")[-1][:-2] _logger.info("Constructing new graph for attack " + class_name) # remove the None arguments, they...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_variables(self, kwargs): """ Construct the inputs to the attack graph to be used by generate_np. :param kwargs: Keyword arguments to generate_np. :...
if isinstance(self.feedable_kwargs, dict): warnings.warn("Using a dict for `feedable_kwargs is deprecated." "Switch to using a tuple." "It is not longer necessary to specify the types " "of the arguments---we build a different graph " ...
<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_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs): """ Creates the symbolic graph of an adversarial example given the name of an att...
# TODO: black box attacks attack_names = {'FGSM': FastGradientMethod, 'MadryEtAl': MadryEtAl, 'MadryEtAl_y': MadryEtAl, 'MadryEtAl_multigpu': MadryEtAlMultiGPU, 'MadryEtAl_y_multigpu': MadryEtAlMultiGPU } if attack_type not...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_value(self, tag, val, desc=''): """ Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy a...
logging.info('%s (%s): %.4f' % (desc, tag, val)) self.summary.value.add(tag=tag, simple_value=val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type): """ Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model....
end = (len(X_test) // self.batch_size) * self.batch_size if self.hparams.fast_tests: end = 10*self.batch_size acc = model_eval(self.sess, x, y, preds_adv, X_test[:end], Y_test[:end], args=self.eval_params) self.log_value('test_accuracy_%s' % att_type, acc, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_multi(self, inc_epoch=True): """ Run the evaluation on multiple attacks. """
sess = self.sess preds = self.preds x = self.x_pre y = self.y X_train = self.X_train Y_train = self.Y_train X_test = self.X_test Y_test = self.Y_test writer = self.writer self.summary = tf.Summary() report = {} # Evaluate on train set subsample_factor = 100 X_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap(f): """ Wraps a callable `f` in a function that warns that the function is deprecated. """
def wrapper(*args, **kwargs): """ Issues a deprecation warning and passes through the arguments. """ warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflow. " " This function was originally needed as a compatibility layer for old versions of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1): """ Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle d...
# Make sure that all arguments were passed as named arguments. if sentinel is not None: name = "softmax_cross_entropy_with_logits" raise ValueError("Only call `%s` with " "named arguments (labels=..., logits=..., ...)" % name) if labels is None or logits is 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 enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir, epsilon): """Enforces size of perturbation on images, and compute hashes for all ima...
dataset_images = [f for f in os.listdir(dataset_batch_dir) if f.endswith('.png')] image_hashes = {} resize_warning = False for img_name in dataset_images: if not os.path.exists(os.path.join(adv_dir, img_name)): logging.warning('Image %s not found in the output', img_name) co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_dataset(storage_client, image_batches, target_dir, local_dataset_copy=None): """Downloads dataset, organize it by batches and rename images. Args: s...
for batch_id, batch_value in iteritems(image_batches.data): batch_dir = os.path.join(target_dir, batch_id) os.mkdir(batch_dir) for image_id, image_val in iteritems(batch_value['images']): dst_filename = os.path.join(batch_dir, image_id + '.png') # try to use local copy first if local_da...
<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_target_classes_for_batch(self, filename, image_batches, batch_id): """Saves file with target class for given dataset batch. Args: filename: output filen...
images = image_batches.data[batch_id]['images'] with open(filename, 'w') as f: for image_id, image_val in iteritems(images): target_class = self.get_target_class(image_val['dataset_image_id']) f.write('{0}.png,{1}\n'.format(image_id, target_class))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tf_min_eig_vec(self): """Function for min eigen vector using tf's full eigen decomposition."""
# Full eigen decomposition requires the explicit psd matrix M _, matrix_m = self.dual_object.get_full_psd_matrix() [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m) index = tf.argmin(eig_vals) return tf.reshape( eig_vectors[:, index], shape=[eig_vectors.shape[0].value, 1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tf_smooth_eig_vec(self): """Function that returns smoothed version of min eigen vector."""
_, matrix_m = self.dual_object.get_full_psd_matrix() # Easier to think in terms of max so negating the matrix [eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m) exp_eig_vals = tf.exp(tf.divide(eig_vals, self.smooth_placeholder)) scaling_factor = tf.reduce_sum(exp_eig_vals) # Multiplying 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 get_min_eig_vec_proxy(self, use_tf_eig=False): """Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's de...
if use_tf_eig: # If smoothness parameter is too small, essentially no smoothing # Just output the eigen vector corresponding to min return tf.cond(self.smooth_placeholder < 1E-8, self.tf_min_eig_vec, self.tf_smooth_eig_vec) # Using autograph to autom...
<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_scipy_eig_vec(self): """Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eig...
if not self.params['has_conv']: matrix_m = self.sess.run(self.dual_object.matrix_m) min_eig_vec_val, estimated_eigen_vector = eigs(matrix_m, k=1, which='SR', tol=1E-4) min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1]) return ...
<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_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val, penalty_val, learning_rate_val): """Run one step of gradient descent for optimization. Arg...
# Running step step_feed_dict = {self.eig_init_vec_placeholder: eig_init_vec_val, self.eig_num_iter_placeholder: eig_num_iter_val, self.smooth_placeholder: smooth_val, self.penalty_placeholder: penalty_val, self.learning_ra...
<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_optimization(self): """Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise """
penalty_val = self.params['init_penalty'] # Don't use smoothing initially - very inaccurate for large dimension self.smooth_on = False smooth_val = 0 learning_rate_val = self.params['init_learning_rate'] self.current_outer_step = 1 while self.current_outer_step <= self.params['outer_num_s...
<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_target_class(input_dir): """Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f: return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip_eta(eta, ord, eps): """ PyTorch implementation of the clip_eta in utils_tf. :param eta: Tensor :param ord: np.inf, 1, or 2 :param eps: float """
if ord not in [np.inf, 1, 2]: raise ValueError('ord must be np.inf, 1, or 2.') avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.device) reduc_ind = list(range(1, len(eta.size()))) if ord == np.inf: eta = torch.clamp(eta, -eps, eps) else: if ord == 1: # TODO # raise No...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attack(self, imgs, targets): """ Perform the EAD attack on the given instance for the given targets. If self.targeted is true, then the targets represents th...
batch_size = self.batch_size r = [] for i in range(0, len(imgs) // batch_size): _logger.debug( ("Running EAD attack on instance %s of %s", i * batch_size, len(imgs))) r.extend( self.attack_batch( imgs[i * batch_size:(i + 1) * batch_size], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(args): """ Validates the submission. """
print_in_box('Validating submission ' + args.submission_filename) random.seed() temp_dir = args.temp_dir delete_temp_dir = False if not temp_dir: temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) delete_temp_dir = True validator = submission_validator_lib.S...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attack(self, x, y_p, **kwargs): """ This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs. ...
inputs = [] outputs = [] # Create the initial random perturbation device_name = '/gpu:0' self.model.set_device(device_name) with tf.device(device_name): with tf.variable_scope('init_rand'): if self.rand_init: eta = tf.random_uniform(tf.shape(x), -self.eps, self.eps) ...
<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_np(self, x_val, **kwargs): """ Facilitates testing this attack. """
_, feedable, _feedable_types, hash_key = self.construct_variables(kwargs) if hash_key not in self.graphs: with tf.variable_scope(None, 'attack_%d' % len(self.graphs)): # x is a special placeholder we always want to have with tf.device('/gpu:0'): x = tf.placeholder(tf.float32, s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None, feed=None, args=None): """ A helper function that computes a tensor on numpy inputs by...
if args is not None: warnings.warn("`args` is deprecated and will be removed on or " "after 2019-03-09. Pass `batch_size` directly.") if "batch_size" in args: assert batch_size is None batch_size = args["batch_size"] if batch_size is None: batch_size = DEFAULT_EXAMPLES_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 _check_y(y): """ Makes sure a `y` argument is a vliad numpy dataset. """
if not isinstance(y, np.ndarray): raise TypeError("y must be numpy array. Typically y contains " "the entire test set labels. Got " + str(y) + " of type " + str(type(y)))
<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_batch(images_batch, preproc_func=None): """ Creates a preprocessing graph for a batch given a function that processes a single image. :param image...
if preproc_func is None: return images_batch with tf.variable_scope('preprocess'): images_list = tf.split(images_batch, int(images_batch.shape[0])) result_list = [] for img in images_list: reshaped_img = tf.reshape(img, img.shape[1:]) processed_img = preproc_func(reshaped_img) re...