Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|>"""Installers for programming language specific libraries. """ def r_library_installer(config): """Install R libraries using CRAN and Bioconductor. """ if config.get("cran") or config.get("bioc") or config.get("github"): with shared._make_tmp_dir() as tmp_d...
rscripts.append(fabutils.find_cmd(env, os.path.join(os.path.dirname(conda_bin), "Rscript"),
Predict the next line after this snippet: <|code_start|>def _build_galaxy_loc_line(env, dbkey, file_path, config, prefix, tool_name): """Prepare genome information to write to a Galaxy *.loc config file. """ if tool_name: str_parts = [] tool_conf = _get_tool_conf(env, tool_name) loc_...
with shared.chdir(tools_dir):
Based on the snippet: <|code_start|>"""Infrastructure for RNA-seq supporting files. """ def finalize(genomes, data_filedir): """Provide symlinks back to reference genomes so tophat avoids generating FASTA genomes. """ genome_dir = os.path.join(data_filedir, "genomes") for (orgname, gid, manager) in ge...
with shared.chdir(aligner_dir):
Predict the next line for this snippet: <|code_start|> env.std_sources = _add_source_versions(env.dist_name, sources) def _setup_debian(): env.logger.info("Debian setup") unstable_remap = {"sid": "squeeze"} shared_sources = _setup_deb_general() sources = [ "deb http://cran.fhcrc.org/bin/lin...
with quiet():
Based on the snippet: <|code_start|>"""Configuration details for specific server types. This module contains functions that help with initializing a Fabric environment for standard server types. """ def _setup_distribution_environment(ignore_distcheck=False): """Setup distribution environment. In low-level...
configure_runsudo(env)
Continue the code snippet: <|code_start|> Raises: FIXParserError """ # pylint: disable=no-self-use delim = buf.find('=') if delim == -1: raise FIXParserError('Incorrect format: missing "="') tag_id = 0 try: tag_id = int...
self._checksum = checksum(field, self._checksum) + 1
Continue the code snippet: <|code_start|> This is a FIX-formatted message, so this assumes that the key is a numeric string, that is only digits are allowed. Args: output: tag: value: """ output.write(_single_field(tag, value)) def _write_field(outp...
class FIXMessage(BasicMessage):
Next line prediction: <|code_start|> self.assertEquals(19001, role_config['admin-port']) self.assertRaises(KeyError, self.config.get_role, 'serverYYY') def test_get_link(self): link_config = self.config.get_link('clientX', 'serverY') self.assertIsNotNone(link_config) self.as...
config = FileConfig(file_path)
Predict the next line for this snippet: <|code_start|>""" base.config unit tests Copyright (c) 2014 Kenn Takara See LICENSE for details """ class TestConfig(unittest.TestCase): # pylint: disable=missing-docstring def setUp(self): <|code_end|> with the help of current file imports: import os imp...
self.config = DictConfig({
Using the snippet: <|code_start|>""" Base client/server controller for testing. Copyright (c) 2014 Kenn Takara See LICENSE for details """ class SimpleClientServerController(BaseClientServerController): """ The base class for FIX-based TestCaseControllers. """ def __init__(self, **kwargs): ...
self.client.send_message(new_order_message(self.client,
Predict the next line for this snippet: <|code_start|> class SimpleClientServerController(BaseClientServerController): """ The base class for FIX-based TestCaseControllers. """ def __init__(self, **kwargs): super(SimpleClientServerController, self).__init__(**kwargs) self.testcase_id = 'Sim...
self.server.send_message(execution_report(self.server,
Continue the code snippet: <|code_start|>""" base.message unit tests Copyright (c) 2014 Kenn Takara See LICENSE for details """ class TestBasicMessage(unittest.TestCase): # pylint: disable=missing-docstring def test_simple_basicmessage(self): """ Create a message and see if basic operation...
mess = BasicMessage()
Predict the next line after this snippet: <|code_start|>from __future__ import print_function try: except ImportError: import_module = __import__ __title__ = 'pif.discover' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013-2016 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('aut...
ip_checkers_dir = get_setting('IP_CHECKERS_DIR')
Predict the next line for this snippet: <|code_start|>from __future__ import print_function try: except ImportError: import_module = __import__ __title__ = 'pif.discover' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013-2016 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('autod...
for app_path in os.listdir(PROJECT_DIR(ip_checkers_dir)):
Given the following code snippet before the placeholder: <|code_start|> :return str: """ raise NotImplementedError( "You should override ``get_ip`` method in your IP checker class." ) class PublicIPCheckerRegistry(object): """Registry of public IP checkers.""" def ...
raise InvalidRegistryItemType(
Given the code snippet: <|code_start|> res = {} failed = [] for checker in checkers: _res = self._test_get_public_ip_using_preferred_checker(checker) if _res is None: failed.append(checker) res.update({checker: _res}) self.assertTrue( ...
class MyPublicIPChecker(BasePublicIPChecker):
Next line prediction: <|code_start|>def log_info(func): """Prints some useful info.""" if not LOG_INFO: return func def inner(self, *args, **kwargs): result = func(self, *args, **kwargs) LOGGER.info('\n%s', func.__name__) LOGGER.info('============================') ...
self.assertTrue(len(registry.registry) > 0)
Continue the code snippet: <|code_start|> def inner(self, *args, **kwargs): result = func(self, *args, **kwargs) LOGGER.info('\n%s', func.__name__) LOGGER.info('============================') LOGGER.info('""" %s """', func.__doc__.strip()) LOGGER.info('-----------------------...
res = get_public_ip(verbose=True)
Given snippet: <|code_start|> class PifTest(unittest.TestCase): """Tests.""" def setUp(self): """Set up.""" pass @log_info def test_01_autodiscover(self): """Test ``autodiscover``.""" autodiscover() self.assertTrue(len(registry.registry) > 0) @log_info ...
checkers = list_checkers()
Predict the next line after this snippet: <|code_start|> """Lists all registered checkers.""" res = list_checkers() self.assertTrue(len(res) > 0) return res @log_info def test_05_unregister_checker(self): """Test un-register checker `dyndns.com`.""" self.assertTru...
ensure_autodiscover()
Next line prediction: <|code_start|> def log_info(func): """Prints some useful info.""" if not LOG_INFO: return func def inner(self, *args, **kwargs): result = func(self, *args, **kwargs) LOGGER.info('\n%s', func.__name__) LOGGER.info('============================') ...
autodiscover()
Next line prediction: <|code_start|> class Grapher: ### CLASS VARIABLES ### _valid_formats = ("png", "pdf", "svg") _valid_layouts = ("circo", "dot", "fdp", "neato", "osage", "sfdp", "twopi") ### INITIALIZER ### def __init__(self, graphable, format_="pdf", layout="dot", output_directory=None): ...
with Timer() as format_timer:
Here is a snippet: <|code_start|> ) self.extensions = extensions self.errored = False self.results: List[Any] = [] self.monkeypatch = None self.proxy_options: Dict[str, Dict[str, Any]] = {} ### SPECIAL METHODS ### def __enter__(self): self.monkeypatch = M...
with RedirectedStreams(self, self), self:
Based on the snippet: <|code_start|> Get graph-order tuple for node. :: >>> from uqbar.containers import UniqueTreeList, UniqueTreeNode >>> root_container = UniqueTreeList(name="root") >>> outer_container = UniqueTreeList(name="outer") >>> inner_container...
for parent, child in nwise(reversed(self.parentage)):
Here is a snippet: <|code_start|> patch_grapher() def patch_grapher(): def get_format(self): return "svg" def open_output_path(self, output_path): with output_path.open() as file_pointer: contents = file_pointer.read() delete_attributes = True document = minido...
Grapher.get_format = get_format
Predict the next line after this snippet: <|code_start|> class MyObject: def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): self.arg1 = arg1 self.arg2 = arg2 self.var_args = var_args self.foo = foo self.bar = bar self.kwargs = kwargs def test_...
assert get_hash(object_a) == get_hash(object_b)
Continue the code snippet: <|code_start|> @pytest.mark.sphinx("text", testroot="uqbar-sphinx-api-1") def test_sphinx_api_1(app, status, warning): app.build() index_source = pathlib.Path(app.srcdir) / "api" / "index.rst" assert index_source.exists() assert "build succeeded" in status.getvalue() as...
assert normalize(file_pointer.read()) == normalize(
Given the following code snippet before the placeholder: <|code_start|> node_a = uqbar.graphs.Node(name="foo") node_b = uqbar.graphs.Node(name="bar") uqbar.graphs.Edge().attach(node_a, node_b) def test___format___str(self): node_a = uqbar.graphs.Node(name="foo") node_b = uqba...
assert format(edge, "graphviz") == normalize(
Based on the snippet: <|code_start|> ]: path = pathlib.Path(app.srcdir) / "_build" / "text" / filename actual_content = normalize(path.read_text()) assert actual_content == expected_content @pytest.mark.sphinx( "text", testroot="uqbar-sphinx-book", confoverrides={"uqbar_book_use_cache":...
assert normalize(ansi_escape(status.getvalue())) == normalize(
Given the code snippet: <|code_start|> @pytest.mark.sphinx("text", testroot="uqbar-sphinx-style") def test_sphinx_style_1(app, status, warning): app.build() assert "build succeeded" in status.getvalue() assert not warning.getvalue().strip() path = ( pathlib.Path(app.srcdir) / "_build"...
assert normalize(file_pointer.read()) == normalize(
Predict the next line after this snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent docs_path = test_path / "docs" if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) if docs_path.exists(): shutil.rmtree(str(docs_path))...
assert normalize(str(node_tree)) == normalize(
Here is a snippet: <|code_start|> uqbar.graphs.Attributes(mode="edge") uqbar.graphs.Attributes(mode="graph") uqbar.graphs.Attributes(mode="node") def test___format___str_01(self): attributes = uqbar.graphs.Attributes(mode="node") assert format(attributes) == repr(attributes) ...
assert format(attributes, "graphviz") == normalize(
Given snippet: <|code_start|> assert node_a._get_canonical_name() == "foo_0" assert node_b._get_canonical_name() == "foo_1" assert node_c._get_canonical_name() == "bar" def test___format___str(self): node = uqbar.graphs.Node() assert format(node) == repr(node) node =...
assert format(node, "graphviz") == normalize(
Continue the code snippet: <|code_start|> builder = uqbar.apis.APIBuilder( [test_path / "fake_package"], test_path / "docs", member_documenter_classes=[ uqbar.apis.FunctionDocumenter, uqbar.apis.SummarizingClassDocumenter, ], module_documenter_class=uqb...
assert normalize(file_pointer.read()) == normalize(
Predict the next line for this snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) def test_str_01(test_path): documenter = uqbar.apis.SummarizingClassDocumenter( "fake_p...
assert normalize(str(documenter)) == normalize(
Using the snippet: <|code_start|> parser.add_argument("--loud", action="store_true", help="be adamant") class WoofCLI(uqbar.cli.CLI): alias = "woof" scripting_group = "mammals" short_description = "speak like a dog" def _process_args(self, arguments): if arguments.loud: pr...
assert normalize(string_io.getvalue()) == normalize(
Based on the snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) def test_str_01(test_path): documenter = uqbar.apis.SummarizingModuleDocumenter("fake_package.module") <|code_end...
assert normalize(str(documenter)) == normalize(
Continue the code snippet: <|code_start|> def from_expr(cls, expr): if isinstance(expr, cls): return expr elif isinstance(expr, float): return cls(int(expr)) elif isinstance(expr, int): return cls(expr) elif isinstance(expr, str): <|code_end|> . Use current file imports: impor...
coerced_expr = to_snake_case(expr.strip()).upper()
Given snippet: <|code_start|> @pytest.fixture def test_path(): test_path = pathlib.Path(__file__).parent if str(test_path) not in sys.path: sys.path.insert(0, str(test_path)) def test_str_01(test_path): documenter = uqbar.apis.ClassDocumenter("fake_package.module.PublicClass") <|code_end|> , co...
assert normalize(str(documenter)) == normalize(
Here is a snippet: <|code_start|> @idiokit.stream def peel_messages(): while True: elements = yield idiokit.next() for message in elements.named("message"): yield idiokit.send(message.children()) <|code_end|> . Write the next line using the current file imports: import getpass impor...
class BridgeBot(bot.Bot):
Continue the code snippet: <|code_start|>""" Bot for testing XMPP server robustness. Sends rapidly as many events to a channel as possible. Maintainer: AbuseSA team <contact@abusesa.com> """ <|code_end|> . Use current file imports: import idiokit from abusehelper.core import bot, events and context (classes, func...
class StressBot(bot.FeedBot):
Given snippet: <|code_start|>""" Bot for testing XMPP server robustness. Sends rapidly as many events to a channel as possible. Maintainer: AbuseSA team <contact@abusesa.com> """ class StressBot(bot.FeedBot): data = bot.Param("event data") @idiokit.stream def feed(self): <|code_end|> , continue by pred...
event = events.Event.from_unicode(self.data.decode("utf-8"))
Continue the code snippet: <|code_start|> class Receiver(bot.XMPPBot): room = bot.Param(""" the room for receiving events from """) @idiokit.stream def main(self): xmpp = yield self.xmpp_connect() room = yield xmpp.muc.join(self.room) yield idiokit.pipe( ro...
events.stanzas_to_events(),
Continue the code snippet: <|code_start|> def normalize(value): if value.startswith("[[") and value.endswith("]]"): return value[2:-2] return value <|code_end|> . Use current file imports: import urllib import getpass import hashlib import idiokit from abusehelper.core import bot, events from openc...
class OpenCollabReader(bot.FeedBot):
Given snippet: <|code_start|>from __future__ import unicode_literals class TestString(unittest.TestCase): def test_matching(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import re import pickle import unittest from ..atoms import String, RegExp, IP, DomainName and ...
self.assertTrue(String("atom").match("atom"))
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals class TestString(unittest.TestCase): def test_matching(self): self.assertTrue(String("atom").match("atom")) self.assertFalse(String("atom").match("ATOM")) _options = [ Stri...
RegExp.from_string("www.example.com", ignore_case=False),
Continue the code snippet: <|code_start|> for flag in [re.M, re.L, re.X]: self.assertRaises(ValueError, RegExp.from_re, re.compile("a", flag)) def test_matching(self): self.assertTrue(RegExp("a").match("a")) # Matching only to the beginning of the string must be explicitly defin...
self.assertRaises(ValueError, IP, "192.0.2.0", 33)
Given the following code snippet before the placeholder: <|code_start|> @idiokit.stream def _rate_limiter(rate_limit): last_output = time.time() while True: if rate_limit is not None: delta = max(time.time() - last_output, 0) delay = 1.0 / rate_limit - delta if dela...
class Receiver(bot.XMPPBot):
Given snippet: <|code_start|>def _rate_limiter(rate_limit): last_output = time.time() while True: if rate_limit is not None: delta = max(time.time() - last_output, 0) delay = 1.0 / rate_limit - delta if delay > 0.0: yield idiokit.sleep(delay) ...
events.events_to_elements(),
Continue the code snippet: <|code_start|> for value in values: results = results | set([x for x in value.split("|") if x]) return tuple(results) @idiokit.stream def _parse(): while True: event = yield idiokit.next() for key in event.keys(): event.pop(key, filter=lambda ...
class RansomwareTrackerBot(bot.PollingBot):
Based on the snippet: <|code_start|> while True: event = yield idiokit.next() for key in event.keys(): event.pop(key, filter=lambda value: not value.strip()) for key in ("ip", "asn", "cc"): event.update(key, _value_split(event.pop(key))) for timestamp in eve...
info, fileobj = yield utils.fetch_url(self.feed_url)
Given the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. _default_session = {} def get_session(backend_name, **options): global _default_session if not _default_session: _default_session = {} ...
pool = ConnectionPool(factory=Connection,
Predict the next line after this snippet: <|code_start|> filename = os.path.join(path, program) if os.access(filename, os.X_OK): return filename return False weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May',...
raise InvalidUrl("nonnumeric port: '%s'" % host[i+1:])
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. MIME_BOUNDARY = 'END_OF_PART' CRLF = '\r\n' def form_encode(obj, charset="utf8"): encoded = url_encode(obj, charset=charset) <|...
return to_bytestring(encoded)
Continue the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. MIME_BOUNDARY = 'END_OF_PART' CRLF = '\r\n' def form_encode(obj, charset="utf8"): encoded = url_encode(obj, charset=charset) return to_byt...
quote=url_quote):
Given the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. MIME_BOUNDARY = 'END_OF_PART' CRLF = '\r\n' def form_encode(obj, charset="utf8"): <|code_end|> , generate the next line using the imports in this fil...
encoded = url_encode(obj, charset=charset)
Predict the next line for this snippet: <|code_start|>def test_016(u, c): fn = os.path.join(os.path.dirname(__file__), "1M") with open(fn, "rb") as f: l = int(os.fstat(f.fileno())[6]) r = c.request(u, 'POST', body=f) t.eq(r.status_int, 200) t.eq(int(r.body_string()), l) @t....
c.filters = [BasicAuth("test", "test")]
Here is a snippet: <|code_start|> klass = webob.exc.status_map[http_code] self.code = http_code self.title = klass.title self.status = '%s %s' % (self.code, self.title) self.explanation = msg self.response = response # default params self.msg = msg def...
errors.ResourceError = WebobResourceError
Predict the next line for this snippet: <|code_start|> You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """R...
return to_bytestring(key), raw
Based on the snippet: <|code_start|> def __call__(self): print self class ContentTypes(object): _values = {} def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, sorted(self._values)) def __str__(self): return '\n'.join(['%-20.20s: %s' % h for h in \ ...
banner1= 'restkit shell %s' % __version__,
Here is a snippet: <|code_start|> raise ImportError('webob (http://pythonpaste.org/webob/) is required.') class Stream(StringIO): def __repr__(self): return '<Stream(%s)>' % self.len class JSON(Stream): def __init__(self, value): self.__value = value if json: Stream....
class Request(BaseRequest):
Using the snippet: <|code_start|># # This file is part of restkit released under the MIT license. # See the NOTICE for more information. try: except ImportError: raise ImportError('WebOb (http://pypi.python.org/pypi/WebOb) is required') __doc__ = '''Subclasses of webob.Request who use restkit to get a webob.Re...
PROXY = Proxy(allowed_methods=['GET', 'POST', 'HEAD', 'DELETE', 'PUT', 'PURGE'])
Continue the code snippet: <|code_start|># -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. """ TeeInput replace old FileInput. It use a file if size > MAX_BODY or memory. It's now possible to rewind read or restart etc ... It's based on TeeIn...
CHUNK_SIZE = conn.CHUNK_SIZE
Given the following code snippet before the placeholder: <|code_start|> def do_HEAD(self): if self.path == "/ok": extra_headers = [('Content-type', 'text/plain')] self._respond(200, extra_headers, '') else: self.error_Response() def error_Response(self, messag...
body = to_bytestring(body)
Given snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. root_uri = "http://%s:%s" % (HOST, PORT) def with_webob(func): def wrapper(*args, **kwargs): req = Request.blank('/') req.environ['SERVER_N...
proxy = wsgi_proxy.Proxy()
Predict the next line for this snippet: <|code_start|> class ModelWithChainedQuerySet(models.Model): foo = models.BooleanField(default=False) bar = models.BooleanField(default=False) <|code_end|> with the help of current file imports: from django.db import models from django.db.models.query import QuerySet ...
objects = QuerySetManager()
Given the following code snippet before the placeholder: <|code_start|> class HtmlGetAnchorHrefTestCase(unittest.TestCase): def test_finds_single_href(self): self.assertEquals( <|code_end|> , predict the next line using imports from the current file: from django.utils import unittest from django_toolkit....
get_anchor_href('<a href="http://example.com">Test</a>'),
Next line prediction: <|code_start|> def test_finds_single_href(self): self.assertEquals( get_anchor_href('<a href="http://example.com">Test</a>'), [u'http://example.com'] ) def test_finds_two_hrefs(self): self.assertEquals( get_anchor_href('<a href="...
get_anchor_contents('<a href="http://example.com">Test</a>'),
Predict the next line after this snippet: <|code_start|> @all_requests def response_content(url, request): if request.headers['User-Agent'] == DESKTOP_USER_AGENT: request.url = 'http://example.com/' return {'status_code': 200} elif request.headers['User-Agent'] == MOBILE_USER_AGENT: req...
url = url_with_protocol(url)
Based on the snippet: <|code_start|> class UrlWithProtocolTestCases(unittest.TestCase): def test_url_with_protocol(self): url = 'example.com' url = url_with_protocol(url) self.assertEquals(url, 'http://example.com') def test_url_with_protocol_www(self): url = 'www.example.com'...
urls = resolve_url(url)
Continue the code snippet: <|code_start|> @all_requests def response_content(url, request): if request.headers['User-Agent'] == DESKTOP_USER_AGENT: request.url = 'http://example.com/' return {'status_code': 200} <|code_end|> . Use current file imports: from django.utils import unittest from django...
elif request.headers['User-Agent'] == MOBILE_USER_AGENT:
Predict the next line for this snippet: <|code_start|> def get_success_url(self): if self.request.REQUEST.has_key('next'): return self.request.REQUEST.get('next') else: return super(GenericUpdateView, self).get_success_url() class GenericDeleteView(DeleteView): template_...
@class_login_required
Here is a snippet: <|code_start|> class SpecialFieldsFormHelper(FormHelper): """ A form helper that automatically uses DatePickerField, DateTimePickerField and DurationPickerField fields. """ def build_default_layout(self, form): fields = [] for name, field in form.fields.iteritems(...
return DatePickerField(name)
Based on the snippet: <|code_start|> class SpecialFieldsFormHelper(FormHelper): """ A form helper that automatically uses DatePickerField, DateTimePickerField and DurationPickerField fields. """ def build_default_layout(self, form): fields = [] for name, field in form.fields.iterite...
return DateTimePickerField(name)
Given the code snippet: <|code_start|> class SpecialFieldsFormHelper(FormHelper): """ A form helper that automatically uses DatePickerField, DateTimePickerField and DurationPickerField fields. """ def build_default_layout(self, form): fields = [] for name, field in form.fields.iteri...
return DurationPickerField(name)
Next line prediction: <|code_start|> class UnicodeWriterTestCase(unittest.TestCase): def test_write(self): f = NamedTemporaryFile(mode='w+') <|code_end|> . Use current file imports: (from django.utils import unittest from django_toolkit.csv.unicode import UnicodeWriter, UnicodeReader, CastingUnicodeWrite...
csv_writer = UnicodeWriter(f, lineterminator="\n")
Predict the next line after this snippet: <|code_start|> self.assertEqual(actual, expected) class CastingUnicodeWriterTestCase(unittest.TestCase): def test_write(self): f = NamedTemporaryFile(mode='w+') csv_writer = CastingUnicodeWriter(f, lineterminator="\n") csv_writer.writerow(...
csv_reader = UnicodeReader(f)
Given the code snippet: <|code_start|> class UnicodeWriterTestCase(unittest.TestCase): def test_write(self): f = NamedTemporaryFile(mode='w+') csv_writer = UnicodeWriter(f, lineterminator="\n") csv_writer.writerow(['NAME', 'AGE']) csv_writer.writerow(['foo', '12']) csv_writ...
csv_writer = CastingUnicodeWriter(f, lineterminator="\n")
Predict the next line for this snippet: <|code_start|> self.assertEquals(self.shorten_url('areallylongsubdomain.areallylongexampleecom12', 32), 'areallylongsubd...gexampleecom12') def test_no_www(self): self.assertEquals(self.shorten_url('www.example.com', 16), 'example.com') def test_www(self)...
def netloc_no_www(self):
Predict the next line after this snippet: <|code_start|> def start_of_month(dt, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify ...
return dt_business_days(start.date(), stop.date())
Next line prediction: <|code_start|> Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://code.activestate.co...
return dt_days(start.date(), stop.date())
Predict the next line for this snippet: <|code_start|># Copyright 2022 The T5X Authors. # # 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 # # ...
loss, z_loss, weight_sum = losses.compute_weighted_cross_entropy(
Here is a 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 # li...
actual_state = state_utils.intersect_state(state_dict, intersect_state_dict)
Predict the next line for this snippet: <|code_start|># 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 an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITION...
t5_data = checkpoint_importer.t5_importer.apply(ckpt_data)
Here is a snippet: <|code_start|># Copyright 2022 The T5X Authors. # # 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...
class SelfAttention(layers.MultiHeadDotProductAttention):
Predict the next line for this snippet: <|code_start|># Copyright 2022 The T5X Authors. # # 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 # # ...
metrics.Sum.from_model_output(values).compute(), expected_result)
Predict the next line after this snippet: <|code_start|># Copyright 2022 The T5X Authors. # # 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 # ...
class SelfAttention(layers.MultiHeadDotProductAttention):
Using the snippet: <|code_start|>"""Tests for gin_utils.""" class GinUtilsTest(absltest.TestCase): def test_rewrite_gin_args(self): test_args = [ '--gin_file=path/to/file', 'gin.value=3', '--gin.value=3', '--gin.value="3"', '--gin.value=\'3\'', '--gin.tricky="ke...
gin_utils.rewrite_gin_args(test_args), expected_args)
Given snippet: <|code_start|># Copyright 2022 The T5X Authors. # # 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 applic...
class SelfAttention(layers.MultiHeadDotProductAttention):
Next line prediction: <|code_start|> emb_dim: int = 512 num_heads: int = 8 num_encoder_layers: int = 6 num_decoder_layers: int = 6 head_dim: int = 64 mlp_dim: int = 2048 # Activation functions are retrieved from Flax. mlp_activations: Sequence[str] = ('relu',) dropout_rate: float = 0.1 # If `True`, t...
x = layers.LayerNorm(
Next line prediction: <|code_start|># Copyright 2022 The T5X Authors. # # 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...
TrainState = train_state_lib.TrainState
Predict the next line after this snippet: <|code_start|> dropout_rate: float = 0.1 # If `True`, the embedding weights are used in the decoder output layer. logits_via_embedding: bool = False class DecoderLayer(nn.Module): """Transformer decoder layer.""" config: TransformerConfig @nn.compact def __call_...
decoder_bias = layers.RelativePositionBiases(
Given the following code snippet before the placeholder: <|code_start|> """Global hyperparameters used to minimize obnoxious kwarg plumbing.""" vocab_size: int # Activation dtypes. dtype: Any = jnp.float32 emb_dim: int = 512 num_heads: int = 8 num_encoder_layers: int = 6 num_decoder_layers: int = 6 hea...
encoder_bias = layers.RelativePositionBiases(
Here is a snippet: <|code_start|> async for index in self.db.indexes.find({"has_json": {"$ne": True}}): index_id = index["_id"] ref_id = index["reference"]["id"] document = await self.db.references.find_one( ref_id, ["data_type", "organism", "targets"] ...
json_string = json.dumps(data, cls=CustomEncoder)
Predict the next line for this snippet: <|code_start|> class CloneReferenceTask(Task): task_type = "clone_reference" def __init__(self, app, task_id): super().__init__(app, task_id) self.steps = [self.copy_otus, self.create_history] async def copy_otus(self): manifest = self.co...
_, patched, _ = await patch_to_version(self.app, source_otu_id, version)
Based on the snippet: <|code_start|> await self.update_context({"inserted_otu_ids": inserted_otu_ids}) async def create_history(self): user_id = self.context["user_id"] inserted_otu_ids = self.context["inserted_otu_ids"] tracker = await self.get_tracker(len(inserted_otu_ids)) ...
remove_diff_files(self.app, diff_file_change_ids),
Given snippet: <|code_start|> @pytest.mark.parametrize("version", ["3.5.9", "3.6.0", "3.6.1"]) async def test_check_mongo_version(dbi, caplog, mocker, version): mocker.patch("virtool.db.mongo.get_mongo_version", return_value=version) caplog.set_level(logging.INFO) try: <|code_end|> , continue by predic...
await check_mongo_version(dbi)
Continue the code snippet: <|code_start|> "stage": None, "error": None, "progress": 0, "timestamp": self._faker.date_time(), } ], "user": {"id": await self.generator.users.get_id()}, } asy...
self._faker = FakerWrapper()
Given snippet: <|code_start|> 1. Removes the ``status`` and ``args`` fields from the job document. 2. Adds a ``username`` field. 3. Adds a ``created_at`` date taken from the first status entry in the job document. 4. Adds ``state`` and ``progress`` fields derived from the most recent ``status`` e...
async def delete(app: App, job_id: str):
Next line prediction: <|code_start|> @pytest.mark.parametrize( "user_id,password,result", [ ("test", "foobar", True), ("baz", "foobar", False), ("test", "baz", False), ("baz", "baz", False), ], ) @pytest.mark.parametrize("legacy", [True, False]) async def test_validate_creden...
document["password"] = hash_password("foobar")