Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> class CatalogueIntegrationTest (unittest.TestCase): def setUp(self): self._data_dir = os.path.join(os.path.dirname(__file__), 'data') def test_load(self): catalogue = tacl.Catalogue() catalogue.load(os.path.join(self._data_dir, '...
self.assertRaises(MalformedCatalogueError, catalogue.load, path)
Given the following code snippet before the placeholder: <|code_start|> """ return self._ordered_labels or self.labels @property def labels(self): """Returns the distinct labels defined in the catalogue. :rtype: `list` """ return sorted(set(self.values())) ...
CATALOGUE_WORK_RELABELLED_ERROR.format(work))
Next line prediction: <|code_start|> """ return self._ordered_labels or self.labels @property def labels(self): """Returns the distinct labels defined in the catalogue. :rtype: `list` """ return sorted(set(self.values())) def load(self, path): """L...
raise MalformedCatalogueError(
Continue the code snippet: <|code_start|> def _get_rows_from_results(self, results): return self._get_rows_from_csv(results.csv( io.StringIO(newline=''))) def _test_required_columns(self, cols, cmd, *args, **kwargs): """Tests that when `cmd` is run with `args` and `kwargs`, it raise...
self.assertRaises(MalformedResultsError, getattr(results, cmd),
Next line prediction: <|code_start|> Z = np.logical_xor(X, Y).astype(int) est_goettingen = _estimate(Z) assert np.isclose(-0.5849625007211562, est_goettingen['avg'][((1,), (2,),)][2]), ( 'Average Shared is not -0.5849...') def test_average_pid_source_copy(): """Test Goettingen estimator on cop...
pid_goettingen = SxPID(SETTINGS)
Here is a snippet: <|code_start|>"""Estimate partial information decomposition (PID). Estimate PID for multiple sources (up to 4 sources) and one target process using SxPID estimator. Note: Written for Python 3.4+ """ <|code_end|> . Write the next line using the current file imports: import numpy as np from .s...
class MultivariatePID(SingleProcessAnalysis):
Predict the next line after this snippet: <|code_start|> index of target processes sources : list of ints indices of the multiple source processes for the target Returns: ResultsMultivariatePID instance results of network inference, see documentation of ...
EstimatorClass = find_estimator(settings['pid_estimator'])
Next line prediction: <|code_start|> sources : list of lists indices of the multiple source processes for each target, e.g., [[0, 1, 2], [1, 0, 3]], all must lists be of the same lenght and list of lists must have the same length as targets Returns: ...
results = ResultsMultivariatePID(
Next line prediction: <|code_start|>"""Estimate partial information decomposition (PID). Estimate PID for two source and one target process using different estimators. Note: Written for Python 3.4+ """ <|code_end|> . Use current file imports: (import numpy as np from .single_process_analysis import SingleProce...
class BivariatePID(SingleProcessAnalysis):
Given the following code snippet before the placeholder: <|code_start|> index of target processes sources : list of ints indices of the two source processes for the target Returns: ResultsPID instance results of network inference, see documentation of ...
EstimatorClass = find_estimator(settings['pid_estimator'])
Based on the snippet: <|code_start|> documentation of analyse_single_target() for details, can contain - lags_pid : list of lists of ints [optional] - lags in samples between sources and target (default=[[1, 1], [1, 1] ...]) data : Data inst...
results = ResultsPID(
Given the code snippet: <|code_start|> reason="Jpype is missing, JIDT estimators are not available") SEED = 0 def _assert_result(results, expected_res, estimator, measure, tol=0.05): # Compare estimates with analytic results and print output. print('{0} - {1} result: {2:.4f} nats expected to be close ...
expected_mi = calculate_mi(corr_expected)
Next line prediction: <|code_start|> @bp.route('/api/v1/deepanimebot/classify_by_url') def api_v1_classify(): maybe_image_url = request.args.get('url') if maybe_image_url is None: return jsonify(error='provide url of image as `url` query param'), 400 message = None try: y = current_app....
app.extensions['classifier'] = classifiers.URLClassifier(
Given snippet: <|code_start|># -*- coding: utf-8 -*- bp = Blueprint('bp', __name__, template_folder='templates') @bp.route('/') def root(): return render_template('index.html') @bp.route('/api/v1/deepanimebot/classify_by_url') def api_v1_classify(): maybe_image_url = request.args.get('url') if maybe_...
except exc.TimeoutError:
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), 'fixtures', '1920x1080.png') def test_fetch_cvimage_from_url(monkeypatch): with open(TEST_IMAGE_PATH, 'rb') as f: image = f.read() monkeypatch.setattr(requests, 'get', mocks.mock...
image = classifiers.fetch_cvimage_from_url('this url is ignored')
Continue the code snippet: <|code_start|> cvimage = cv2.imread(TEST_IMAGE_PATH) # TODO: add fixture for weights and refactor so that model is loaded from a workspace directory classifier = classifiers.ImageClassifier('ignored path', 128, 'deep_anime_model') y = classifier.classify(cvimage) assert isi...
with pytest.raises(exc.NotImage):
Given the following code snippet before the placeholder: <|code_start|> if retweeted_status is None: return False return retweeted_status.author.screen_name == screen_name def status_mentions(status, screen_name): for mention in status.entities.get('user_mentions', []): if mention['screen_n...
classifier = classifiers.MockClassifier()
Using the snippet: <|code_start|> sender_name = status.author.screen_name if sender_name == self.screen_name: return logger.debug(u"{0} incoming status {1}".format(status.id, status.text)) if retweets_me(status, self.screen_name): logger.debug("{0} is a retweet"....
except exc.TimeoutError:
Given snippet: <|code_start|> if not rv: return api, action, args, kwargs = rv end = start + random.randint(1, 5) sleep = end - time.time() if sleep > 0: time.sleep(sleep) return getattr(api, action)(*args, **kwargs) return wrapper class Rep...
reply = self.get_reply(status['id'], status['entities'], TWEET_MAX_LENGTH - len('d {} '.format(sender_name)), messages.DMMessages)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- def test_my_guess_honors_max_length_by_truncating_longest(): y = [ deploy.Prediction(2, '567890', 0.024), deploy.Prediction(7, '012', 0.046), ] # before truncation: # '\n2. 567890 2.40%\n7. 012 4.60%' max_length = 26 <|cod...
reply = messages.Messages.my_guess(y, preface='', max_length=max_length)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- @timeout(30) def fetch_cvimage_from_url(url, maxsize=10 * 1024 * 1024): req = requests.get(url, timeout=5, stream=True) content = '' for chunk in req.iter_content(2048): content += chunk if len(content) > maxsize: r...
message = at_random(
Using the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import class Messages(object): '''Each method is expected to return a message of length under TWEET_MAX_LENGTH. ''' @staticmethod def took_too_long(): <|code_end|> , determine the next line of code. You have imp...
return at_random(
Using the snippet: <|code_start|># -*- coding: utf-8 -*- def test_top_n_shows(monkeypatch): for report, expected in [ (two_shows, [ {'id': '11770', 'name': 'Steins;Gate'}, {'id': '10216', 'name': 'Fullmetal Alchemist: Brotherhood'}]), (no_shows, []), ]: ...
shows = anime_names.get_top_n_shows(100)
Given snippet: <|code_start|> class test_loci(unittest.TestCase): def setUp(self): self.solution ={'A':allele("A"), 'T':allele("T"), 'C':allele("C"), 'G':allele("G"), '-':allele("-")} self.solut...
self.l = locus(pos =0)
Using the snippet: <|code_start|> "chr": u"PA", "count": 10, "freq": 0.10, "mutationalClass": [ { u"ORF": u"PA", u"aminoAcidPos": 6, u"classification": u"Synonymous"...
x = parseJson(json.loads(self.jsonString))
Here is a snippet: <|code_start|> class test_checkORF(unittest.TestCase): def tearDown(self): """ This method is called after each test """ pass def test_good(self): sequence = Seq("ATGATGTAA") <|code_end|> . Write the next line using the current file imports: ...
self.assertTrue(checkORF(sequence))
Using the snippet: <|code_start|> class test_loci(unittest.TestCase): def setUp(self): pass def test_trimming_ends(self): solution = ["AAAAA",[[2,7]]] seqs = ["--AAAAA--","TTAAAAATT"]#TTAATTAAA-AGC" <|code_end|> , determine the next line of code. You have imports: import unittest from...
output = trim_sequences(seqs)
Given snippet: <|code_start|> class TrimmerTest(unittest.TestCase): def test_trim_passthroughIfLengthsMatch(self): left_stanza = "@id.1\nACGTACGT\n+\nQQQQQQQQ" right_stanza = "@id.2\nTGCATGCA\n+\nQQQQQQQQ" source_left = MockReader(left_stanza) source_right = MockReader(right_stanza)...
trim(source_left, source_right, dest_left, dest_right)
Based on the snippet: <|code_start|> class DemultiplexerTest(unittest.TestCase): def test_demultiplex_singleton_identity(self): left_stanza = "@CAT:DUPE_3:ID_1047:FLAG_1 1\nACGTACGT\n+\nAAAAAAAA" right_stanza = "@CAT:DUPE_3:ID_1047:FLAG_1 2\nACGTACGT\n+\nAAAAAAAA" source_left = MockReader(l...
demultiplex(source_left, source_right, barcode_files)
Given the following code snippet before the placeholder: <|code_start|> right_barcodeB = MockWriter() barcode_files = { \ 'AAACCC' : [left_barcodeA, right_barcodeA], \ 'GGGTTT' : [left_barcodeB, right_barcodeB] } demultiplex(source_left, source_right, barcode_files) ...
self.assertRaises(MismatchedSequenceIdError, demultiplex, source_left, source_right, barcode_files)
Predict the next line after this snippet: <|code_start|> def test_demultiplex(self): left_stanza1 = "@AAACCC:DUPE_3:ID_1047:FLAG_1 1\nACGTACGT\n+\nAAAAAAAA" right_stanza1 = "@AAACCC:DUPE_3:ID_1047:FLAG_1 2\nACGTACGT\n+\nAAAAAAAA" left_stanza2 = "@GGGTTT:DUPE_3:ID_1047:FLAG_1 1\nACGTACGT\n+\nA...
self.assertRaises(UndefinedBarcodeError, demultiplex, source_left, source_right, barcode_files)
Continue the code snippet: <|code_start|># Copyright 2015 Google Inc. All rights reserved. # # 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...
Http.request('http://www.example.org')
Predict the next line for this snippet: <|code_start|>class TestCases(unittest.TestCase): TEST_PROJECT_ID = 'test_project' def validate(self, mock_http_request, expected_url, expected_args=None, expected_data=None, expected_headers=None, expected_method=None): url = mock_http_request.call_args[...
Api.get_environment_details('ZONE', 'ENVIRONMENT')
Based on the snippet: <|code_start|> """ Represents a Composer object that encapsulates a set of functionality relating to the Cloud Composer service. This object can be used to generate the python airflow spec. """ gcs_file_regexp = re.compile('gs://.*') def __init__(self, zone, environment): """ Ini...
environment_details = Api.get_environment_details(self._zone, self._environment)
Using the snippet: <|code_start|># Copyright 2018 Google Inc. All rights reserved. # # 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 requ...
test_composer = Composer('foo_zone', 'foo_environment')
Given snippet: <|code_start|> return r'(?P<%s>[01])' % self._attr_name if self._attr_type == 'int': return r'(?P<%s>[0-9]+)' % self._attr_name if self._attr_type == 'float': return r'(?P<%s>[0-9,.]+)' % self._attr_name if self._attr_type == 'string': ...
return {Required(self._attr_name): All(NotNone(msg='<%s> should be not None' % self._attr_name), Boolean())}
Using the snippet: <|code_start|>__author__ = 'Maxim Dutkin (max@dutkin.ru)' class M2CoreIntEnumTest(unittest.TestCase): def setUp(self): <|code_end|> , determine the next line of code. You have imports: import unittest from m2core.common.int_enum import M2CoreIntEnum and context (class names, function names,...
class SampleEnum(M2CoreIntEnum):
Given snippet: <|code_start|> self._current_token = None self._redis = redis_connector self._redis_scheme = redis_scheme self.__inited = False def get_user_id(self) -> None or int: """ Returns user id from Redis (if found) :return: """ self._c...
token = '%s_%s' % (DataHelper.random_hex_str(8), DataHelper.random_hex_str(32))
Given the code snippet: <|code_start|> self._redis.srem(self._redis_scheme['ROLE_PERMISSIONS']['prefix'] % role_id, permission) def dump_user_roles(self, user_id: int, role_ids: list): """ Stores (rewrites) user roles list in Redis """ # delete all existing roles ...
p = M2Permission.load_by_params(system_name=p_name)
Using the snippet: <|code_start|> self._redis_scheme['USER_ROLES']['prefix'] % self._current_user ) group_ids = [int(role_id) for role_id in redis_val] all_permissions = set() for group_id in group_ids: # get permissions per each role by role id permiss...
if options.access_token_update_on_check:
Predict the next line for this snippet: <|code_start|> return self in user_permissions else: return self.rule_chain(user_permissions) def __repr__(self): if self.rule_chain: return self.rule_chain.__repr__() else: return f'<{self.__class__.__na...
@classproperty
Given the code snippet: <|code_start|> query = query.filter(getattr(cls, _field) == _params[_field]) if order_by: order_by_params = order_by.split(' ') order_function = globals()[order_by_params[1]] query = query.order_by(order_function(getattr(cls, order_by_p...
raise M2Error('Error while trying to set non-existent property `%s`' % name)
Given snippet: <|code_start|># import all handlers # import core if __name__ == '__main__': # INIT M2CORE options.config_name = 'config.py' m2core = M2Core() # setup core logger level <|code_end|> , continue by predicting the next line. Consider current file imports: from m2core.common.options import...
core_logger.setLevel(logging.DEBUG)
Here is a snippet: <|code_start|>__author__ = 'Maxim Dutkin (max@dutkin.ru)' class Rules(defaultdict): def validator(self, human_route: str=None): return self[human_route]['validator'] def docs(self, human_route: str=None, method: str=None): return self[human_route]['docs'].get(method.upper...
permissions = PermissionsEnum.SKIP
Given snippet: <|code_start|>__author__ = 'Maxim Dutkin (max@dutkin.ru)' class Rules(defaultdict): def validator(self, human_route: str=None): return self[human_route]['validator'] def docs(self, human_route: str=None, method: str=None): return self[human_route]['docs'].get(method.upper()) ...
-> UrlParser:
Given the code snippet: <|code_start|> class CreatedMixin: """ Stored in UTC without any offset and timezone """ created = Column(DateTime(timezone=False), default=datetime.utcnow, server_default=text('now()'), nullable=False) updated = Column(DateTime(timezone=False), default=datetime.utcnow, serv...
class M2Permission(BaseModel):
Here is a snippet: <|code_start|> class CreatedMixin: """ Stored in UTC without any offset and timezone """ created = Column(DateTime(timezone=False), default=datetime.utcnow, server_default=text('now()'), nullable=False) updated = Column(DateTime(timezone=False), default=datetime.utcnow, server_de...
def can(self, permission_rule: Permission) -> bool:
Based on the snippet: <|code_start|> CreatedMixin.created._creation_order = 9998 CreatedMixin.updated._creation_order = 9999 class SortMixin: sort_order = Column(BigInteger, default=0, server_default='0', nullable=False) SortMixin.sort_order._creation_order = 9997 class M2PermissionCheckMixin: def can(sel...
all_perms = PermissionsEnum.all_platform_permissions
Based on the snippet: <|code_start|> sort_order = Column(BigInteger, default=0, server_default='0', nullable=False) SortMixin.sort_order._creation_order = 9997 class M2PermissionCheckMixin: def can(self, permission_rule: Permission) -> bool: return permission_rule(self.permissions) class M2Permissi...
raise M2Error(f'No corresponding enum member found for Permission with sys_name=`{sys_name}`')
Using the snippet: <|code_start|> def authorize(cls, _email: str, _password: str) -> dict or None: """ Authorize user and save his access token to Redis :param _email: user email :param _password: user password """ user_obj = cls.q.filter( func.lower(cls.em...
M2UserRole.load_or_create(user_id=self.get('id'), role_id=role.get('id'))
Given the following code snippet before the placeholder: <|code_start|> name = Column(String(255), info={'custom_param_for_json_scheme_1': '11111', 'custom_param_for_json_scheme_2': True}) gender = Column(Integer, nullable=False) @classmethod def authorize(cls, _email: str, _password: str) -> dict or No...
role = M2Role.load_by_params(name=_role_name)
Given the following code snippet before the placeholder: <|code_start|> @classmethod def authorize(cls, _email: str, _password: str) -> dict or None: """ Authorize user and save his access token to Redis :param _email: user email :param _password: user password """ ...
raise M2Error('Trying to add non-existent role', True)
Next line prediction: <|code_start|> class SessionMixin: __abstract__ = True @classmethod def set_db_session(cls, session) -> scoped_session or Session: """ Sets DB Session during M2Core initialization with this method """ cls._db_session = session <|code_end|> . Use curre...
@classproperty
Based on the snippet: <|code_start|> class SessionMixin: __abstract__ = True @classmethod def set_db_session(cls, session) -> scoped_session or Session: """ Sets DB Session during M2Core initialization with this method """ cls._db_session = session @classproperty d...
raise M2Error('No DB session defined')
Given the following code snippet before the placeholder: <|code_start|># import all handlers # import permissions # import core # INIT M2CORE options.config_name = 'config.py' m2core = M2Core() if __name__ == '__main__': # setup core logger level core_logger.setLevel(logging.DEBUG) # setup project logg...
m2core.route(human_route, RestApiDocsHandler, get=PlatformPermissions.SKIP)
Given snippet: <|code_start|># import all handlers # import permissions # import core # INIT M2CORE options.config_name = 'config.py' m2core = M2Core() if __name__ == '__main__': # setup core logger level <|code_end|> , continue by predicting the next line. Consider current file imports: from m2core.common.op...
core_logger.setLevel(logging.DEBUG)
Given the code snippet: <|code_start|># Copyright 2012, 2014 Richard Dymond (rjdymond@gmail.com) # # This file is part of Pyskool. # # Pyskool is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 o...
self.snapshot = get_snapshot(snafile)
Using the snippet: <|code_start|># # This file is part of Pyskool. # # Pyskool is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # Pysk...
self.bottom = Location(bottom)
Given snippet: <|code_start|>--------------- The keys to move Eric around are: * 'q' or up arrow - go up stairs, or continue walking in the same direction * 'a' or down arrow - go down stairs, or continue walking in the same direction * 'o' or left arrow - left * 'p' or right arrow - right * 'f' - fire catapult * 'h' ...
version=version,
Given the code snippet: <|code_start|> i = 0 while i < len(args): arg = args[i] if arg == '-q': verbose = False elif arg.startswith('-'): print_usage() else: p_args.append(arg) i += 1 if len(p_args) != 1: print_usage() re...
create_sounds(SKOOL_DAZE, sounds_dir, verbose)
Predict the next line for this snippet: <|code_start|> i = 0 while i < len(args): arg = args[i] if arg == '-q': verbose = False elif arg.startswith('-'): print_usage() else: p_args.append(arg) i += 1 if len(p_args) != 1: prin...
create_sounds(SKOOL_DAZE, sounds_dir, verbose)
Given snippet: <|code_start|> while i < len(args): arg = args[i] if arg == '-q': verbose = False elif arg.startswith('-'): print_usage() else: p_args.append(arg) i += 1 if len(p_args) != 1: print_usage() return p_args[0], ver...
create_sounds(BACK_TO_SKOOL, sounds_dir, verbose)
Here is a snippet: <|code_start|> arg = args[i] if arg == '-q': verbose = False elif arg.startswith('-'): print_usage() else: p_args.append(arg) i += 1 if len(p_args) != 1: print_usage() return p_args[0], verbose def print_usage...
create_sounds(SKOOL_DAZE_TAKE_TOO, sounds_dir, verbose)
Using the snippet: <|code_start|> if arg == '-q': verbose = False elif arg.startswith('-'): print_usage() else: p_args.append(arg) i += 1 if len(p_args) != 1: print_usage() return p_args[0], verbose def print_usage(): sys.stderr.wri...
create_sounds(EZAD_LOOKS, sounds_dir, verbose)
Given snippet: <|code_start|> verbose = False elif arg.startswith('-'): print_usage() else: p_args.append(arg) i += 1 if len(p_args) != 1: print_usage() return p_args[0], verbose def print_usage(): sys.stderr.write("""Usage: {0} [options] D...
create_sounds(BACK_TO_SKOOL_DAZE, sounds_dir, verbose)
Based on the snippet: <|code_start|> class PauseTestCase(TestCase): """ Check to make sure that entries can be paused and unpaused as expected. Rules for pausing an entry: - Must be owned by user - If paused, unpause it - Entry must be open """ fixtures = ['activities', 'projects', 'use...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Using the snippet: <|code_start|> class PauseTestCase(TestCase): """ Check to make sure that entries can be paused and unpaused as expected. Rules for pausing an entry: - Must be owned by user - If paused, unpause it - Entry must be open """ fixtures = ['activities', 'projects', 'users'...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Predict the next line for this snippet: <|code_start|> class AddEntryTestCase(TestCase): """ Rules for adding an entry: - User is logged in - Project is specified - Start time is in the past - End time is in the past - Start time is before end time """ fixtures = ['activities', 'pro...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Continue the code snippet: <|code_start|> class AddEntryTestCase(TestCase): """ Rules for adding an entry: - User is logged in - Project is specified - Start time is in the past - End time is in the past - Start time is before end time """ fixtures = ['activities', 'projects', 'user...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Next line prediction: <|code_start|> SITE = Site.objects.get_current() admin_url = reverse('admin_pendulum_pendulumconfiguration_add') login_url = getattr(settings, 'LOGIN_URL', '/accounts/login/') class PendulumMiddleware: """ This middleware ensures that anyone trying to access Pendulum must be logged in...
except PendulumConfiguration.DoesNotExist:
Using the snippet: <|code_start|> return self.name def __log_count(self): """ Determine the number of entries associated with this activity """ return self.entries.all().count() log_count = property(__log_count) def __total_hours(self): """ Determine ...
set = self.in_period(utils.determine_period())
Predict the next line for this snippet: <|code_start|> class RemoveEntryTestCase(TestCase): """ Test the functionality for removing an entry Rules for removal: - Owned by user - The user will be prompted to confirm their decision """ fixtures = ['activities', 'projects', 'users', 'entries']...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Next line prediction: <|code_start|> class RemoveEntryTestCase(TestCase): """ Test the functionality for removing an entry Rules for removal: - Owned by user - The user will be prompted to confirm their decision """ fixtures = ['activities', 'projects', 'users', 'entries'] def setUp(se...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Predict the next line for this snippet: <|code_start|> class PendulumDateTimeField(forms.SplitDateTimeField): """ This custom field is just a way to offer some more friendly ways to enter a time, such as 1pm or 8:15 pm """ <|code_end|> with the help of current file imports: from django import forms fr...
widget = PendulumDateTimeWidget
Continue the code snippet: <|code_start|> class PendulumDateTimeField(forms.SplitDateTimeField): """ This custom field is just a way to offer some more friendly ways to enter a time, such as 1pm or 8:15 pm """ widget = PendulumDateTimeWidget def __init__(self, date_formats=None, time_formats=Non...
time_formats = time_formats or DEFAULT_TIME_FORMATS
Given snippet: <|code_start|> class UpdateEntryTestCase(TestCase): """ Make sure that the code for updating a closed entry works as expected. Rules for updating an entry: - Owned by user - Closed - Cannot start in the future - Cannot end in the future - Start must be before end """ ...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Next line prediction: <|code_start|> class UpdateEntryTestCase(TestCase): """ Make sure that the code for updating a closed entry works as expected. Rules for updating an entry: - Owned by user - Closed - Cannot start in the future - Cannot end in the future - Start must be before end ...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Given the following code snippet before the placeholder: <|code_start|> class ClockOutTestCase(TestCase): """ Make sure that entries can be closed properly. Rules for clocking out: - Entry must belong to user - Entry must be open - Entry may be paused, but must be unpaused after being closed ...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Given the code snippet: <|code_start|> class ClockOutTestCase(TestCase): """ Make sure that entries can be closed properly. Rules for clocking out: - Entry must belong to user - Entry must be open - Entry may be paused, but must be unpaused after being closed """ fixtures = ['activities...
response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
Given snippet: <|code_start|> return ax else: plt.show(block=block) def pit_filter(self, kernel_size): """ Filters pits in the raster. Intended for use with canopy height models (i.e. grid(0.5).interpolate("max", "z"). This function modifies the raster array ...
gisexport.array_to_raster(self.array, self._affine, self.grid.cloud.crs, path)
Given snippet: <|code_start|> """ summary = {} summary["Minimum (x y z)"] = [ float("{0:.2f}".format(elem)) for elem in self.data.min ] summary["Maximum (x y z)"] = [ float("{0:.2f}".format(elem)) for elem in self.data.max ] summary["Number...
return rasterizer.Grid(self, cell_size)
Continue the code snippet: <|code_start|> construct the intermediate bare earth model. """ filter = Zhang2003(cell_size) if classified: filter.bem(self, classified=classified) filter.normalize(self) else: filter.normalize(self) def subtr...
def clip(self, polygon):
Given the following code snippet before the placeholder: <|code_start|> def test_missing_variable(): template = '{x}' x, y = DataItem('x', 1), DataItem('y', 2) <|code_end|> , predict the next line using imports from the current file: from crosscompute.scripts.serve import parse_template_parts from crosscomput...
parts = parse_template_parts(template, [x, y])
Continue the code snippet: <|code_start|> get_absolute_path = mocker.patch(x + 'get_absolute_path') exists = mocker.patch(x + 'exists') posts_request.matchdict = {'path': 'x'} tool_definition = { 'configuration_folder': TOOL_FOLDER, 'argument_names': ['a'], 'x.a_path': 'x'} g...
get_result_file_response(posts_request, result)
Here is a snippet: <|code_start|> tool_definition['argument_names'] = ('x_path',) # Use bad upload_id raw_arguments = MultiDict({'x': 'a'}) with raises(HTTPBadRequest) as e: result_request.prepare_arguments(tool_definition, raw_arguments) assert e.value.detail['x'] == ...
f = get_tool_file_response
Given snippet: <|code_start|> # Use good path raw_arguments = MultiDict({'x': 'xyz/x/x.txt'}) result = result_request.prepare_arguments( tool_definition, raw_arguments) assert open(result.arguments['x_path']).read() == 'whee' def test_accept_upload_id( self, r...
f = parse_result_relative_path
Here is a snippet: <|code_start|> class TestParseTemplate(object): def test_accept_whitespace(self): data_item = DataItem('x', '') data_items = [data_item] <|code_end|> . Write the next line using the current file imports: from crosscompute.models import Result from crosscompute.types import Dat...
assert data_items == parse_template_parts('{x}', data_items)
Continue the code snippet: <|code_start|> target_path = tmpdir.join('variables.json').strpath value = 1 variable_id = 'a' value_by_id_by_path = defaultdict(dict) save_text_json(target_path, value, variable_id, value_by_id_by_path) assert value_by_id_by_path[target_path][variable_id] == value de...
with raises(CrossComputeExecutionError):
Given snippet: <|code_start|> if 'path' in variable_configuration: mode_name = variable_definition.mode_name path = self.folder / mode_name / variable_configuration['path'] try: variable_configuration.update(json.load(open(path, 'rt'))) except OSErr...
mode_code = MODE_CODE_BY_NAME[variable_definition.mode_name]
Predict the next line after this snippet: <|code_start|> mode_name = variable_definition.mode_name path = self.folder / mode_name / variable_configuration['path'] try: variable_configuration.update(json.load(open(path, 'rt'))) except OSError: ...
mode_uri = MODE_ROUTE.format(mode_code=mode_code)
Given the following code snippet before the placeholder: <|code_start|> path = self.folder / mode_name / variable_configuration['path'] try: variable_configuration.update(json.load(open(path, 'rt'))) except OSError: L.error('path not found %s', format_p...
variable_uri = VARIABLE_ROUTE.format(
Given the code snippet: <|code_start|> def __init__(self, automation_definition, batch_definition): self.automation_definition = automation_definition self.batch_definition = batch_definition self.folder = automation_definition.folder / batch_definition.folder def get_variable_configura...
except CrossComputeDataError as e:
Here is a snippet: <|code_start|> class DiskBatch(Batch): def __init__(self, automation_definition, batch_definition): self.automation_definition = automation_definition self.batch_definition = batch_definition self.folder = automation_definition.folder / batch_definition.folder def ge...
variable_data = load_variable_data(
Predict the next line for this snippet: <|code_start|> if '</p>\n<p>' not in html: html = html.removeprefix('<p>') html = html.removesuffix('</p>') return html def is_port_in_use(port): # https://stackoverflow.com/a/52872579 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: ...
process = LoggableProcess(name='browser', target=wait_then_run)
Based on the snippet: <|code_start|> def test_format_slug(): assert format_slug('a b,c') == 'a-b-c' def test_get_html_from_markdown(): <|code_end|> , predict the immediate next line with the help of imports: from crosscompute.macros.web import ( format_slug, get_html_from_markdown) and context (classes...
html = get_html_from_markdown('x')
Here is a snippet: <|code_start|> def test_run_command(tmp_path): o_path = tmp_path / 'o.txt' e_path = tmp_path / 'e.txt' with open(o_path, 'wt') as o_file, open(e_path, 'w+t') as e_file: <|code_end|> . Write the next line using the current file imports: from pytest import raises from crosscompute.except...
with raises(CrossComputeExecutionError):
Continue the code snippet: <|code_start|> def test_run_command(tmp_path): o_path = tmp_path / 'o.txt' e_path = tmp_path / 'e.txt' with open(o_path, 'wt') as o_file, open(e_path, 'w+t') as e_file: with raises(CrossComputeExecutionError): <|code_end|> . Use current file imports: from pytest import ...
_run_command('', tmp_path, {}, o_file, e_file)
Predict the next line after this snippet: <|code_start|> } class LinkView(VariableView): view_name = 'link' def render_output(self, b: Batch, x: Element): variable_definition = self.variable_definition data_uri = b.get_data_uri(variable_definition, x) c = b.get_variable_config...
function_by_name = FUNCTION_BY_NAME
Here is a snippet: <|code_start|> for (let i = 0; i < columnCount; i++) { const column = columns[i]; const th = document.createElement('th'); th.innerText = column; tr.append(th); } thead.append(tr); for (let i = 0; i < rowCount; i++) { const row = rows[i]; tr = document.createElement('tr...
maximum_length=MAXIMUM_FILE_CACHE_LENGTH)
Predict the next line for this snippet: <|code_start|> def get_variable_value_by_id(data_by_id): return { variable_id: data['value'] for variable_id, data in data_by_id.items() } def format_text(text, data_by_id): if not data_by_id: return text def f(match): expression_text =...
return VARIABLE_ID_PATTERN.sub(f, text)