Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Using the snippet: <|code_start|> <span> 42 </span> </div>""", tmpl.generate(foo={'bar': 42}).render(encoding=None)) def test_unicode_expr(self): tmpl = MarkupTemplate(u"""<div xmlns:py="http://genshi.edgewall.org/"> <span py:with="weeks=(u'一', u'二', u'三', u...
suite.addTest(doctest.DocTestSuite(directives))
Predict the next line for this snippet: <|code_start|>#=========================================================================== # # Config parsing # #=========================================================================== __doc__ = """Config parsing. """ #======================================================...
cfg = Data( _config = p )
Given the following code snippet before the placeholder: <|code_start|>batteryMap = { "normal" : 1.0, "low" : 0.1, } #=========================================================================== def decode( text, sensorMap ): """Decode a sensor post from the Acurite bridge. Input is a line of text sent ...
data = Data()
Given the code snippet: <|code_start|>#=========================================================================== # # File and directory utilities. # #=========================================================================== #=========================================================================== def makeDirs(...
Error.raiseException( e, msg )
Next line prediction: <|code_start|> def __init__( self, endian, elems ): """Constructr endian == BIG_ENDIAN or LITTLE_ENDIAN elems = [ ( struct_format_code, name ), ... ] """ assert( endian == "BIG_ENDIAN" or endian == "LITTLE_ENDIAN" ) if endian == "BIG_ENDIAN": ...
obj = Data()
Here is a snippet: <|code_start|>sys.path.insert(1,"./COMTool/") if sys.version_info < (3, 8): print("only support python >= 3.8, but now is {}".format(sys.version_info)) sys.exit(1) <|code_end|> . Write the next line using the current file imports: import os, sys, shutil import zipfile import shutil impor...
linux_out = "comtool_ubuntu_v{}.tar.xz".format(version.__version__)
Here is a snippet: <|code_start|> if type(v) == str: bundle_str_args += f'{k}="{v}",\n' else: bundle_str_args += f'{k}={v},\n' return bundle_str_args match = re.findall(r'BUNDLE\((.*?)\)', spec, flags=re.MULTILINE|re.DOTALL) if len(match) <= 0: ...
i18n.main("finish")
Based on the snippet: <|code_start|>here = path.abspath(path.dirname(__file__)) # update translate i18n.main("finish") # Get the long description from the README file with open(path.join(here, 'README.MD'), encoding='utf-8') as f: long_description = f.read() systemPlatform = platform.platform() if "Linux" i...
version=version.__version__,
Given the code snippet: <|code_start|> here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # Dependencies are automatically detected, but it might need fine tuning. #中文需要显式用gbk方式编码 ...
product_name = parameters.appName.encode('gbk')
Given the code snippet: <|code_start|> here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # Dependencies are automatically detected, but it might need fine tuning. #中文需要显式用gbk方式编码 ...
product_desc = (parameters.appName+" V"+str(helpAbout.versionMajor)+"."+str(helpAbout.versionMinor)).encode("gbk")
Predict the next line for this snippet: <|code_start|> self._ready = asyncio.Event() self._log = loggers[__name__] def append(self, state): self._deque.append(state) self._ready.set() def extend(self, states): self._deque.extend(states) self._ready.set() asy...
size += len(state.data) + TLMessage.SIZE_OVERHEAD
Predict the next line after this snippet: <|code_start|> self._state = state self._deque = collections.deque() self._ready = asyncio.Event() self._log = loggers[__name__] def append(self, state): self._deque.append(state) self._ready.set() def extend(self, states...
while self._deque and len(batch) <= MessageContainer.MAXIMUM_LENGTH:
Here is a snippet: <|code_start|> :param result: The result type of the TL object :param is_function: Is the object a function or a type? :param usability: The usability for this method. :param friendly: A tuple (namespace, friendly method name) if known. :param layer: The layer t...
self.class_name = snake_to_camel_case(self.name)
Predict the next line for this snippet: <|code_start|> 'InputChatPhoto': 'utils.get_input_chat_photo({})', 'InputGroupCall': 'utils.get_input_group_call({})', } NAMED_AUTO_CASTS = { ('chat_id', 'int'): 'await client._get_peer_id({})' } # Secret chats have a chat_id which may be negative. # With the named a...
with file.open('w') as f, SourceBuilder(f) as builder:
Given snippet: <|code_start|> elif 'string' == arg.type: builder.writeln('{} = reader.tgread_string()', name) elif 'Bool' == arg.type: builder.writeln('{} = reader.tgread_bool()', name) elif 'true' == arg.type: # Arbitrary not-None value, don't actually read "true" flags bui...
class_name = snake_to_camel_case(t)
Given snippet: <|code_start|> ... await event.delete() ... # No other event handler will have a chance to handle this event ... raise StopPropagation ... >>> @client.on(events.NewMessage) ... async def _(event): ... # Will never be reached, because ...
def __init__(self, event: EventBuilder, callback: callable, priority: int, filter: Filter):
Using the snippet: <|code_start|> # {fingerprint: (Crypto.PublicKey.RSA._RSAobj, old)} dictionary _server_keys = {} def get_byte_array(integer): """Return the variable length bytes corresponding to the given int""" # Operate in big endian (unlike most of Telegram API) since: # > "...pq is a representati...
n = tlobject.TLObject._serialize_bytes(get_byte_array(key.n))
Predict the next line after this snippet: <|code_start|> r.append(bytes(padding)) return b''.join(r) @staticmethod def _serialize_datetime(dt): if not dt and not isinstance(dt, timedelta): return b'\0\0\0\0' if isinstance(dt, datetime): dt = _datetime_to_...
return pretty_print(self)
Using the snippet: <|code_start|> else: docs.write(' print(result') if tlobject.result != 'Bool' \ and not tlobject.result.startswith('Vector'): docs.write('.stringify()') docs.write(')</pre>')...
docs.write_head(title=snake_to_camel_case(name),
Predict the next line after this snippet: <|code_start|> class RDPFile(DPAPIProbe): def parse(self, data): self.cleartext = None self.dpapiblob = None self.entropy = None self.values = defaultdict(lambda: None) def preprocess(self, **k): s = [] if k.get('file') ...
self.dpapiblob = blob.DPAPIBlob(self.values['password 51'])
Based on the snippet: <|code_start|>## circulated without prior licence ## ## ## ## Author: Jean-Michel Picod <jmichel.p@gmail.com> ## ## ...
self.blob = blob.DPAPIBlob(self.raw)
Given snippet: <|code_start|># Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'),
Given the code snippet: <|code_start|>from __future__ import division from __future__ import print_function flags.DEFINE_string('model', 'w2v', 'Word embedding model') flags.DEFINE_float('noise_multiplier', 0., 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_cli...
model = load_glove_model(model_path)
Given the following code snippet before the placeholder: <|code_start|> flags.DEFINE_string('model', 'w2v', 'Word embedding model') flags.DEFINE_float('noise_multiplier', 0., 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_clip', 0., 'Clipping norm') flags.DEFINE...
model = load_tf_embedding(FLAGS.exp_id, save_dir=save_dir,
Predict the next line after this snippet: <|code_start|> self.gen_params = [v for v in t_vars if v.name.startswith('gen')] self.gen_optimizer = tf.train.AdamOptimizer(lr, beta1=beta1) self.gen_loss = -tf.reduce_mean(self.fake_score) self.gen_train_ops = self.gen_optimizer.minimize( self.gen_loss...
gen_sampler = inf_batch_iterator(n_data, batch_size)
Given the code snippet: <|code_start|> sess = tf.Session() sess.run(tf.global_variables_initializer()) for e in range(epoch): train_d_loss = [] train_g_loss = [] train_l2_loss = [] for _ in range(num_batch_per_epoch): # train disc first for _ in range(disc_iters): disc_idx = ne...
for idx in iterate_minibatches_indices(len(z), batch_size=2048):
Continue the code snippet: <|code_start|> model = WGANGP(x_dim, y_dim, lr=lr, lmbda=lmbda, gamma=gamma, beta1=beta1, activation=activation) gen_sampler = inf_batch_iterator(n_data, batch_size) disc_sampler = inf_batch_iterator(n_data, batch_size) num_batch_per_epoch = n_data // batch_size + (n_...
log('Epoch: {}, disc loss: {:.4f}, gen loss: {:.4f},'
Given the code snippet: <|code_start|># Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
GLOVE_EMBEDDING_PATH = WORD_EMB_PATH + 'glove.840B.300d_gensim.txt'
Predict the next line after this snippet: <|code_start|># Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
VOCAB_PATH = VOCAB_PATH.format(0)
Next line prediction: <|code_start|>def main(_): assert FLAGS.dpsgd exp_id = FLAGS.exp_id num_gpu = FLAGS.num_gpu train_words, unigrams, word_sample_int = preprocess_texts(exp_id) n_vocab = len(unigrams) n_sampled = FLAGS.n_sampled n_embedding = FLAGS.hidden_size init_width = 0.5 / n_embedding epochs ...
optimizer = SparseDPAdamGaussianOptimizer(
Predict the next line after this snippet: <|code_start|> sampled_w_mat = tf.reshape(sampled_w, [nb, n_sampled, n_embedding]) sampled_b_vec = tf.reshape(sampled_b, [nb, n_sampled]) example_emb_mat = tf.reshape(example_emb, [nb, n_embedding, 1]) sampled_logits = tf.squeeze( tf.matmul(sampled_w_mat, ...
train_ops = rigid_op_sequence(tower_grads)
Predict the next line after this snippet: <|code_start|> return vocab_to_int, int_to_vocab def get_target(words, idx, r): start = idx - r if (idx - r) > 0 else 0 stop = idx + r target_words = words[start:idx] + words[idx + 1:stop + 1] return target_words def get_batches(words, batch_size, word_sample_int, ...
with smart_open.open(read_wiki9_train_split(exp_id), encoding='utf-8') as f:
Given the following code snippet before the placeholder: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expr...
flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'),
Given the code snippet: <|code_start|> grads_and_vars, scalar_loss = model(inputs, labels) train_ops = optimizer.apply_gradients(grads_and_vars) saver = tf.train.Saver() iterations = epochs * len(train_words) // batch_size print_every = FLAGS.print_every with tf.Session() as sess: iteration = 0 ...
log("Iteration: {:.4f}%, Loss: {:.4f}, {:.4f} sec/batch".format(
Next line prediction: <|code_start|># Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'),
Given the code snippet: <|code_start|> else: corpus_model = Corpus(dictionary) corpus_model.fit(corpus, window=params['window'] * 2, ignore_missing=True) if save_dict: corpus_model.save(dict_path) print('Dict size: %s' % len(corpus_model.dictionary)) print('Collocations: %s' % corpus_model.matri...
train_docs, test_docs = split_wiki9_articles(exp_id)
Next line prediction: <|code_start|> corpus_model.fit(corpus, window=params['window'] * 2, ignore_missing=True) if save_dict: corpus_model.save(dict_path) print('Dict size: %s' % len(corpus_model.dictionary)) print('Collocations: %s' % corpus_model.matrix.nnz) glove = Glove(no_components=100, learn...
wiki9_articles = WIKI9Articles(train_docs)
Next line prediction: <|code_start|> @six.python_2_unicode_compatible class News(Node): """Represents a News on CrunchBase""" KNOWN_PROPERTIES = [ "title", "author", "posted_on", "url", "created_at", "updated_at", ] def _coerce_values(self): fo...
setattr(self, attr, parse_date(getattr(self, attr)))
Given the following code snippet before the placeholder: <|code_start|> "videos", "news", ] KNOWN_PROPERTIES = [ "permalink", "api_path", "web_path", "last_name", "first_name", "also_known_as", "bio", "profile_image_url", "r...
setattr(self, attr, parse_date(getattr(self, attr)))
Predict the next line for this snippet: <|code_start|> @six.python_2_unicode_compatible class Job(Node): """Represents a Job on CrunchBase""" KNOWN_PROPERTIES = [ "title", "is_current", "started_on", "started_on_trust_code", "ended_on", "ended_on_trust_code", ...
setattr(self, attr, parse_date(getattr(self, attr)))
Here is a snippet: <|code_start|> "api_path", "web_path", "funding_type", "series", "series_qualifier", "announced_on", "announced_on_trust_code", "closed_on", "closed_on_trust_code", "money_raised", "money_raised_currency_code", ...
setattr(self, attr, parse_date(getattr(self, attr)))
Here is a snippet: <|code_start|> "name", "also_known_as", "lifecycle_stage", "profile_image_url", "launched_on", "launched_on_trust_code", "closed_on", "closed_on_trust_code", "homepage_url", "short_description", "description", ...
setattr(self, attr, parse_date(getattr(self, attr)))
Based on the snippet: <|code_start|> The data that is used to initialize a Page looks like this:: "data": { "paging": { "items_per_page": 1000, "current_page": 1, "number_of_pages": 1, "next_page_url": null, "prev_p...
self.total_items = safe_int(paging.get('total_items')) or 0
Given the following code snippet before the placeholder: <|code_start|> "role_company", "role_investor", "role_group", "role_school", "founded_on", "founded_on_trust_code", "is_closed", "closed_on", "closed_on_trust_code", "num_employees_min...
setattr(self, attr, parse_date(getattr(self, attr)))
Next line prediction: <|code_start|> KNOWN_RELATIONSHIPS = [ 'venture_firm', 'investor', 'images', 'videos', 'news', ] KNOWN_PROPERTIES = [ "api_path", "web_path", "permalink", "name", "announced_on", "announced_on_trus...
setattr(self, attr, parse_date(getattr(self, attr)))
Based on the snippet: <|code_start|> @six.python_2_unicode_compatible class Degree(Node): """Represents a Degree on CrunchBase""" KNOWN_PROPERTIES = [ # 'type', # 'uuid', 'started_on', 'started_on_trust_code', 'is_completed', 'completed_on', 'completed_...
setattr(self, attr, parse_date(getattr(self, attr)))
Based on the snippet: <|code_start|>class Acquisition(Node): """Represents a Acquisition on CrunchBase""" KNOWN_PROPERTIES = [ "api_path", "web_path", "price", "price_currency_code", "price_usd", "payment_type", "acquisition_type", "acquisition_st...
setattr(self, attr, parse_date(getattr(self, attr)))
Next line prediction: <|code_start|> HIDDEN_INPUT = forms.widgets.HiddenInput class PartnerForm(forms.ModelForm): def clean(self): cleaned_data = super(PartnerForm, self).clean() if cleaned_data.get('http_auth'): if not cleaned_data.get('http_auth_user'): self._errors['...
model = models.Partner
Given the code snippet: <|code_start|> if not cleaned_data.get('http_auth_pass'): self._errors['http_auth_pass'] = self.error_class( ['HTTP password is mandatory when HTTP authentication is enabled']) if cleaned_data.get('encryption') and not cleaned_data.get('encr...
datefrom = forms.DateTimeField(initial=viewlib.datetimefrom)
Next line prediction: <|code_start|> class Command(BaseCommand): help = _(u'Send all pending asynchronous mdns to your trading partners') def handle(self, *args, **options): # First part of script sends asynchronous MDNs for inbound messages received from partners # Fetch all the pending async...
in_pending_mdns = models.MDN.objects.filter(status='P') # , timestamp__gt=time_threshold) --> why do this?
Using the snippet: <|code_start|> class Command(BaseCommand): help = _(u'Send all pending asynchronous mdns to your trading partners') def handle(self, *args, **options): # First part of script sends asynchronous MDNs for inbound messages received from partners # Fetch all the pending asynchro...
pyas2init.logger.info(_(u'Sending all pending asynchronous MDNs'))
Here is a snippet: <|code_start|> class Command(BaseCommand): help = _(u'Starts the PyAS2 server') def handle(self, *args, **options): try: except Exception: raise ImportError(_(u'Dependency failure: cherrypy library is needed to start the as2 server')) cherrypy.config.upd...
'log.error_file': os.path.join(pyas2init.gsettings['log_dir'], 'cherrypy_error.log'),
Here is a snippet: <|code_start|> def decompress_message(message, payload): """ Function for decompressing the message """ decompressed_content = None if payload.get_content_type() == 'application/pkcs7-mime' \ and payload.get_param('smime-type') == 'compressed-data': <|code_end|> . Write the n...
models.Log.objects.create(message=message, status='S',
Given the code snippet: <|code_start|> def decompress_message(message, payload): """ Function for decompressing the message """ decompressed_content = None if payload.get_content_type() == 'application/pkcs7-mime' \ and payload.get_param('smime-type') == 'compressed-data': models.Log.ob...
pyas2init.logger.debug(
Continue the code snippet: <|code_start|> handler = LinuxEventHandler(logger=logger, dir_watch_data=dir_watch_data, cond=cond, tasks=tasks) notifier = pyinotify.Notifier(watch_manager, handler) notifier.loop() # end of linux-specific #######################################################...
dir_watch_data[-1]['path'] = as2utils.join(pyas2init.gsettings['root_dir'], 'messages',
Given the code snippet: <|code_start|> list_filter = ('name', 'as2_name') fieldsets = ( (None, { 'fields': ( 'name', 'as2_name', 'email_address', 'target_url', 'subject', 'content_type', 'confirmation_message') }), ('Http Authentication', { 'classes...
admin.site.register(models.PrivateCertificate, PrivateCertificateAdmin)
Predict the next line after this snippet: <|code_start|> class Command(BaseCommand): help = _(u'Send an as2 message to your trading partner') args = '<organization_as2name partner_as2name path_to_payload>' def add_arguments(self, parser): parser.add_argument('organization_as2name', type=str) ...
org = models.Organization.objects.get(as2_name=options['organization_as2name'])
Given the following code snippet before the placeholder: <|code_start|> STATUS_CHOICES = ( ('S', _('Sent')), ('R', _('Received')), ('P', _('Pending')), ) message_id = models.CharField(max_length=250, primary_key=True) timestamp = models.DateTimeField(auto_now_add=True) status ...
as2utils.dirshouldbethere(
Continue the code snippet: <|code_start|> staff_required = user_passes_test(lambda u: u.is_staff) superuser_required = user_passes_test(lambda u: u.is_superuser) urlpatterns = [ url(r'^login.*', auth_views.login, {'template_name': 'admin/login.html'}, name='login'), url(r'^logout.*', auth_views.logout, {'next_...
url(r'^home.*', login_required(views.home, login_url='login'), name='home'),
Predict the next line for this snippet: <|code_start|> # Declare global variables gsettings = {} logger = None convertini2logger = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, 'STARTINFO': 25 } def initialize(...
gsettings['managepy_path'] = as2utils.join(settings.BASE_DIR, 'manage.py')
Given snippet: <|code_start|> TEST_DIR = os.path.join((os.path.dirname( os.path.abspath(__file__))), 'fixtures') class AS2SendReceiveTest(TestCase): """Test cases for the AS2 server and client. We will be testing each permutation as defined in RFC 4130 Section 2.4.2 """ @classmethod def setUp...
cls.server_key = models.PrivateCertificate.objects.create(
Given the following code snippet before the placeholder: <|code_start|> with open(out_message.mdn.file, 'rb') as mdn_file: mdn_content = mdn_file.read() # Switch the out and in messages, this is to prevent duplicate message from being picked out_message.delete() in_message.pk...
processed_payload = as2lib.build_message(message)
Here is a snippet: <|code_start|> class Command(BaseCommand): help = _(u'Retrying all failed outbound communications') def handle(self, *args, **options): pyas2init.logger.info(_(u'Retrying all failed outbound messages')) # Get the list of all messages with status retry <|code_end|> . Write t...
failed_msgs = models.Message.objects.filter(status='R', direction='OUT')
Using the snippet: <|code_start|> class Command(BaseCommand): help = _(u'Retrying all failed outbound communications') def handle(self, *args, **options): <|code_end|> , determine the next line of code. You have imports: from django.core.management.base import BaseCommand from django.utils.translation import...
pyas2init.logger.info(_(u'Retrying all failed outbound messages'))
Predict the next line after this snippet: <|code_start|> class Command(BaseCommand): help = _(u'Retrying all failed outbound communications') def handle(self, *args, **options): pyas2init.logger.info(_(u'Retrying all failed outbound messages')) # Get the list of all messages with status retry...
payload = as2lib.build_message(failed_msg)
Given snippet: <|code_start|> class Command(BaseCommand): help = _(u'Automatic maintenance for the AS2 server. ' u'Cleans up all the old logs, messages and archived files.') def handle(self, *args, **options): pyas2init.logger.info(_(u'Automatic maintenance process started')) max_...
old_message = models.Message.objects.filter(
Given snippet: <|code_start|> class Command(BaseCommand): help = _(u'Automatic maintenance for the AS2 server. ' u'Cleans up all the old logs, messages and archived files.') def handle(self, *args, **options): <|code_end|> , continue by predicting the next line. Consider current file imports: fr...
pyas2init.logger.info(_(u'Automatic maintenance process started'))
Given snippet: <|code_start|> register = template.Library() @register.simple_tag def get_init(key): <|code_end|> , continue by predicting the next line. Consider current file imports: from django import template from pyas2 import pyas2init and context: # Path: pyas2/pyas2init.py # def initialize(): # def initserve...
return pyas2init.gsettings.get(key,'')
Given the code snippet: <|code_start|> 'mnist_ceda': 'models/mnist_ceda.pkl', 'mnist_cnn': 'models/mnist_lenet_dropout.pkl', 'cifar_vgg_16': 'models/cifar_vgg_16_dropout.pkl', 'cifar_vgg_32': 'models/cifar_vgg_32_dropout.pkl', 'cifar_vgg_64': 'models/cifar_vgg_64_dropout.pkl', }) PROBA_SAFETY_URL = ...
with jv_utils.open_file(model_path, 'rb', root_dir=root_dir) as f:
Next line prediction: <|code_start|> ] return params class AttacksTest(parameterized.TestCase): def setUp(self): super().setUp() self.prng_seq = hk.PRNGSequence(1234) self.data_spec = make_data_spec(next(self.prng_seq)) def test_forward_deterministic(self): params = make_params(next(self.prng...
attacks.adversarial_attack(
Given the code snippet: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
return verify_utils.DataSpec(
Given the code snippet: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
Variable = Union[relaxation.RelaxVariable,
Predict the next line after this snippet: <|code_start|> def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): """Mainly used for unit testing.""" key = jax.random.PRNGKey(0) if seed is None else jax.random.PRNGKey(seed) if nn == 'mlp': layer_sizes = '5, 5, 5' layer_sizes = np....
bounds = utils.boundprop(
Next line prediction: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
val, info = cvxpy_verify.solve_mip_mlp_elided(verif_instance)
Based on the snippet: <|code_start|># Lint as: python3 """Tests for cvxpy_verify.py.""" NO_MIP_SOLVERS_MESSAGE = 'No mixed-integer solver is installed.' class CvxpyTest(parameterized.TestCase): @unittest.skipUnless(MIP_SOLVERS, NO_MIP_SOLVERS_MESSAGE) def test_mip_status(self): """Test toy MIP is solved op...
model_fn = lambda x: utils.predict_mlp(params, x)
Next line prediction: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
verif_instance = test_utils.make_toy_verif_instance(seed)
Given the code snippet: <|code_start|> tight_input_bounds = jax_verify.IntervalBound(z, z) fun_to_prop = functools.partial(model.apply, params) tight_output_bounds = jax_verify.interval_bound_propagation( fun_to_prop, tight_input_bounds) model_eval = model.apply(params, z) # Because the in...
lambda x: True if isinstance(x, bound_propagation.Bound) else None,
Here is a snippet: <|code_start|> ConfigDict = ml_collections.ConfigDict DataSpec = verify_utils.DataSpec IntervalBound = jax_verify.IntervalBound SpecType = verify_utils.SpecType Tensor = jnp.array LayerParams = verify_utils.LayerParams ModelParams = verify_utils.ModelParams ModelParamsElided = verify_utils.ModelPara...
with jv_utils.open_file(data_path, 'rb', root_dir=root_dir) as f:
Given snippet: <|code_start|># Lint as: python3 """Tests for cvxpy_verify.py.""" class ParamExtractionTest(parameterized.TestCase): """Test the functions extracting network parameters from functions.""" def check_fun_extract(self, fun_to_extract, example_inputs): extracted_params = utils.get_layer_params(fu...
cnn_params = test_utils.make_cnn_params(layer_sizes, k1)
Predict the next line after this snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied...
form = lagrangian_form.Linear()
Given the following code snippet before the placeholder: <|code_start|> return 1.0 def verify_cnn_single_dual(verif_instance): """Run verification for a CNN on a single MNIST/CIFAR problem.""" verif_instance = problem.make_sdp_verif_instance(verif_instance) solver_params = dict( use_exact_eig_train=FLAGS...
obj_value, info = sdp_verify.solve_sdp_dual(
Using the snippet: <|code_start|>flags.DEFINE_string('opt_name', 'rmsprop', 'Optix class: "adam" "sgd" or "rmsprop"') flags.DEFINE_float('kappa_zero_after', 1e9, 'zero kappa_{1:n} after N steps') flags.DEFINE_float('kappa_reg_weight', -1, '-1 disables kappa regularization') FLAGS = flags.FLAGS def...
bounds = boundprop_utils.boundprop(
Continue the code snippet: <|code_start|> """Creates verif instance.""" if FLAGS.boundprop_type == 'ibp': bounds = utils.boundprop( params, utils.init_bound(x, epsilon, input_bounds=input_bounds)) else: bounds = boundprop_utils.boundprop( params, np.expand_dims(x, axis=0), epsilon, input_bo...
verif_instance = problem.make_sdp_verif_instance(verif_instance)
Continue the code snippet: <|code_start|>flags.DEFINE_float('eval_every', 1000, 'Iterations per log.') flags.DEFINE_float('lr_init', 1e-3, 'initial learning rate') flags.DEFINE_float('anneal_factor', 0.1, 'learning rate anneal factor') flags.DEFINE_string('opt_name', 'rmsprop', 'Optix class: "adam" ...
bounds = utils.boundprop(
Predict the next line for this snippet: <|code_start|> """Sample uniformly some point respecting the bounds. Args: key: Random number generator bounds: Tuple containing [lower bound, upper bound] nb_points: How many points to sample. axis: Which dimension to add to correspond to the number of points...
fun = functools.partial(utils.predict_cnn, params)
Given snippet: <|code_start|> def sample_bounded_points(key: jnp.ndarray, bounds: Tuple[jnp.ndarray, jnp.ndarray], nb_points: int, axis: int = 0) -> jnp.ndarray: """Sample uniformly some point respecting the bounds. Args: key: Rando...
params = sdp_test_utils.make_mlp_params(architecture, key_2)
Here is a snippet: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
Primitive = Union[jax.core.Primitive, synthetic_primitives.FakePrimitive]
Given the code snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on ...
LagrangianForm = lagrangian_form.LagrangianForm
Continue the code snippet: <|code_start|> """Small helper functions.""" Params = collections.namedtuple('Params', ['inner', 'outer']) ParamsTypes = collections.namedtuple('ParamsTypes', ['inner', 'outer', 'lagrangian_form']) DataSpec = collections.namedtuple( 'DataSpec', ...
return sdp_utils.fwd(inputs, self.params)
Continue the code snippet: <|code_start|>""" MLP_PATH = 'models/raghunathan18_pgdnn.pkl' CNN_PATH = 'models/mnist_wongsmall_eps_10_adv.pkl' ALL_BOUNDPROP_METHODS = ( jax_verify.interval_bound_propagation, jax_verify.forward_fastlin_bound_propagation, jax_verify.backward_fastlin_bound_propagation, jax_v...
return utils.predict_mlp(params, inputs)
Given snippet: <|code_start|> """Hessian-vector product for H_lambda - refer to docstring for `Av()`.""" lag_grad = lambda v2: flatten(jax.grad(lagrangian)(v2)) hv_v = jax.grad(lambda v2: jnp.vdot(lag_grad(v2), v))(zeros) hv_flat = flatten(hv_v) return hv_flat def Av(v): """Matrix-vector produ...
eig_vec, eig_info = eigenvector_utils.min_eigenvector_exact(
Continue the code snippet: <|code_start|> def _schedule(values: List[float], boundaries: List[int], dtype=jnp.float32) -> Callable[[chex.Array], chex.Numeric]: """Schedule the value of p, the proportion of elements to be modified.""" large_step = max(boundaries) + 1 boundaries = bound...
initialize_fn: utils.InitializeFn,
Given the code snippet: <|code_start|># nu_quad: IBP quadratic matrix constraint: (x_i - l_i)(x_j - u_j) <= 0 # muminus: x'>=0 # muminus2: Triangle linear Relu relaxation - u(Wx+b) - ul - (u-l)x' >= 0 # where l = min(l, 0), u = max(u, 0) # muplus: x'>=Wx+b DualVar = collections.namedtuple( 'DualVar', ...
layer_sizes = utils.layer_sizes_from_bounds(bounds)
Based on the snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and #...
init_bound = utils.init_bound(x[0], epsilon, input_bounds=input_bounds)
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # h...
DataSpec = verify_utils.DataSpec
Predict the next line after this snippet: <|code_start|> std=layer_params.b_std, bounds=layer_params.b_bound, prng_key=key_b, ) layer_params = dataclasses.replace(layer_params, b=b_sampled) sampled_params.append(layer_params) return sampled_params return s...
logits = sdp_utils.predict_cnn(
Predict the next line after this snippet: <|code_start|> class SubpixIndexTestCase(unittest.TestCase): """ Tests for get_healsparse_subpix_indices """ def test_subpix_nside_lt_cov_nside(self): """ Test when subpix_nside is less than coverage nside """ # Test with no bo...
covpix = get_healsparse_subpix_indices(subpix_nside, subpix_hpix, subpix_border, coverage_nside)
Next line prediction: <|code_start|> """ def find_center(self): """ Find the center using the CenteringWcenZred algorithm. This algorithm computes the primary centering likelihood algorithm by computing the connectivity of the members, as well as ensuring consistency bet...
phi_cen = gaussFunction(self.cluster.neighbors.refmag[use],
Based on the snippet: <|code_start|> This algorithm computes the primary centering likelihood algorithm by computing the connectivity of the members, as well as ensuring consistency between zred of the candidates and the cluster redshift. Will set self.maxind (index of best center); self...
zrmod = interpol(self.zlambda_corr.zred_uncorr, self.zlambda_corr.z, self.cluster.redshift)
Given the following code snippet before the placeholder: <|code_start|> # validate the galfile and refmag type(self).__dict__['galfile'].validate('galfile') type(self).__dict__['refmag'].validate('refmag') # get galaxy file stats gal_stats = self._galfile_stats() self.ga...
self.cluster_dtype = copy.copy(cluster_dtype_base)