Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals try: except ImportError: test_path = os.path.dirname(os.path.abspath(__file__)) base_path = os.path.dirname(test_path) class TestUpdater(unittest.TestCase): ...
self.default_config = get_default_config()
Here is a snippet: <|code_start|> def check_extension(filename): """Check if the file extension is in the allowed extensions The `fnmatch` module can also get the suffix: patterns = ["*.md", "*.mkd", "*.markdown"] fnmatch.filter(files, pattern) """ exts = ['.{0}'.format(e) for e in sim...
if not isinstance(directory, unicode):
Based on the snippet: <|code_start|>@task def commit(): """git commit source changes from all tracked files include: - add all tracked files in the work tree, include modified(M), deleted(D) - commit all files in the index, include added(A), modified(M), renamed(R), deleted(D) - untr...
_ans = raw_input('\n{0}\nAdd these files to index? (y/N) '
Predict the next line after this snippet: <|code_start|> class Reuse_TCPServer(socket_server.TCPServer): allow_reuse_address = True class YARequestHandler(http_server.SimpleHTTPRequestHandler): def translate_path(self, path): """map url path to local file system. path and return path are str...
if is_py2:
Given the following code snippet before the placeholder: <|code_start|> URL_ROOT = None PUBLIC_DIRECTORY = None class Reuse_TCPServer(socket_server.TCPServer): allow_reuse_address = True class YARequestHandler(http_server.SimpleHTTPRequestHandler): def translate_path(self, path): """map url path to...
if not isinstance(path, unicode):
Based on the snippet: <|code_start|> def setUp(self): self.default_config = get_default_config() self.args = deepcopy(INIT_ARGS) self.target_path = "_build" if os.path.exists(self.target_path): shutil.rmtree(self.target_path) self.files = [ "_config.ym...
cli.main(self.args)
Continue the code snippet: <|code_start|> cli.main(self.args) for f in self.files: self.assertTrue(os.path.isfile(os.path.join(self.target_path, f))) for d in self.dirs: self.assertTrue(os.path.isdir(os.path.join(self.target_path, d))) def tearDown(self): if ...
copytree(s_themes_path, self.d_themes_path)
Next line prediction: <|code_start|> self.dirs = [ self.default_config['source'], self.default_config['destination'], self.default_config['themes_dir'], os.path.join(self.default_config['themes_dir'], self.default_config['theme']), ...
emptytree(self.output_path)
Using the snippet: <|code_start|>from __future__ import print_function, with_statement, unicode_literals test_path = os.path.dirname(os.path.abspath(__file__)) base_path = os.path.dirname(test_path) INIT_ARGS = { u'--help': False, u'--version': False, u'-c': None, u'-f': None, u'-p': None, u...
self.default_config = get_default_config()
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- logger = logging.getLogger(__name__) yes_answer = ('y', 'yes') def get_input(text): <|code_end|> , generate the next line using the imports in this file: import os import shutil import logging from simiki.compat import raw_input fro...
return raw_input(text)
Predict the next line for this snippet: <|code_start|> try: if os.path.exists(local_dir): _need_update = False for root, dirs, files in os.walk(original_dir): files = [f for f in files if not f.startswith(".")] dirs[:] = [d for d in dirs if not d.start...
copytree(original_dir, local_dir)
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- logger = logging.getLogger(__name__) yes_answer = ('y', 'yes') def get_input(text): return raw_input(text) def _update_file(filename, local_path, original_path): """ :filename: file name to be updated, without directory :loc...
original_fn_md5 = get_md5(original_fn)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals class ANSIFormatter(Formatter): """Use ANSI escape sequences to colored log""" def format(self, record): try: msg = super(ANSIFormatter...
utils.color_msg(lvl2color[rln], rln),
Given snippet: <|code_start|> rln = record.levelname if rln in lvl2color: return "[{0}]: {1}".format( utils.color_msg(lvl2color[rln], rln), msg ) else: return msg class NonANSIFormatter(Formatter): """Non ANSI color format...
if is_linux or is_osx:
Using the snippet: <|code_start|> rln = record.levelname if rln in lvl2color: return "[{0}]: {1}".format( utils.color_msg(lvl2color[rln], rln), msg ) else: return msg class NonANSIFormatter(Formatter): """Non ANSI color fo...
if is_linux or is_osx:
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals test_path = os.path.dirname(os.path.abspath(__file__)) class TestParseConfig(unittest.TestCase): def setUp(self): wiki_path = os.path.join(test_path, 'mywiki_for_others')...
config = parse_config(self.config_file)
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals test_path = os.path.dirname(os.path.abspath(__file__)) class TestParseConfig(unittest.TestCase): def setUp(self): wiki_path = os.path.join(test_path, 'mywiki_for_o...
self.expected_config = get_default_config()
Continue the code snippet: <|code_start|> the file doesn't exist, the script will exit with code 1 and tell the user how to generate it. :return: the cookie secret as bytes """ try: with open(os.path.join(_pwd, 'cookie_secret'), 'rb') as cookie_file: cookie_secret = cookie_file.r...
schema=options.schema,
Predict the next line for this snippet: <|code_start|> ("utf8","utf8_estonian_ci",False), # 198 ("utf8","utf8_spanish_ci",False), # 199 ("utf8","utf8_swedish_ci",False), # 200 ("utf8","utf8_turkish_ci",False), # 201 ("utf8","utf8_czech_ci",False), # 202 ("utf8","utf8_danish_ci",False)...
raise ProgrammingError("Character set '%d' unsupported" % (setid))
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ solace.views.themes ~~~~~~~~~~~~~~~~~~~ Implements support for the themes. :copyright: (c) 2010 by the Solace Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ def get_resource(request, theme, fi...
theme = get_theme(theme)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ solace.utils.ctxlocal ~~~~~~~~~~~~~~~~~~~~~ The context local that is used in the application and i18n system. The application makes this request-bound. :copyright: (c) 2010 by the Solace Team, see AUTHORS for more details. :lice...
after_request_shutdown.connect(local_mgr.cleanup)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ solace.utils.mail ~~~~~~~~~~~~~~~~~ This module can be used to send mails. :copyright: (c) 2010 by the Solace Team, see AUTHORS for more details. (c) 2009 by the Zine Team, see AUTHORS for more details. :license: BSD, ...
if settings.MAIL_LOG_FILE is not None:
Given snippet: <|code_start|> Column('upvotes', Integer, nullable=False), # the number of downvotes casted Column('downvotes', Integer, nullable=False), # the number of bronce badges Column('bronce_badges', Integer, nullable=False), # the number of silver badges Column('silver_badges', Intege...
Column('locale', LocaleType, index=True),
Continue the code snippet: <|code_start|> # the date of the last login Column('last_login', DateTime), # the user's activation key. If this is NULL, the user is already # activated, otherwise this is the key the user has to enter on the # activation page (it's part of the link actually) to activate ...
Column('badge', BadgeType(), index=True),
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ solace.schema ~~~~~~~~~~~~~ This module defines the solace schema. The structure is pretty simple and should scale up to the number of posts we expect. Not much magic happening here. :copyright: (c) 2010 by the Solace Team, se...
users = Table('users', metadata,
Here is a snippet: <|code_start|> mysql_charset=settings.MYSQL_TABLE_CHARSET) metadata.create_all(bind=engine) def drop_tables(): """Drops all tables again.""" metadata.drop_all(bind=get_engine()) def add_query_debug_headers(request, response): """Add headers with the ...
after_request_shutdown.connect(session.remove)
Predict the next line for this snippet: <|code_start|> metadata.create_all(bind=engine) def drop_tables(): """Drops all tables again.""" metadata.drop_all(bind=get_engine()) def add_query_debug_headers(request, response): """Add headers with the SQL info.""" if settings.TRACK_QUERIES: cou...
before_response_sent.connect(add_query_debug_headers)
Here is a snippet: <|code_start|> orm.attributes.instance_state(obj).expire_attributes(dict_, [column]) else: orm.attributes.set_committed_value(obj, column, val + delta) table = mapper.tables[0] stmt = sql.update(table, mapper.primary_key[0] == pk[0], { column: table.c[column] +...
after_cursor_executed.emit(cursor=self, statement=statement,
Based on the snippet: <|code_start|> assert len(pk) == 1, 'atomic_add not supported for classes with ' \ 'more than one primary key' val = orm.attributes.get_attribute(obj, column) if expire: dict_ = orm.attributes.instance_dict(obj) orm.attributes.instance_state(obj...
before_cursor_executed.emit(cursor=self, statement=statement,
Next line prediction: <|code_start|> finally: after_cursor_executed.emit(cursor=self, statement=statement, parameters=parameters, time=_timer() - start) class SignalTrackingMapperExtension(MapperExtension): """Remembe...
before_models_committed.emit(changes=d.values())
Using the snippet: <|code_start|>class SignalTrackingMapperExtension(MapperExtension): """Remembers model changes for the session commit code.""" def after_delete(self, mapper, connection, instance): return self._record(instance, 'delete') def after_insert(self, mapper, connection, instance): ...
after_models_committed.emit(changes=d.values())
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ solace.database ~~~~~~~~~~~~~~~ This module defines lower-level database support. :copyright: (c) 2010 by the Solace Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import with_st...
options = {'echo': settings.DATABASE_ECHO,
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ solace.utils.remoting ~~~~~~~~~~~~~~~~~~~~~ This module implements a baseclass for remote objects. These objects can be exposed via JSON on the URL and are also used by libsolace's direct connection....
if is_lazy_string(obj):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ solace.packs ~~~~~~~~~~~~ The packs for static files. :copyright: (c) 2010 by the Solace Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ <|code_end|> , generate the next line using the imports ...
pack_mgr = PackManager(os.path.join(os.path.dirname(__file__), 'static'))
Next line prediction: <|code_start|> CheckH1MirnovCoords.h1 = True CheckH1MirnovCoords.mds = True CheckH1MirnovCoords.net = True CheckH1MirnovCoords.slow = True CheckH1MirnovCoords.busted = True class CheckH1Device(H1DevTestCase): def test_load_h1(self): self.assertTrue(issubclass(H1, Device)) ...
class CheckGetH1Device(PfTestBase):
Given the code snippet: <|code_start|>""" """ TEST_DATA_PATH = os.path.abspath(os.path.dirname(__file__)) TEST_CONFIG_FILE = os.path.join(TEST_DATA_PATH, "test.cfg") class H1DevTestCase(BasePyfusionTestCase): def setUp(self): pyfusion.conf.utils.clear_config() if pyfusion.orm_manager.IS_ACTIVE: ...
self.assertTrue(isinstance(data, TimeseriesData))
Predict the next line for this snippet: <|code_start|> "Checking again in:\n{} seconds.\n" "Total time elapsed:\n{} seconds.".format(self.jobid, self._cur, self.total_time)) return def start(self): self.root.after(1000, self.countdown) return...
exit_state = jt.get_slurm_exit_state(sjobexitmod_output)
Given snippet: <|code_start|> xZero = (b1 - b2)/(m2 - m1) yZero = m1*xZero + b1 return (xZero, yZero) @register("FlucStruc") def fsplot_phase(input_data, closed=True, hold=0): """ plot the phase of a flucstruc, optionally replicating the last point at the beginning (if closed=True). This version...
short_names_1,p,s = split_names(ch1n) # need to break up loops to do this
Given the code snippet: <|code_start|>"""Test code for data acquisition.""" # channel names in pyfusion test config file timeseries_test_channel_1 = "test_timeseries_channel_1" timeseries_test_channel_2 = "test_timeseries_channel_2" multichannel_name = "test_multichannel_timeseries" <|code_end|> , generate the next...
class CheckFakeDataAcquisition(PfTestBase):
Given the code snippet: <|code_start|> plt.title("Shot 159243 Toroidal Array") if dosave is not None and "poloidal" in dosave.lower(): plt.title("Shot 159243 Poloidal Array") plt.xlabel("Time (ms)") plt.ylabel("Freq (kHz)") plt.xlim([750, 850]) plt.ylim([45...
nt, t_actual = jt.find_closest(raw_times, t0)
Predict the next line after this snippet: <|code_start|> class Device(object): """Represent a laboratory device. In general, a customised subclass of Device will be used. Usage: Device(device_name, **kwargs) Arguments: device_name -- name of device as listed in configuration file, ...
self.acquisition = import_from_str(acq_class_str)(self.acq_name)
Predict the next line for this snippet: <|code_start|>"""Basic device class""" class Device(object): """Represent a laboratory device. In general, a customised subclass of Device will be used. Usage: Device(device_name, **kwargs) Arguments: device_name -- name of device as listed in confi...
self.__dict__.update(get_config_as_dict('Device', config_name))
Using the snippet: <|code_start|> Arguments: device_name -- name of device as listed in configuration file, i.e.: [Device:device_name] Keyword arguments: Any setting in the [Device:device_name] section of the configuration file can be overridden by supplying a keyword argument to her...
@orm_register()
Using the snippet: <|code_start|>"""MDSPlus acquisition.""" try: except: print "MDSplus python package not found" <|code_end|> , determine the next line of code. You have imports: import warnings, os import MDSplus from pyfusion.acquisition.base import BaseAcquisition and context (class names, function names...
class MDSPlusAcquisition(BaseAcquisition):
Predict the next line for this snippet: <|code_start|> (1.185, 0.7732, 0.289):c2, (1.216, 0.7732, 0.227):c3, (1.198, 0.7732, 0.137):c4, (1.129, 0.7732, 0.123):c5, (1.044, 0.7732, 0.128):c6, (0.96...
class MirnovKhMagneticCoordTransform(BaseCoordTransform):
Continue the code snippet: <|code_start|> for test_class in find_subclasses(pyfusion, PfTestBase): globals()['TestSQL%s' %test_class.__name__] = type('TestSQL%s' %test_class.__name__, (test_class, SQLTestCase), {}) globals()['TestSQL%s' %test_class.__name__].sql = True globals()['TestSQL%s' %test_class.__...
globals()['TestNoSQL%s' %test_class.__name__] = type('TestNoSQL%s' %test_class.__name__, (test_class, NoSQLTestCase), {})
Given the code snippet: <|code_start|> for test_class in find_subclasses(pyfusion, PfTestBase): globals()['TestSQL%s' %test_class.__name__] = type('TestSQL%s' %test_class.__name__, (test_class, SQLTestCase), {}) globals()['TestSQL%s' %test_class.__name__].sql = True globals()['TestSQL%s' %test_class.__nam...
for flag in TEST_FLAGS:
Given snippet: <|code_start|> class MetaMethods(type): """Metaclass which provides filter and plot methods for data classes.""" def __new__(cls, name, bases, attrs): for reg in [filter_reg, plot_reg]: reg_methods = reg.get(name, []) attrs.update((i.__name__,history_reg_method(i))...
transform_class = import_from_str(transform_class_str)
Given the code snippet: <|code_start|> def load_transform(self, transform_class): def _new_transform_method(**kwargs): return transform_class().transform(self.__dict__.get(transform_class.input_coords),**kwargs) self.__dict__.update({transform_class.output_coords:_new_transform_method}) ...
config_dict.update(get_config_as_dict('Diagnostic', channel_name))
Next line prediction: <|code_start|> def updated_method(input_data, *args, **kwargs): do_copy = kwargs.pop('copy', True) if do_copy: original_hist = input_data.history input_data = copy.copy(input_data) copy_history_string = "\n%s > (copy)" %(datetime.now()) ...
for reg in [filter_reg, plot_reg]:
Given the following code snippet before the placeholder: <|code_start|> def updated_method(input_data, *args, **kwargs): do_copy = kwargs.pop('copy', True) if do_copy: original_hist = input_data.history input_data = copy.copy(input_data) copy_history_string = "\n%s...
for reg in [filter_reg, plot_reg]:
Continue the code snippet: <|code_start|> def save(self): if pyfusion.orm_manager.IS_ACTIVE: # this may be inefficient: get it working, then get it fast self.channels.save() session = pyfusion.orm_manager.Session() session.add(self) session...
label = unique_id()
Given snippet: <|code_start|> def add_coords(self, **kwargs): self.__dict__.update(kwargs) def load_from_config(self, **kwargs): for kw in kwargs.iteritems(): if kw[0] == 'coord_transform': transform_list = pyfusion.config.pf_options('CoordTransform', kw[1]) ...
@orm_register()
Here is a snippet: <|code_start|>""" generate flucstrucs for benchmarking """ THIS_DIR = os.path.dirname(__file__) stats_file = os.path.join(THIS_DIR, "stats", "fs") n_ch = 30 n_samples = 1024*100 <|code_end|> . Write the next line using the current file imports: import numpy as np import cProfile, pstats, os from ...
data = get_multimode_test_data(channels=get_n_channels(n_ch),
Next line prediction: <|code_start|>""" generate flucstrucs for benchmarking """ THIS_DIR = os.path.dirname(__file__) stats_file = os.path.join(THIS_DIR, "stats", "fs") n_ch = 30 n_samples = 1024*100 <|code_end|> . Use current file imports: (import numpy as np import cProfile, pstats, os from pyfusion.data.tests im...
data = get_multimode_test_data(channels=get_n_channels(n_ch),
Given the following code snippet before the placeholder: <|code_start|>""" generate flucstrucs for benchmarking """ THIS_DIR = os.path.dirname(__file__) stats_file = os.path.join(THIS_DIR, "stats", "fs") n_ch = 30 n_samples = 1024*100 data = get_multimode_test_data(channels=get_n_channels(n_ch), <|code_end|> , predi...
timebase = Timebase(np.arange(n_samples)*1.e-6),
Using the snippet: <|code_start|>except: # importing MDSPlusBaseDataFetcher will fail if MDSPlus is not # installed. in general, we avoid mds in nosttests by calling # nosetests -a '!mds' pyfusion but in this case, the import occurs # outside of a class definition, and can't be avoided wi...
class CheckMDSPlusDataAcquisition(PfTestBase):
Continue the code snippet: <|code_start|> # df_str = "pyfusion.acquisition.MDSPlus.tests.DummyMDSDataFetcher" # test_data = test_acq.getdata(dummy_shot, data_fetcher=df_str, mds_tree="H1DATA") # from MDSplus import Data # self.assertEqual(Data.__dict__, test_data.meta['mds_Data'].__dict__) ...
class MDSAcqTestCase(BasePyfusionTestCase):
Here is a snippet: <|code_start|>"""Test code for MDSPlus data acquisition.""" try: except: # importing MDSPlusBaseDataFetcher will fail if MDSPlus is not # installed. in general, we avoid mds in nosttests by calling # nosetests -a '!mds' pyfusion but in this case, the import occurs # ou...
class DummyMDSData(BaseData):
Next line prediction: <|code_start|>tf.compat.v1.enable_eager_execution() class _VariablesTest(): def testAttributes(self): # Test that after converting an initializer into a variable all the # attributes stays the same. tens = initializers.random_tensor([2, 3, 2], tt_rank=2, dtype=self.dtype) <|code_...
tens_v = variables.get_variable('tt_tens', initializer=tens)
Here is a snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _VariablesTest(): def testAttributes(self): # Test that after converting an initializer into a variable all the # attributes stays the same. <|code_end|> . Write the next line using the current file imports: import numpy as np i...
tens = initializers.random_tensor([2, 3, 2], tt_rank=2, dtype=self.dtype)
Given snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class UtilsTest(tf.test.TestCase): def testUnravelIndex(self): # 2D. shape = (7, 6) linear_idx = [22, 41, 37] desired = [[3, 4], [6, 5], [6, 1]] <|code_end|> , continue by predicting the next line. Consider current file imports: i...
actual = utils.unravel_index(linear_idx, shape)
Using the snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _ApproximateTest(): def testAddN(self): # Sum a bunch of TT-matrices. tt_a = initializers.random_matrix(((2, 1, 4), (2, 2, 2)), tt_rank=2, dtype=self.dtype) tt_b = initializers.random_mat...
res_actual = ops.full(approximate.add_n([tt_a, tt_b], 6))
Here is a snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _ApproximateTest(): def testAddN(self): # Sum a bunch of TT-matrices. tt_a = initializers.random_matrix(((2, 1, 4), (2, 2, 2)), tt_rank=2, dtype=self.dtype) tt_b = initializers.random_mat...
res_actual = ops.full(approximate.add_n([tt_a, tt_b], 6))
Given snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _ApproximateTest(): def testAddN(self): # Sum a bunch of TT-matrices. <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import tensorflow as tf from t3f import ops from t3f import app...
tt_a = initializers.random_matrix(((2, 1, 4), (2, 2, 2)), tt_rank=2,
Given the code snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _ShapesTest(): def testLazyShapeOverflow(self): large_shape = [10] * 20 <|code_end|> , generate the next line using the imports in this file: import tensorflow as tf from t3f import initializers from t3f import shapes and cont...
tensor = initializers.random_matrix_batch([large_shape, large_shape],
Next line prediction: <|code_start|>tf.compat.v1.enable_eager_execution() class _ShapesTest(): def testLazyShapeOverflow(self): large_shape = [10] * 20 tensor = initializers.random_matrix_batch([large_shape, large_shape], batch_size=5, dtype=self.dtype) <|code_end|> . Use current file impo...
self.assertAllEqual([5, 10 ** 20, 10 ** 20], shapes.lazy_shape(tensor))
Here is a snippet: <|code_start|>tf.compat.v1.enable_v2_behavior() class _NeuralTest(): def testKerasDense(self): # Try to create the layer twice to check that it won't crush saying the # variable already exist. x = tf.random.normal((20, 28*28)) <|code_end|> . Write the next line using the current fil...
layer = nn.KerasDense(input_dims=[7, 4, 7, 4], output_dims=[5, 5, 5, 5])
Based on the snippet: <|code_start|> def value_and_grad(f, x): """Gradient of the given function w.r.t. x. Works in eager and graph mode.""" if utils.in_eager_mode(): with tf.GradientTape() as tape: tape.watch(x) v = f(x) return v, tape.gradient(v, x) else: v = f(x) return v, tf.grad...
tt_ranks = shapes.lazy_tt_ranks(left)
Given the code snippet: <|code_start|> e.g. ones that include QR or SVD decomposition (t3f.project, t3f.round) or for functions that work with TT-cores directly (in contrast to working with TT-object only via t3f functions). In this cases this function can silently return wrong results! Example: # Scala...
left = decompositions.orthogonalize_tt_cores(x)
Next line prediction: <|code_start|> # Scalar product with some predefined tensor squared 0.5 * <x, t>**2. # It's gradient is <x, t> t and it's Riemannian gradient is # t3f.project(<x, t> * t, x) f = lambda x: 0.5 * t3f.flat_inner(x, t)**2 projected_grad = t3f.gradients(f, x) # t3f.proj...
x_projection = riemannian.deltas_to_tangent_space(d, x, left, right)
Given the following code snippet before the placeholder: <|code_start|>tf.compat.v1.enable_eager_execution() class _TensorTrainBatchTest(): def testTensorIndexing(self): <|code_end|> , predict the next line using imports from the current file: import numpy as np import tensorflow as tf from t3f import initialize...
tens = initializers.random_tensor_batch((3, 3, 4), batch_size=3,
Predict the next line after this snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _TensorTrainBatchTest(): def testTensorIndexing(self): tens = initializers.random_tensor_batch((3, 3, 4), batch_size=3, dtype=self.dtype) <|code_end|> using the curr...
desired = ops.full(tens)[:, :, :, :]
Next line prediction: <|code_start|>tf.compat.v1.enable_eager_execution() class _BatchOpsTest(): def testConcatMatrix(self): # Test concating TTMatrix batches along batch dimension. <|code_end|> . Use current file imports: (import numpy as np import tensorflow as tf from t3f import ops from t3f import batch_...
first = initializers.random_matrix_batch(((2, 3), (3, 3)), batch_size=1,
Continue the code snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _InitializersTest(): def testTensorOnesAndZeros(self): <|code_end|> . Use current file imports: import numpy as np import tensorflow as tf from t3f import initializers from t3f import ops and context (classes, functions, or cod...
tt_ones = initializers.tensor_ones([2, 3, 4], dtype=self.dtype)
Given the code snippet: <|code_start|>tf.compat.v1.enable_eager_execution() class _InitializersTest(): def testTensorOnesAndZeros(self): tt_ones = initializers.tensor_ones([2, 3, 4], dtype=self.dtype) tt_zeros = initializers.tensor_zeros([2, 3, 4], dtype=self.dtype) ones_desired = np.ones((2, 3, 4), ...
tt_ones_full = self.evaluate(ops.full(tt_ones))
Predict the next line for this snippet: <|code_start|> def l2_regularizer(scale, scope=None): """Returns a function that applies L2 regularization to TensorTrain weights. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. scope: An optional scope name. Returns: A function wit...
return tf.multiply(my_scale, ops.frobenius_norm_squared(tt), name=name)
Given snippet: <|code_start|>The advantage over using `temci completion` directly is, that it's normally significantly faster. Usage: ``` temci_completion [zsh|bash] ``` This returns the location of the completion file. """ SUPPORTED_SHELLS = ["zsh", "bash"] def print_help(): print(""" temci (version {}...
""".format(version, "|".join(SUPPORTED_SHELLS)))
Given snippet: <|code_start|>""" Tests related to the processing of settings """ def test_config_not_ignored(): """ Issue "Config now seems to be ignored completely after type checking #62" """ <|code_end|> , continue by predicting the next line. Consider current file imports: from tests.utils import run...
assert "3 single benchmarks" in run_temci("short exec ls", settings={"run": {"runs": 3}}).out
Predict the next line for this snippet: <|code_start|> { "attributes": { "description": "b" }, "run_config": { "cmd": "true" }, "build_config": { ...
if is_perf_available():
Given snippet: <|code_start|>def test_successful_run_errors(): d = run_temci("short exec true").yaml_contents["run_output.yaml"][0] assert "internal_error" not in d assert "error" not in d def test_errorneous_run(): d = run_temci("short exec 'exit 1'", expect_success=False).yaml_contents["run_output.y...
assert run_temci("short exec 'exit 1' --discard_all_data_for_block_on_error", expect_success=False).ret_code == ErrorCode.PROGRAM_ERROR.value
Predict the next line for this snippet: <|code_start|> def test_errorneous_run(): d = run_temci("short exec 'exit 1'", expect_success=False).yaml_contents["run_output.yaml"][0] assert "error" in d e = d["error"] assert e["return_code"] == 1 def test_check_tag_attribute(): assert run_temci("exec b...
assert "42" in run_temci_proc("short shell echo 42").out
Continue the code snippet: <|code_start|> def run(): sudo_opt_index = sys.argv.index("--sudo") if "--sudo" in sys.argv else sys.maxsize raw_opt_index = sys.argv.index("--") if "--" in sys.argv else sys.maxsize has_sudo_opt = sudo_opt_index != sys.maxsize and sudo_opt_index < raw_opt_index <|code_end|> . U...
if not has_sudo_opt or has_root_privileges():
Using the snippet: <|code_start|> Number = t.Union[int, float] """ Numeric type """ def fnumber(number: Number, rel_deviation: Number = None, abs_deviation: Number = None, is_percent: bool = False) -> str: return FNumber(number, rel_deviation, abs_deviation, is_percent).format() class ParenthesesMode(Enum): ...
@document(settings_format="Configuration format, is in the settings under report/number")
Continue the code snippet: <|code_start|> "hint": ["true", "false"] } } # type: t.Dict[str, t.Any] """ Completion hints for supported shells for this type instance """ def _instancecheck_impl(self, value, info: Info) -> InfoMsg: res = ExactEither(True, False).__i...
wrong = not bool(res) or parse_timespan(value) == None
Given the following code snippet before the placeholder: <|code_start|> return fmt.format(pval) + ["", "k", "M", "G", "T", "P"][exponents] + self.suffix() def suffix(self) -> str: return {self.IB: "iB", self.HZ: "Hz", self.NORMAL: ""}[self] def format_nt(nt: t.NamedTuple, **units: Unit) -> t.List...
if util.on_apple_os():
Based on the snippet: <|code_start|>""" Tests for reporters """ def test_console_reporter_auto_mode(): d = lambda d: { "attributes": {"description": "XYZ" + d}, "data": {"p": [1]} } <|code_end|> , predict the immediate next line with the help of imports: import json from tests.utils import r...
out = run_temci("report in.yaml --console_mode auto",
Continue the code snippet: <|code_start|>def test_properties_regexp(): out = run_temci(r"report in.yaml --properties 'p.*'", files={ "in.yaml": [ { "attributes": {"description": "XYZ"}, "data": {"p456": [1], "z111": [2]} } ] }).out asse...
run_temci_proc("report --reporter {} in.yaml".format(name), files={
Based on the snippet: <|code_start|> self.keep_alive = True # This is a subset of {UPGRADE, CONNECT}, containing the proposals # made by the client for switching protocols. self.pending_switch_proposals: Set[Type[Sentinel]] = set() self.states: Dict[Type[Sentinel], Type[Sentinel...
raise LocalProtocolError(
Based on the snippet: <|code_start|># # It'd be nice if there were some cleaner way to do all this. This isn't # *too* terrible, but I feel like it could probably be better. # # WARNING # ------- # # The script that generates the state machine diagrams for the docs knows how # to read out the EVENT_TRIGGERED_TRANSITION...
class CLIENT(Sentinel, metaclass=Sentinel):
Based on the snippet: <|code_start|># High level events that make up HTTP/1.1 conversations. Loosely inspired by # the corresponding events in hyper-h2: # # http://python-hyper.org/h2/en/stable/api.html#events # # Don't subclass these. Stuff will break. # Everything in __all__ gets re-exported as part of the h11...
method_re = re.compile(method.encode("ascii"))
Based on the snippet: <|code_start|># High level events that make up HTTP/1.1 conversations. Loosely inspired by # the corresponding events in hyper-h2: # # http://python-hyper.org/h2/en/stable/api.html#events # # Don't subclass these. Stuff will break. # Everything in __all__ gets re-exported as part of the h11...
request_target_re = re.compile(request_target.encode("ascii"))
Given snippet: <|code_start|> An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte string. :term:`Bytes-like objects <bytes-like object>` and native strings containing only ascii characters will be automatically converted to byte strings. .. attribute:: target The target...
headers: Headers
Based on the snippet: <|code_start|> .. attribute:: http_version The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details. """ __slots__ = ("method", "headers", "target", "http_version")...
self, "headers", normalize_and_validate(headers, _parsed=_parsed)
Given the following code snippet before the placeholder: <|code_start|> The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details. """ __slots__ = ("method", "headers", "target", "http_version"...
object.__setattr__(self, "method", bytesify(method))
Given the following code snippet before the placeholder: <|code_start|> target: Union[bytes, str], http_version: Union[bytes, str] = b"1.1", _parsed: bool = False, ) -> None: super().__init__() if isinstance(headers, Headers): object.__setattr__(self, "headers", he...
raise LocalProtocolError("Missing mandatory Host: header")
Given snippet: <|code_start|> super().__init__() if isinstance(headers, Headers): object.__setattr__(self, "headers", headers) else: object.__setattr__( self, "headers", normalize_and_validate(headers, _parsed=_parsed) ) if not _parsed: ...
validate(method_re, self.method, "Illegal method characters")
Based on the snippet: <|code_start|> with pytest.raises(LocalProtocolError) as excinfo: validate(my_re, b"", "oops {}") assert "oops {}" in str(excinfo.value) with pytest.raises(LocalProtocolError) as excinfo: validate(my_re, b"", "oops {} xx", 10) assert "oops 10 xx" in str(excinfo.val...
assert bytesify(b"123") == b"123"
Predict the next line for this snippet: <|code_start|> def test_ProtocolError() -> None: with pytest.raises(TypeError): ProtocolError("abstract base class") def test_LocalProtocolError() -> None: try: <|code_end|> with the help of current file imports: import re import sys import traceback import...
raise LocalProtocolError("foo")
Based on the snippet: <|code_start|> def test_ProtocolError() -> None: with pytest.raises(TypeError): ProtocolError("abstract base class") def test_LocalProtocolError() -> None: try: raise LocalProtocolError("foo") except LocalProtocolError as e: assert str(e) == "foo" as...
except RemoteProtocolError as exc2: