Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> .. versionchanged:: 3.2 Added ``fmt`` and ``datefmt`` arguments. """ logging.Formatter.__init__(self, datefmt=datefmt) self._fmt = fmt self._colors = {} if color and _stderr_supports_color(): # The curses module has some str/bytes confusion in # python3. Until version 3.2.3, most methods return # bytes, but only accept strings. In addition, we want to # output these strings with the logging module, which # works with unicode strings. The explicit calls to # unicode() below are harmless in python2 but will do the # right conversion in python 3. fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf") or "") if (3, 0) < sys.version_info < (3, 2, 3): fg_color = unicode_type(fg_color, "ascii") for levelno, code in colors.items(): self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), "ascii") self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii") else: self._normal = '' def format(self, record): try: message = record.getMessage() <|code_end|> with the help of current file imports: import logging import logging.handlers import sys import curses # type: ignore import hurray.options import hurray.options from hurray.server.util import unicode_type, basestring_type and context from other files: # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): , which may contain function names, class names, or code. Output only the next line.
assert isinstance(message, basestring_type) # guaranteed by logging
Based on the snippet: <|code_start|> try: ret = fn(*args, **kwargs) except: exc = sys.exc_info() top = contexts[1] # If there was exception, try to handle it by going through the exception chain if top is not None: exc = _handle_exception(top, exc) else: # Otherwise take shorter path and run stack contexts in reverse order while last_ctx > 0: last_ctx -= 1 c = stack[last_ctx] try: c.exit(*exc) except: exc = sys.exc_info() top = c.old_contexts[1] break else: top = None # If if exception happened while unrolling, take longer exception handler path if top is not None: exc = _handle_exception(top, exc) # If exception was not handled, raise it if exc != (None, None, None): <|code_end|> , predict the immediate next line with the help of imports: import sys import threading from hurray.server.util import raise_exc_info and context (classes, functions, sometimes code) from other files: # Path: hurray/server/util.py # def raise_exc_info(exc_info): # # type: (Tuple[type, BaseException, types.TracebackType]) -> None # pass . Output only the next line.
raise_exc_info(exc)
Predict the next line after this snippet: <|code_start|># ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Simple function wrappers for read and write operations using the configured strategy. The acquisition of the read and write locks (start_read, start_write) as well as the read and write operation itself _must_ be wrapped with try/finally. Otherwise the corresponding locks cannot be decremented/released if program execution ends, e.g., while performing a read or write operation (because of a SIGTERM signal, for example). """ def reader(f): """ Decorates methods reading a shared resource """ @wraps(f) def func_wrapper(self, *args, **kwargs): """ Wraps reading functions. """ <|code_end|> using the current file's imports: from functools import wraps from .exithandler import handle_exit from .lock import SWMR_SYNC and any relevant context from other files: # Path: hurray/swmr/exithandler.py # @contextlib.contextmanager # def handle_exit(callback=None, append=False): # """A context manager which properly handles SIGTERM and SIGINT # (KeyboardInterrupt) signals, registering a function which is # guaranteed to be called after signals are received. # Also, it makes sure to execute previously registered signal # handlers as well (if any). # # >>> app = App() # >>> with handle_exit(app.stop): # ... app.start() # ... # >>> # # If append == False raise RuntimeError if there's already a handler # registered for SIGTERM, otherwise both new and old handlers are # executed in this order. # """ # t = threading.current_thread() # if t.name != 'MainThread': # warnings.warn("!!! h5pySWMR warning: SIGTERM handling does not (yet) " # "work in a threaded environment. Locks may not be " # "released after process termination.", UserWarning) # yield # return # # old_handler = signal.signal(signal.SIGTERM, _sigterm_handler) # if old_handler != signal.SIG_DFL and old_handler != _sigterm_handler: # if not append: # raise RuntimeError("there is already a handler registered for " # "SIGTERM: %r" % old_handler) # # def handler(signum, frame): # try: # _sigterm_handler(signum, frame) # finally: # old_handler(signum, frame) # signal.signal(signal.SIGTERM, handler) # # if _sigterm_handler.__enter_ctx__: # raise RuntimeError("can't use nested contexts") # _sigterm_handler.__enter_ctx__ = True # # try: # yield # except KeyboardInterrupt: # pass # except SystemExit as err: # # code != 0 refers to an application error (e.g. explicit # # sys.exit('some error') call). # # We don't want that to pass silently. # # Nevertheless, the 'finally' clause below will always # # be executed. # if err.code != 0: # raise # finally: # _sigterm_handler.__enter_ctx__ = False # if callback is not None: # callback() # # Path: hurray/swmr/lock.py # SWMR_SYNC = start_sync_manager() . Output only the next line.
with handle_exit(append=True):
Given snippet: <|code_start|># (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Simple function wrappers for read and write operations using the configured strategy. The acquisition of the read and write locks (start_read, start_write) as well as the read and write operation itself _must_ be wrapped with try/finally. Otherwise the corresponding locks cannot be decremented/released if program execution ends, e.g., while performing a read or write operation (because of a SIGTERM signal, for example). """ def reader(f): """ Decorates methods reading a shared resource """ @wraps(f) def func_wrapper(self, *args, **kwargs): """ Wraps reading functions. """ with handle_exit(append=True): try: <|code_end|> , continue by predicting the next line. Consider current file imports: from functools import wraps from .exithandler import handle_exit from .lock import SWMR_SYNC and context: # Path: hurray/swmr/exithandler.py # @contextlib.contextmanager # def handle_exit(callback=None, append=False): # """A context manager which properly handles SIGTERM and SIGINT # (KeyboardInterrupt) signals, registering a function which is # guaranteed to be called after signals are received. # Also, it makes sure to execute previously registered signal # handlers as well (if any). # # >>> app = App() # >>> with handle_exit(app.stop): # ... app.start() # ... # >>> # # If append == False raise RuntimeError if there's already a handler # registered for SIGTERM, otherwise both new and old handlers are # executed in this order. # """ # t = threading.current_thread() # if t.name != 'MainThread': # warnings.warn("!!! h5pySWMR warning: SIGTERM handling does not (yet) " # "work in a threaded environment. Locks may not be " # "released after process termination.", UserWarning) # yield # return # # old_handler = signal.signal(signal.SIGTERM, _sigterm_handler) # if old_handler != signal.SIG_DFL and old_handler != _sigterm_handler: # if not append: # raise RuntimeError("there is already a handler registered for " # "SIGTERM: %r" % old_handler) # # def handler(signum, frame): # try: # _sigterm_handler(signum, frame) # finally: # old_handler(signum, frame) # signal.signal(signal.SIGTERM, handler) # # if _sigterm_handler.__enter_ctx__: # raise RuntimeError("can't use nested contexts") # _sigterm_handler.__enter_ctx__ = True # # try: # yield # except KeyboardInterrupt: # pass # except SystemExit as err: # # code != 0 refers to an application error (e.g. explicit # # sys.exit('some error') call). # # We don't want that to pass silently. # # Nevertheless, the 'finally' clause below will always # # be executed. # if err.code != 0: # raise # finally: # _sigterm_handler.__enter_ctx__ = False # if callback is not None: # callback() # # Path: hurray/swmr/lock.py # SWMR_SYNC = start_sync_manager() which might include code, classes, or functions. Output only the next line.
SWMR_SYNC.start_read(self.file)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # # Copyright 2009 Facebook # Modifications copyright 2016 Meteotest # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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 limitations # under the License. """Escaping/unescaping methods for HTML, JSON, URLs, and others. Also includes a few other miscellaneous string manipulation functions that have crept in over time. """ from __future__ import absolute_import, division, print_function, with_statement <|code_end|> with the help of current file imports: from hurray.server.util import PY3, unicode_type and context from other files: # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): , which may contain function names, class names, or code. Output only the next line.
if PY3:
Next line prediction: <|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 limitations # under the License. """Escaping/unescaping methods for HTML, JSON, URLs, and others. Also includes a few other miscellaneous string manipulation functions that have crept in over time. """ from __future__ import absolute_import, division, print_function, with_statement if PY3: unichr = chr _UTF8_TYPES = (bytes, type(None)) def utf8(value): # type: (typing.Union[bytes,unicode_type,None])->typing.Union[bytes,None] """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value <|code_end|> . Use current file imports: (from hurray.server.util import PY3, unicode_type) and context including class names, function names, or small code snippets from other files: # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): . Output only the next line.
if not isinstance(value, unicode_type):
Based on the snippet: <|code_start|>#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 django.setup() # pylint: disable=wrong-import-position def do_build_bulletin(bulletin_id): if bulletin_id == cavedb.utils.GLOBAL_BULLETIN_ID: <|code_end|> , predict the immediate next line with the help of imports: import sys import django import cavedb.utils from cavedb.generate_docs import write_global_bulletin_files from cavedb.generate_docs import write_bulletin_files from cavedb.generate_docs import run_buildscript and context (classes, functions, sometimes code) from other files: # Path: cavedb/generate_docs.py # def write_global_bulletin_files(): # outputter = cavedb.docgen_all.create_global_docgen_classes() # # outputter.open(None) # # outputter.indexed_terms([]) # # # No GIS section. Only write that on the bulletin. # # outputter.begin_regions([]) # # for bulletin in cavedb.models.Bulletin.objects.all(): # for region in cavedb.models.BulletinRegion.objects.filter(bulletin__id=bulletin.id): # write_region(region, outputter) # # outputter.end_regions() # # outputter.close() # # write_build_scripts(cavedb.utils.GLOBAL_BULLETIN_ID, outputter) # # Path: cavedb/generate_docs.py # def write_bulletin_files(bulletin): # outputter = cavedb.docgen_all.create_bulletin_docgen_classes(bulletin) # # all_regions_gis_hash = get_all_regions_gis_hash(bulletin.id) # # outputter.open(all_regions_gis_hash) # # outputter.indexed_terms(get_indexed_terms(bulletin)) # # write_gis_sections(bulletin.id, outputter) # # chapters = get_chapters_and_sections(bulletin.id) # # outputter.begin_regions(chapters) # # for region in cavedb.models.BulletinRegion.objects.filter(bulletin__id=bulletin.id): # write_region(region, outputter) # # outputter.end_regions() # # outputter.close() # # write_build_scripts(bulletin.id, outputter) # # Path: cavedb/generate_docs.py # def run_buildscript(bulletin_id): # build_script_file = cavedb.utils.get_build_script(bulletin_id) # # basedir = '%s/bulletins/bulletin_%s' % (settings.MEDIA_ROOT, bulletin_id) # os.chdir(basedir) # os.system('%s' % (build_script_file)) . Output only the next line.
write_global_bulletin_files()
Based on the snippet: <|code_start|>#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 django.setup() # pylint: disable=wrong-import-position def do_build_bulletin(bulletin_id): if bulletin_id == cavedb.utils.GLOBAL_BULLETIN_ID: write_global_bulletin_files() else: bulletin = cavedb.models.Bulletin.objects.get(pk=bulletin_id) if bulletin is None: print('Bulletin %s not found' % (bulletin_id)) sys.exit(1) <|code_end|> , predict the immediate next line with the help of imports: import sys import django import cavedb.utils from cavedb.generate_docs import write_global_bulletin_files from cavedb.generate_docs import write_bulletin_files from cavedb.generate_docs import run_buildscript and context (classes, functions, sometimes code) from other files: # Path: cavedb/generate_docs.py # def write_global_bulletin_files(): # outputter = cavedb.docgen_all.create_global_docgen_classes() # # outputter.open(None) # # outputter.indexed_terms([]) # # # No GIS section. Only write that on the bulletin. # # outputter.begin_regions([]) # # for bulletin in cavedb.models.Bulletin.objects.all(): # for region in cavedb.models.BulletinRegion.objects.filter(bulletin__id=bulletin.id): # write_region(region, outputter) # # outputter.end_regions() # # outputter.close() # # write_build_scripts(cavedb.utils.GLOBAL_BULLETIN_ID, outputter) # # Path: cavedb/generate_docs.py # def write_bulletin_files(bulletin): # outputter = cavedb.docgen_all.create_bulletin_docgen_classes(bulletin) # # all_regions_gis_hash = get_all_regions_gis_hash(bulletin.id) # # outputter.open(all_regions_gis_hash) # # outputter.indexed_terms(get_indexed_terms(bulletin)) # # write_gis_sections(bulletin.id, outputter) # # chapters = get_chapters_and_sections(bulletin.id) # # outputter.begin_regions(chapters) # # for region in cavedb.models.BulletinRegion.objects.filter(bulletin__id=bulletin.id): # write_region(region, outputter) # # outputter.end_regions() # # outputter.close() # # write_build_scripts(bulletin.id, outputter) # # Path: cavedb/generate_docs.py # def run_buildscript(bulletin_id): # build_script_file = cavedb.utils.get_build_script(bulletin_id) # # basedir = '%s/bulletins/bulletin_%s' % (settings.MEDIA_ROOT, bulletin_id) # os.chdir(basedir) # os.system('%s' % (build_script_file)) . Output only the next line.
write_bulletin_files(bulletin)
Next line prediction: <|code_start|>#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 django.setup() # pylint: disable=wrong-import-position def do_build_bulletin(bulletin_id): if bulletin_id == cavedb.utils.GLOBAL_BULLETIN_ID: write_global_bulletin_files() else: bulletin = cavedb.models.Bulletin.objects.get(pk=bulletin_id) if bulletin is None: print('Bulletin %s not found' % (bulletin_id)) sys.exit(1) write_bulletin_files(bulletin) <|code_end|> . Use current file imports: (import sys import django import cavedb.utils from cavedb.generate_docs import write_global_bulletin_files from cavedb.generate_docs import write_bulletin_files from cavedb.generate_docs import run_buildscript) and context including class names, function names, or small code snippets from other files: # Path: cavedb/generate_docs.py # def write_global_bulletin_files(): # outputter = cavedb.docgen_all.create_global_docgen_classes() # # outputter.open(None) # # outputter.indexed_terms([]) # # # No GIS section. Only write that on the bulletin. # # outputter.begin_regions([]) # # for bulletin in cavedb.models.Bulletin.objects.all(): # for region in cavedb.models.BulletinRegion.objects.filter(bulletin__id=bulletin.id): # write_region(region, outputter) # # outputter.end_regions() # # outputter.close() # # write_build_scripts(cavedb.utils.GLOBAL_BULLETIN_ID, outputter) # # Path: cavedb/generate_docs.py # def write_bulletin_files(bulletin): # outputter = cavedb.docgen_all.create_bulletin_docgen_classes(bulletin) # # all_regions_gis_hash = get_all_regions_gis_hash(bulletin.id) # # outputter.open(all_regions_gis_hash) # # outputter.indexed_terms(get_indexed_terms(bulletin)) # # write_gis_sections(bulletin.id, outputter) # # chapters = get_chapters_and_sections(bulletin.id) # # outputter.begin_regions(chapters) # # for region in cavedb.models.BulletinRegion.objects.filter(bulletin__id=bulletin.id): # write_region(region, outputter) # # outputter.end_regions() # # outputter.close() # # write_build_scripts(bulletin.id, outputter) # # Path: cavedb/generate_docs.py # def run_buildscript(bulletin_id): # build_script_file = cavedb.utils.get_build_script(bulletin_id) # # basedir = '%s/bulletins/bulletin_%s' % (settings.MEDIA_ROOT, bulletin_id) # os.chdir(basedir) # os.system('%s' % (build_script_file)) . Output only the next line.
run_buildscript(bulletin_id)
Given the following code snippet before the placeholder: <|code_start|> continue ret += '<a href="%s/region/%s/map/%s">%s %s</a><br/>\n' % \ (baseurl, region.id, gismap.name, gismap.name, region.region_name) ret += '<br/>\n' return ret show_maps.short_description = "GIS Maps" show_maps.allow_tags = True class Meta: ordering = ('bulletin_name',) # Restrict the list of choices to items that are underneath the current bulletin class BulletinChoice(models.ForeignKey): #pylint: disable=abstract-method def formfield(self, **kwargs): #pylint: disable=protected-access # The bulletin_id appears to be only available on the form. Since that # information is not available here, retrieve the bulletin_id from the # URL. regex = re.compile(r'.*?bulletin\\/(\d+)\\/') <|code_end|> , predict the next line using imports from the current file: import os import re import time import cavedb.docgen_all import cavedb.perms import cavedb.utils from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models from cavedb.middleware import get_request_uri, get_valid_bulletins and context including class names, function names, and sometimes code from other files: # Path: cavedb/middleware.py # def get_request_uri(): # return getattr(THREAD_LOCALS, 'request_uri', None) # # def get_valid_bulletins(): # return getattr(THREAD_LOCALS, 'valid_bulletins', []) . Output only the next line.
matches = regex.match(get_request_uri())
Given the following code snippet before the placeholder: <|code_start|> class BulletinRegion(models.Model): bulletin = models.ForeignKey(Bulletin) region_name = models.CharField(max_length=64) map_region_name = models.CharField(max_length=64, blank=True, null=True) introduction = models.TextField(blank=True, null=True) show_gis_map = models.BooleanField('Show GIS Map', null=False, default=True) sort_order = models.IntegerField() create_date = models.DateTimeField("Creation Date", auto_now_add=True, editable=False, \ null=True) mod_date = models.DateTimeField("Modification Date", auto_now=True, editable=False, null=True) def __str__(self): return '%s - %s' % (self.bulletin.short_name, self.region_name) class Meta: verbose_name = 'region' ordering = ('bulletin', 'region_name',) # Only show the user the regions that they are allowed to see. class RegionChoice(models.ForeignKey): #pylint: disable=abstract-method def formfield(self, **kwargs): #pylint: disable=protected-access return super(RegionChoice, self).formfield(queryset=self.rel.to._default_manager \ <|code_end|> , predict the next line using imports from the current file: import os import re import time import cavedb.docgen_all import cavedb.perms import cavedb.utils from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models from cavedb.middleware import get_request_uri, get_valid_bulletins and context including class names, function names, and sometimes code from other files: # Path: cavedb/middleware.py # def get_request_uri(): # return getattr(THREAD_LOCALS, 'request_uri', None) # # def get_valid_bulletins(): # return getattr(THREAD_LOCALS, 'valid_bulletins', []) . Output only the next line.
.complex_filter({'bulletin__id__in': get_valid_bulletins()}))
Predict the next line for this snippet: <|code_start|># SPDX-License-Identifier: Apache-2.0 class MapserverMapfile(cavedb.docgen_common.Common): def __init__(self, bulletin): cavedb.docgen_common.Common.__init__(self) self.bulletin = bulletin self.gis_maps = {} def gis_map(self, gismap): shpdir = cavedb.docgen_gis_common.get_bulletin_shp_directory(self.bulletin.id) gis_options = {} gis_options['basename'] = gismap.name <|code_end|> with the help of current file imports: from django.conf import settings from cavedb.docgen_gis_common import get_bulletin_mapserver_mapfile import cavedb.docgen_common import cavedb.docgen_gis_common import cavedb.utils and context from other files: # Path: cavedb/docgen_gis_common.py # def get_bulletin_mapserver_mapfile(bulletin_id, map_name): # return '%s/%s.map' % (get_bulletin_gis_maps_directory(bulletin_id), map_name) , which may contain function names, class names, or code. Output only the next line.
gis_options['path'] = get_bulletin_mapserver_mapfile(self.bulletin.id, gismap.name)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class TestFileBroker(fake_env.TestFakeFs): def test_pushpull1(self): fb = filebroker.FileBroker('bla', create = True) fb.push_metafile('citekey1', 'abc') fb.push_bibfile('citekey1', 'cdef') self.assertEqual(fb.pull_metafile('citekey1'), 'abc') self.assertEqual(fb.pull_bibfile('citekey1'), 'cdef') fb.push_bibfile('citekey1', 'ghi') self.assertEqual(fb.pull_bibfile('citekey1'), 'ghi') def test_existing_data(self): self.fs.add_real_directory(os.path.join(self.rootpath, 'testrepo'), read_only=False) fb = filebroker.FileBroker('testrepo', create = True) <|code_end|> . Write the next line using the current file imports: import unittest import os import dotdot import fake_env from pubs import content, filebroker and context from other files: # Path: pubs/content.py # class UnableToDecodeTextFile(Exception): # def __init__(self, path): # def __str__(self): # def _check_system_path_exists(path, fail=True): # def _check_system_path_is(nature, path, fail=True): # def system_path(path): # def _open(path, mode): # def check_file(path, fail=True): # def check_directory(path, fail=True): # def read_text_file(filepath, fail=True): # def read_binary_file(filepath, fail=True): # def remove_file(filepath): # def write_file(filepath, data, mode='w'): # def content_type(path): # def url_exists(url): # def check_content(path): # def _get_byte_url_content(path, ui=None): # def _dump_byte_url_content(source, target): # def get_content(path, ui=None): # def move_content(source, target, overwrite=False): # def copy_content(source, target, overwrite=False): # # Path: pubs/filebroker.py # META_EXT = '.yaml' # BIB_EXT = '.bib' # def filter_filename(filename, ext): # def __init__(self, directory, create=False): # def _create(self): # def bib_path(self, citekey): # def meta_path(self, citekey): # def pull_cachefile(self, filename): # def push_cachefile(self, filename, data): # def mtime_metafile(self, citekey): # def mtime_bibfile(self, citekey): # def pull_metafile(self, citekey): # def pull_bibfile(self, citekey): # def push_metafile(self, citekey, metadata): # def push_bibfile(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def listing(self, filestats=True): # def __init__(self, directory, scheme='docsdir', subdir='doc'): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # class FileBroker(object): # class DocBroker(object): , which may include functions, classes, or code. Output only the next line.
bib_content = content.read_text_file('testrepo/bib/Page99.bib')
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class TestTag(unittest.TestCase): def test_parse_tags(self): self.assertEqual(['+abc', '+def9'], _parse_tag_seq('abc+def9')) self.assertEqual(['+abc', '-def9'], _parse_tag_seq('abc-def9')) self.assertEqual(['-abc', '-def9'], _parse_tag_seq('-abc-def9')) self.assertEqual(['+abc', '-def9'], _parse_tag_seq('+abc-def9')) def test_tag_groups(self): self.assertEqual(({'math', 'romance'}, {'war'}), <|code_end|> . Write the next line using the current file imports: import unittest import dotdot from pubs.commands.tag_cmd import _parse_tag_seq, _tag_groups and context from other files: # Path: pubs/commands/tag_cmd.py # def _parse_tag_seq(s): # """Transform 'math-ai' in ['+math', '-ai']""" # tags = [] # if s[0] == ':': # s = '-' + s[1:] # if s[0] not in ['+', '-']: # s = '+' + s # last = 0 # for m in re.finditer(r'[+-]', s): # if m.start() == last: # if last != 0: # raise ValueError('could not match tag expression') # else: # tag = s[last:(m.start())] # if len(tag) > 0: # tags.append(s[last:(m.start())]) # last = m.start() # if last == len(s): # raise ValueError('could not match tag expression') # else: # tags.append(s[last:]) # return tags # # def _tag_groups(tags): # plus_tags, minus_tags = [], [] # for tag in tags: # if tag[0] == '+': # plus_tags.append(tag[1:]) # else: # assert tag[0] == '-' # minus_tags.append(tag[1:]) # return set(plus_tags), set(minus_tags) , which may include functions, classes, or code. Output only the next line.
_tag_groups(_parse_tag_seq('-war+math+romance')))
Here is a snippet: <|code_start|> from __future__ import unicode_literals class TestDOIStandardization(unittest.TestCase): def setUp(self): # some of these come from # https://stackoverflow.com/questions/27910/finding-a-doi-in-a-document-or-page self.crossref_dois = ( '10.2310/JIM.0b013e31820bab4c', '10.1007/978-3-642-28108-2_19', '10.1016/S0735-1097(98)00347-7', ) self.hard_dois = ( '10.1175/1520-0485(2002)032<0870:CT>2.0.CO;2', '10.1002/(SICI)1522-2594(199911)42:5<952::AID-MRM16>3.0.CO;2-S', '10.1579/0044-7447(2006)35\[89:RDUICP\]2.0.CO;2', ) self.currently_not_supported = ( '10.1007.10/978-3-642-28108-2_19', '10.1000.10/123456', '10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7', ) def test_http_dxdoi_org(self): doi = 'http://dx.doi.org/10.1109/5.771073' <|code_end|> . Write the next line using the current file imports: import unittest from pubs.utils import standardize_doi and context from other files: # Path: pubs/utils.py # def standardize_doi(doi): # """ # Given a putative doi, attempts to always return it in the form of # 10.XXXX/... Specifically designed to handle these cases: # - https://doi.org/<doi> # - http://doi.org/<doi> # - https://dx.doi.org/<doi> # - http://dx.doi.org/<doi> # - dx.doi.org/<doi> # - doi.org/<doi> # and attempts to verify doi adherence to DOI handbook standards and # crossref.org advice: # https://www.doi.org/doi_handbook/2_Numbering.html # https://www.crossref.org/blog/dois-and-matching-regular-expressions/ # # :returns standardized doi # """ # # doi_regexes = ( # r'(10\.\d{4,9}/[-._;()/:A-z0-9\>\<]+)', # r'(10.1002/[^\s]+)', # r'(10\.\d{4}/\d+-\d+X?(\d+)\d+<[\d\w]+:[\d\w]*>\d+.\d+.\w+;\d)', # r'(10\.1021/\w\w\d+\+)', # r'(10\.1207/[\w\d]+\&\d+_\d+)') # doi_pattern = re.compile('|'.join(doi_regexes)) # # match = doi_pattern.search(doi) # if not match: # raise ValueError("Not a valid doi: {}".format(doi)) # new_doi = match.group(0) # # return new_doi , which may include functions, classes, or code. Output only the next line.
sdoi = standardize_doi(doi)
Here is a snippet: <|code_start|> def push_metadata(self, key, meta): self.meta = meta def push_cache(name, entries): if name != 'metacache': raise AttributeError class FakeDataBrokerBib(object): bib = None def pull_bibentry(self, key): return self.bib def push_bibentry(self, key, bib): self.bib = bib def push_cache(name, entries): if name != 'bibcache': raise AttributeError class TestCacheEntrySet(unittest.TestCase): def setUp(self): self.databroker_meta = FakeDataBrokerMeta() self.databroker_meta.filebroker = FakeFileBrokerMeta() self.databroker_bib = FakeDataBrokerBib() self.databroker_bib.filebroker = FakeFileBrokerBib() <|code_end|> . Write the next line using the current file imports: import unittest import time import dotdot from pubs.datacache import CacheEntrySet and context from other files: # Path: pubs/datacache.py # class CacheEntrySet(object): # # def __init__(self, databroker, name): # self.databroker = databroker # self.name = name # if name == 'metacache': # self._pull_fun = databroker.pull_metadata # self._push_fun = databroker.push_metadata # self._mtime_fun = databroker.filebroker.mtime_metafile # elif name == 'bibcache': # self._pull_fun = databroker.pull_bibentry # self._push_fun = databroker.push_bibentry # self._mtime_fun = databroker.filebroker.mtime_bibfile # else: # raise ValueError # self._entries = None # self.modified = False # # does the filesystem supports subsecond stat time? # self.nsec_support = os.stat('.').st_mtime != int(os.stat('.').st_mtime) # # @property # def entries(self): # if self._entries is None: # self._entries = self._try_pull_cache() # return self._entries # # def flush(self, force=False): # if force or self.modified: # self.databroker.push_cache(self.name, self.entries) # self.modified = False # # def pull(self, citekey): # if self._is_outdated(citekey): # # if we get here, we must update the cache. # t = time.time() # data = self._pull_fun(citekey) # self.entries[citekey] = CacheEntry(data, t) # self.modified = True # return self.entries[citekey].data # # def push(self, citekey, data): # self._push_fun(citekey, data) # self.push_to_cache(citekey, data) # # def push_to_cache(self, citekey, data): # """Push to cash only.""" # mtime = self._mtime_fun(citekey) # self.entries[citekey] = CacheEntry(data, mtime) # self.modified = True # # def remove_from_cache(self, citekey): # """Removes from cache only.""" # if citekey in self.entries: # self.entries.pop(citekey) # self.modified = True # # def _try_pull_cache(self): # try: # return self.databroker.pull_cache(self.name) # except Exception: # take no prisonners; if something is wrong, no cache. # return {} # # def _is_outdated(self, citekey): # if citekey in self.entries: # mtime = self._mtime_fun(citekey) # boundary = mtime if self.nsec_support else mtime + 1 # return self.entries[citekey].timestamp < boundary # else: # return True , which may include functions, classes, or code. Output only the next line.
self.metacache = CacheEntrySet(self.databroker_meta, 'metacache')
Next line prediction: <|code_start|> def __init__(self, error_msg, bibdata): """ :param error_msg: specific message about what went wrong :param bibdata: the data that was unsuccessfully decoded. """ super(Exception, self).__init__(error_msg) # make `str(self)` work. self.data = bibdata bwriter = bp.bwriter.BibTexWriter() bwriter.display_order = BIBFIELD_ORDER def encode_metadata(self, metadata): return yaml.safe_dump(metadata, allow_unicode=True, encoding=None, indent=4) def decode_metadata(self, metadata_raw): return yaml.safe_load(metadata_raw) def encode_bibdata(self, bibdata, ignore_fields=[]): """Encode bibdata """ bpdata = bp.bibdatabase.BibDatabase() bpdata.entries = [self._entry_to_bp_entry(k, copy.copy(bibdata[k]), ignore_fields=ignore_fields) for k in bibdata] return self.bwriter.write(bpdata) def _entry_to_bp_entry(self, key, entry, ignore_fields=[]): """Convert back entries to the format expected by bibtexparser.""" entry[BP_ID_KEY] = key # Convert internal 'type' to bibtexparser entrytype key <|code_end|> . Use current file imports: (import copy import logging import pyparsing import bibtexparser import bibtexparser as bp import yaml from .bibstruct import TYPE_KEY) and context including class names, function names, or small code snippets from other files: # Path: pubs/bibstruct.py # TYPE_KEY = 'ENTRYTYPE' . Output only the next line.
entry[BP_ENTRYTYPE_KEY] = entry.pop(TYPE_KEY)
Predict the next line after this snippet: <|code_start|>def read_binary_file(filepath, fail=True): check_file(filepath, fail=fail) with _open(filepath, 'rb') as f: content = f.read() return content def remove_file(filepath): check_file(filepath) os.remove(filepath) def write_file(filepath, data, mode='w'): """Write data to file. Data should be unicode except when binary mode is selected, in which case data is expected to be binary. """ check_directory(os.path.dirname(filepath)) if 'b' not in mode and sys.version_info < (3,): # _open returns in binary mode for python2 # Data must be encoded data = data.encode('utf-8') with _open(filepath, mode) as f: f.write(data) # dealing with formatless content def content_type(path): <|code_end|> using the current file's imports: import sys import os import shutil from .p3 import urlparse, HTTPConnection, urlopen and any relevant context from other files: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): . Output only the next line.
parsed = urlparse(path)
Predict the next line after this snippet: <|code_start|> os.remove(filepath) def write_file(filepath, data, mode='w'): """Write data to file. Data should be unicode except when binary mode is selected, in which case data is expected to be binary. """ check_directory(os.path.dirname(filepath)) if 'b' not in mode and sys.version_info < (3,): # _open returns in binary mode for python2 # Data must be encoded data = data.encode('utf-8') with _open(filepath, mode) as f: f.write(data) # dealing with formatless content def content_type(path): parsed = urlparse(path) if parsed.scheme in ('http', 'https'): return 'url' else: return 'file' def url_exists(url): parsed = urlparse(url) <|code_end|> using the current file's imports: import sys import os import shutil from .p3 import urlparse, HTTPConnection, urlopen and any relevant context from other files: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): . Output only the next line.
conn = HTTPConnection(parsed.netloc)
Based on the snippet: <|code_start|> # dealing with formatless content def content_type(path): parsed = urlparse(path) if parsed.scheme in ('http', 'https'): return 'url' else: return 'file' def url_exists(url): parsed = urlparse(url) conn = HTTPConnection(parsed.netloc) conn.request('HEAD', parsed.path) response = conn.getresponse() conn.close() return response.status == 200 def check_content(path): if content_type(path) == 'url': return url_exists(path) else: return check_file(path) def _get_byte_url_content(path, ui=None): if ui is not None: ui.message('dowloading {}'.format(path)) <|code_end|> , predict the immediate next line with the help of imports: import sys import os import shutil from .p3 import urlparse, HTTPConnection, urlopen and context (classes, functions, sometimes code) from other files: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): . Output only the next line.
response = urlopen(path)
Given snippet: <|code_start|>from __future__ import unicode_literals # Citekey stuff TYPE_KEY = 'ENTRYTYPE' CONTROL_CHARS = ''.join(map(uchr, list(range(0, 32)) + list(range(127, 160)))) CITEKEY_FORBIDDEN_CHARS = '@\'\\,#}{~%/ ' # '/' is OK for bibtex but forbidden # here since we transform citekeys into filenames CITEKEY_EXCLUDE_RE = re.compile( '[%s]' % re.escape(CONTROL_CHARS + CITEKEY_FORBIDDEN_CHARS)) def str2citekey(s): <|code_end|> , continue by predicting the next line. Consider current file imports: import unicodedata import re from .p3 import ustr, uchr and context: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): which might include code, classes, or functions. Output only the next line.
key = unicodedata.normalize('NFKD', ustr(s)).encode('ascii', 'ignore').decode()
Given the following code snippet before the placeholder: <|code_start|> DFT_CONFIG_PATH = os.path.expanduser('~/.pubsrc') class ConfigurationNotFound(IOError): def __init__(self, path): super(ConfigurationNotFound, self).__init__( "No configuration found at path {}. Maybe you need to initialize " "your repository with `pubs init` or specify a --config argument." "".format(path)) def post_process_conf(conf): """Do some post processing on the configuration""" check_conf(conf) if conf['main']['docsdir'] == 'docsdir://': conf['main']['docsdir'] = os.path.join(conf['main']['pubsdir'], 'doc') return conf def load_default_conf(): """Load the default configuration""" <|code_end|> , predict the next line using imports from the current file: import os import platform import configobj import validate from .spec import configspec from .. import uis and context including class names, function names, and sometimes code from other files: # Path: pubs/config/spec.py . Output only the next line.
default_conf = configobj.ConfigObj(configspec=configspec)
Using the snippet: <|code_start|>from __future__ import unicode_literals def compare_yaml_str(s1, s2): if s1 == s2: return True else: y1 = yaml.safe_load(s1) y2 = yaml.safe_load(s2) return y1 == y2 class TestEnDecode(unittest.TestCase): def test_decode_emptystring(self): <|code_end|> , determine the next line of code. You have imports: import unittest import yaml import dotdot from pubs import endecoder from pubs.p3 import ustr from fixtures import dummy_metadata from str_fixtures import bibtex_raw0, metadata_raw0, turing_bib, bibtex_month and context (class names, function names, or code) available: # Path: pubs/endecoder.py # BP_ID_KEY = 'ID' # BP_ENTRYTYPE_KEY = 'ENTRYTYPE' # BP_ID_KEY = 'id' # BP_ENTRYTYPE_KEY = 'type' # BIBFIELD_ORDER = ['author', 'title', 'journal', 'institution', 'publisher', # 'year', 'month', 'number', 'volume', 'pages', 'url', 'link', # 'doi', 'note', 'abstract'] # def sanitize_citekey(record): # def customizations(record): # def __init__(self, error_msg, bibdata): # def encode_metadata(self, metadata): # def decode_metadata(self, metadata_raw): # def encode_bibdata(self, bibdata, ignore_fields=[]): # def _entry_to_bp_entry(self, key, entry, ignore_fields=[]): # def decode_bibdata(self, bibstr): # def _format_parsing_error(cls, e): # class EnDecoder(object): # class BibDecodingError(Exception): # # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): . Output only the next line.
decoder = endecoder.EnDecoder()
Given the code snippet: <|code_start|>from __future__ import unicode_literals def compare_yaml_str(s1, s2): if s1 == s2: return True else: y1 = yaml.safe_load(s1) y2 = yaml.safe_load(s2) return y1 == y2 class TestEnDecode(unittest.TestCase): def test_decode_emptystring(self): decoder = endecoder.EnDecoder() with self.assertRaises(decoder.BibDecodingError): decoder.decode_bibdata('') def test_encode_bibtex_is_unicode(self): decoder = endecoder.EnDecoder() entry = decoder.decode_bibdata(bibtex_raw0) bibraw = decoder.encode_bibdata(entry) <|code_end|> , generate the next line using the imports in this file: import unittest import yaml import dotdot from pubs import endecoder from pubs.p3 import ustr from fixtures import dummy_metadata from str_fixtures import bibtex_raw0, metadata_raw0, turing_bib, bibtex_month and context (functions, classes, or occasionally code) from other files: # Path: pubs/endecoder.py # BP_ID_KEY = 'ID' # BP_ENTRYTYPE_KEY = 'ENTRYTYPE' # BP_ID_KEY = 'id' # BP_ENTRYTYPE_KEY = 'type' # BIBFIELD_ORDER = ['author', 'title', 'journal', 'institution', 'publisher', # 'year', 'month', 'number', 'volume', 'pages', 'url', 'link', # 'doi', 'note', 'abstract'] # def sanitize_citekey(record): # def customizations(record): # def __init__(self, error_msg, bibdata): # def encode_metadata(self, metadata): # def decode_metadata(self, metadata_raw): # def encode_bibdata(self, bibdata, ignore_fields=[]): # def _entry_to_bp_entry(self, key, entry, ignore_fields=[]): # def decode_bibdata(self, bibstr): # def _format_parsing_error(cls, e): # class EnDecoder(object): # class BibDecodingError(Exception): # # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): . Output only the next line.
self.assertIsInstance(bibraw, ustr)
Given the code snippet: <|code_start|> return CommandAlias(name, definition, description) class CommandAlias(Alias): """Default kind of alias. - definition is used as a papers command - other arguments are passed to the command """ def command(self, conf, args): raw_args = ([args.prog] + shlex.split(self.definition + ' ' + ' '.join(args.arguments))) execute(raw_args) class ShellAlias(Alias): def command(self, conf, args): """Uses a shell function so that arguments can be used in the command as shell arguments. """ subprocess.call( 'pubs_alias_fun () {{\n{}\n}}\npubs_alias_fun {}'.format( self.definition, ' '.join([shell_quote(a) for a in args.arguments]) ), shell=True) <|code_end|> , generate the next line using the imports in this file: import shlex import subprocess import argparse from pipes import quote as shell_quote from ...plugins import PapersPlugin from ...pubs_cmd import execute and context (functions, classes, or occasionally code) from other files: # Path: pubs/plugins.py # class PapersPlugin(object): # """The base class for all plugins. Plugins provide # functionality by defining a subclass of PapersPlugin and overriding # the abstract methods defined here. # """ # # name = None # # def get_commands(self, subparsers, conf): # """Populates the parser with plugins specific command. # Returns iterable of pairs (command name, command function to call). # """ # return [] # # @classmethod # def get_instance(cls): # if cls in _instances: # return _instances[cls] # else: # raise RuntimeError("{} instance not created".format(cls.__name__)) # # @classmethod # def is_loaded(cls): # return cls in _instances # # Path: pubs/pubs_cmd.py # def execute(raw_args=sys.argv): # # try: # desc = 'Pubs: your bibliography on the command line.\nVisit https://github.com/pubs/pubs for more information.' # parser = p3.ArgumentParser(prog="pubs", add_help=False, description=desc) # parser.add_argument("-c", "--config", help="path to an alternate configuration file", # type=str, metavar="FILE") # parser.add_argument('--force-colors', dest='force_colors', # action='store_true', default=False, # help='colors are not disabled when piping to a file or other commands') # #parser.add_argument("-u", "--update", help="update config if needed", # # default=False, action='store_true') # top_args, remaining_args = parser.parse_known_args(raw_args[1:]) # # if top_args.config: # conf_path = top_args.config # else: # conf_path = config.get_confpath(verify=False) # will be checked on load # # # Loading config # try: # conf = config.load_conf(path=conf_path) # if update.update_check(conf, path=conf.filename): # # an update happened, reload conf. # conf = config.load_conf(path=conf_path) # except config.ConfigurationNotFound: # if (len(remaining_args) == 0 or remaining_args[0] == 'init' # or all(arg[0] == '-' for arg in remaining_args)): # only optional arguments # conf = config.load_default_conf() # conf.filename = conf_path # else: # raise # # uis.init_ui(conf, force_colors=top_args.force_colors) # ui = uis.get_ui() # # parser.add_argument('-v', '--version', action='version', version=__version__) # parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, # help='Show this help message and exit.') # subparsers = parser.add_subparsers(title="commands", dest="command") # # # Populate the parser with core commands # for cmd_name, cmd_mod in CORE_CMDS.items(): # cmd_parser = cmd_mod.parser(subparsers, conf) # cmd_parser.set_defaults(func=cmd_mod.command) # # # Extend with plugin commands # plugins.load_plugins(conf, ui) # for p in plugins.get_plugins().values(): # p.update_parser(subparsers, conf) # # # Eventually autocomplete # autocomplete(parser) # # # Parse and run appropriate command # # if no command, print help and exit peacefully (as '--help' does) # args = parser.parse_args(remaining_args) # if not args.command: # parser.print_help(file=sys.stderr) # sys.exit(2) # # events.PreCommandEvent().send() # args.prog = "pubs" # FIXME? # args.func(conf, args) # # except Exception as e: # if not uis.get_ui().handle_exception(e): # raise # finally: # events.PostCommandEvent().send() . Output only the next line.
class AliasPlugin(PapersPlugin):
Given the following code snippet before the placeholder: <|code_start|> def parser(self, parser): self.parser = parser p = parser.add_parser(self.name, help=self.description) p.add_argument('arguments', nargs=argparse.REMAINDER, help="arguments to be passed to %s" % self.name) return p def command(self, conf, args): raise NotImplementedError @classmethod def create_alias(cls, name, definition, description=None): if len(definition) > 0 and definition[0] == '!': return ShellAlias(name, definition[1:], description) else: return CommandAlias(name, definition, description) class CommandAlias(Alias): """Default kind of alias. - definition is used as a papers command - other arguments are passed to the command """ def command(self, conf, args): raw_args = ([args.prog] + shlex.split(self.definition + ' ' + ' '.join(args.arguments))) <|code_end|> , predict the next line using imports from the current file: import shlex import subprocess import argparse from pipes import quote as shell_quote from ...plugins import PapersPlugin from ...pubs_cmd import execute and context including class names, function names, and sometimes code from other files: # Path: pubs/plugins.py # class PapersPlugin(object): # """The base class for all plugins. Plugins provide # functionality by defining a subclass of PapersPlugin and overriding # the abstract methods defined here. # """ # # name = None # # def get_commands(self, subparsers, conf): # """Populates the parser with plugins specific command. # Returns iterable of pairs (command name, command function to call). # """ # return [] # # @classmethod # def get_instance(cls): # if cls in _instances: # return _instances[cls] # else: # raise RuntimeError("{} instance not created".format(cls.__name__)) # # @classmethod # def is_loaded(cls): # return cls in _instances # # Path: pubs/pubs_cmd.py # def execute(raw_args=sys.argv): # # try: # desc = 'Pubs: your bibliography on the command line.\nVisit https://github.com/pubs/pubs for more information.' # parser = p3.ArgumentParser(prog="pubs", add_help=False, description=desc) # parser.add_argument("-c", "--config", help="path to an alternate configuration file", # type=str, metavar="FILE") # parser.add_argument('--force-colors', dest='force_colors', # action='store_true', default=False, # help='colors are not disabled when piping to a file or other commands') # #parser.add_argument("-u", "--update", help="update config if needed", # # default=False, action='store_true') # top_args, remaining_args = parser.parse_known_args(raw_args[1:]) # # if top_args.config: # conf_path = top_args.config # else: # conf_path = config.get_confpath(verify=False) # will be checked on load # # # Loading config # try: # conf = config.load_conf(path=conf_path) # if update.update_check(conf, path=conf.filename): # # an update happened, reload conf. # conf = config.load_conf(path=conf_path) # except config.ConfigurationNotFound: # if (len(remaining_args) == 0 or remaining_args[0] == 'init' # or all(arg[0] == '-' for arg in remaining_args)): # only optional arguments # conf = config.load_default_conf() # conf.filename = conf_path # else: # raise # # uis.init_ui(conf, force_colors=top_args.force_colors) # ui = uis.get_ui() # # parser.add_argument('-v', '--version', action='version', version=__version__) # parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, # help='Show this help message and exit.') # subparsers = parser.add_subparsers(title="commands", dest="command") # # # Populate the parser with core commands # for cmd_name, cmd_mod in CORE_CMDS.items(): # cmd_parser = cmd_mod.parser(subparsers, conf) # cmd_parser.set_defaults(func=cmd_mod.command) # # # Extend with plugin commands # plugins.load_plugins(conf, ui) # for p in plugins.get_plugins().values(): # p.update_parser(subparsers, conf) # # # Eventually autocomplete # autocomplete(parser) # # # Parse and run appropriate command # # if no command, print help and exit peacefully (as '--help' does) # args = parser.parse_args(remaining_args) # if not args.command: # parser.print_help(file=sys.stderr) # sys.exit(2) # # events.PreCommandEvent().send() # args.prog = "pubs" # FIXME? # args.func(conf, args) # # except Exception as e: # if not uis.get_ui().handle_exception(e): # raise # finally: # events.PostCommandEvent().send() . Output only the next line.
execute(raw_args)
Given the code snippet: <|code_start|> # code for fake fs real_os = os real_os_path = os.path real_open = open real_shutil = shutil real_glob = glob real_io = io original_exception_handler = uis.InputUI.handle_exception # needed to get locale.getpreferredencoding(False) (invoked by pyfakefs) # to work properly locale.setlocale(locale.LC_ALL, '') # Test helpers # automating input <|code_end|> , generate the next line using the imports in this file: import sys import io import os import shutil import glob import locale import dotdot from pyfakefs import fake_filesystem, fake_filesystem_unittest from pubs.p3 import input from pubs import content, filebroker, uis and context (functions, classes, or occasionally code) from other files: # Path: pubs/p3.py # def input(): # return raw_input().decode(sys.stdin.encoding or 'utf8', 'ignore') # # Path: pubs/content.py # class UnableToDecodeTextFile(Exception): # def __init__(self, path): # def __str__(self): # def _check_system_path_exists(path, fail=True): # def _check_system_path_is(nature, path, fail=True): # def system_path(path): # def _open(path, mode): # def check_file(path, fail=True): # def check_directory(path, fail=True): # def read_text_file(filepath, fail=True): # def read_binary_file(filepath, fail=True): # def remove_file(filepath): # def write_file(filepath, data, mode='w'): # def content_type(path): # def url_exists(url): # def check_content(path): # def _get_byte_url_content(path, ui=None): # def _dump_byte_url_content(source, target): # def get_content(path, ui=None): # def move_content(source, target, overwrite=False): # def copy_content(source, target, overwrite=False): # # Path: pubs/filebroker.py # META_EXT = '.yaml' # BIB_EXT = '.bib' # def filter_filename(filename, ext): # def __init__(self, directory, create=False): # def _create(self): # def bib_path(self, citekey): # def meta_path(self, citekey): # def pull_cachefile(self, filename): # def push_cachefile(self, filename, data): # def mtime_metafile(self, citekey): # def mtime_bibfile(self, citekey): # def pull_metafile(self, citekey): # def pull_bibfile(self, citekey): # def push_metafile(self, citekey, metadata): # def push_bibfile(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def listing(self, filestats=True): # def __init__(self, directory, scheme='docsdir', subdir='doc'): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # class FileBroker(object): # class DocBroker(object): # # Path: pubs/uis.py # DEBUG = False # unhandled exceptions traces are printed # DEBUG_ALL_TRACES = False # handled exceptions traces are printed # def _get_encoding(conf): # def _get_local_editor(): # def get_ui(): # def init_ui(conf, force_colors=False): # def __init__(self, conf, force_colors=False): # def message(self, *messages, **kwargs): # def info(self, message, **kwargs): # def warning(self, message, **kwargs): # def error(self, message, **kwargs): # def exit(self, error_code=1): # def handle_exception(self, exc): # def test_handle_exception(self, exc): # def __init__(self, conf, force_colors=False): # def input(self): # def input_choice_ng(self, options, option_chars=None, default=None, question=''): # def input_choice(self, options, option_chars, default=None, question=''): # def input_yn(self, question='', default='y'): # def editor_input(self, initial="", suffix='.tmp'): # def edit_file(self, path, temporary): # def _call_editor(self, path): # class PrintUI(object): # class InputUI(PrintUI): . Output only the next line.
real_input = input
Predict the next line for this snippet: <|code_start|> input() returns 'yes' input() returns 'no' input() raises IndexError """ class UnexpectedInput(Exception): pass def __init__(self, inputs, module_list=tuple()): self.inputs = list(inputs) or [] self.module_list = module_list self._cursor = 0 self._original_handler = None def as_global(self): for md in self.module_list: md.input = self if md.__name__ == 'pubs.uis': md.InputUI.editor_input = self md.InputUI.edit_file = self.input_to_file # Do not catch UnexpectedInput def handler(ui, exc): if isinstance(exc, self.UnexpectedInput): raise else: original_exception_handler(ui, exc) md.InputUI.handle_exception = handler def input_to_file(self, path_to_file, temporary=True): <|code_end|> with the help of current file imports: import sys import io import os import shutil import glob import locale import dotdot from pyfakefs import fake_filesystem, fake_filesystem_unittest from pubs.p3 import input from pubs import content, filebroker, uis and context from other files: # Path: pubs/p3.py # def input(): # return raw_input().decode(sys.stdin.encoding or 'utf8', 'ignore') # # Path: pubs/content.py # class UnableToDecodeTextFile(Exception): # def __init__(self, path): # def __str__(self): # def _check_system_path_exists(path, fail=True): # def _check_system_path_is(nature, path, fail=True): # def system_path(path): # def _open(path, mode): # def check_file(path, fail=True): # def check_directory(path, fail=True): # def read_text_file(filepath, fail=True): # def read_binary_file(filepath, fail=True): # def remove_file(filepath): # def write_file(filepath, data, mode='w'): # def content_type(path): # def url_exists(url): # def check_content(path): # def _get_byte_url_content(path, ui=None): # def _dump_byte_url_content(source, target): # def get_content(path, ui=None): # def move_content(source, target, overwrite=False): # def copy_content(source, target, overwrite=False): # # Path: pubs/filebroker.py # META_EXT = '.yaml' # BIB_EXT = '.bib' # def filter_filename(filename, ext): # def __init__(self, directory, create=False): # def _create(self): # def bib_path(self, citekey): # def meta_path(self, citekey): # def pull_cachefile(self, filename): # def push_cachefile(self, filename, data): # def mtime_metafile(self, citekey): # def mtime_bibfile(self, citekey): # def pull_metafile(self, citekey): # def pull_bibfile(self, citekey): # def push_metafile(self, citekey, metadata): # def push_bibfile(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def listing(self, filestats=True): # def __init__(self, directory, scheme='docsdir', subdir='doc'): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # class FileBroker(object): # class DocBroker(object): # # Path: pubs/uis.py # DEBUG = False # unhandled exceptions traces are printed # DEBUG_ALL_TRACES = False # handled exceptions traces are printed # def _get_encoding(conf): # def _get_local_editor(): # def get_ui(): # def init_ui(conf, force_colors=False): # def __init__(self, conf, force_colors=False): # def message(self, *messages, **kwargs): # def info(self, message, **kwargs): # def warning(self, message, **kwargs): # def error(self, message, **kwargs): # def exit(self, error_code=1): # def handle_exception(self, exc): # def test_handle_exception(self, exc): # def __init__(self, conf, force_colors=False): # def input(self): # def input_choice_ng(self, options, option_chars=None, default=None, question=''): # def input_choice(self, options, option_chars, default=None, question=''): # def input_yn(self, question='', default='y'): # def editor_input(self, initial="", suffix='.tmp'): # def edit_file(self, path, temporary): # def _call_editor(self, path): # class PrintUI(object): # class InputUI(PrintUI): , which may contain function names, class names, or code. Output only the next line.
content.write_file(path_to_file, self())
Given the code snippet: <|code_start|> # code for fake fs real_os = os real_os_path = os.path real_open = open real_shutil = shutil real_glob = glob real_io = io <|code_end|> , generate the next line using the imports in this file: import sys import io import os import shutil import glob import locale import dotdot from pyfakefs import fake_filesystem, fake_filesystem_unittest from pubs.p3 import input from pubs import content, filebroker, uis and context (functions, classes, or occasionally code) from other files: # Path: pubs/p3.py # def input(): # return raw_input().decode(sys.stdin.encoding or 'utf8', 'ignore') # # Path: pubs/content.py # class UnableToDecodeTextFile(Exception): # def __init__(self, path): # def __str__(self): # def _check_system_path_exists(path, fail=True): # def _check_system_path_is(nature, path, fail=True): # def system_path(path): # def _open(path, mode): # def check_file(path, fail=True): # def check_directory(path, fail=True): # def read_text_file(filepath, fail=True): # def read_binary_file(filepath, fail=True): # def remove_file(filepath): # def write_file(filepath, data, mode='w'): # def content_type(path): # def url_exists(url): # def check_content(path): # def _get_byte_url_content(path, ui=None): # def _dump_byte_url_content(source, target): # def get_content(path, ui=None): # def move_content(source, target, overwrite=False): # def copy_content(source, target, overwrite=False): # # Path: pubs/filebroker.py # META_EXT = '.yaml' # BIB_EXT = '.bib' # def filter_filename(filename, ext): # def __init__(self, directory, create=False): # def _create(self): # def bib_path(self, citekey): # def meta_path(self, citekey): # def pull_cachefile(self, filename): # def push_cachefile(self, filename, data): # def mtime_metafile(self, citekey): # def mtime_bibfile(self, citekey): # def pull_metafile(self, citekey): # def pull_bibfile(self, citekey): # def push_metafile(self, citekey, metadata): # def push_bibfile(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def listing(self, filestats=True): # def __init__(self, directory, scheme='docsdir', subdir='doc'): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # class FileBroker(object): # class DocBroker(object): # # Path: pubs/uis.py # DEBUG = False # unhandled exceptions traces are printed # DEBUG_ALL_TRACES = False # handled exceptions traces are printed # def _get_encoding(conf): # def _get_local_editor(): # def get_ui(): # def init_ui(conf, force_colors=False): # def __init__(self, conf, force_colors=False): # def message(self, *messages, **kwargs): # def info(self, message, **kwargs): # def warning(self, message, **kwargs): # def error(self, message, **kwargs): # def exit(self, error_code=1): # def handle_exception(self, exc): # def test_handle_exception(self, exc): # def __init__(self, conf, force_colors=False): # def input(self): # def input_choice_ng(self, options, option_chars=None, default=None, question=''): # def input_choice(self, options, option_chars, default=None, question=''): # def input_yn(self, question='', default='y'): # def editor_input(self, initial="", suffix='.tmp'): # def edit_file(self, path, temporary): # def _call_editor(self, path): # class PrintUI(object): # class InputUI(PrintUI): . Output only the next line.
original_exception_handler = uis.InputUI.handle_exception
Here is a snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals class APITests(unittest.TestCase): @mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get) def test_readme(self, reqget): apis.doi2bibtex('10.1007/s00422-012-0514-6') apis.isbn2bibtex('978-0822324669') apis.arxiv2bibtex('math/9501234') class TestDOI2Bibtex(APITests): @mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get) def test_unicode(self, reqget): bib = apis.doi2bibtex('10.1007/BF01700692') <|code_end|> . Write the next line using the current file imports: import unittest import mock import dotdot import mock_requests from pubs.p3 import ustr from pubs import apis from pubs.apis import _is_arxiv_oldstyle, _extract_arxiv_id and context from other files: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): # # Path: pubs/apis.py # class ReferenceNotFoundError(Exception): # def get_bibentry_from_api(id_str, id_type, try_doi=True, ui=None, raw=False): # def _get_request(url, headers=None): # def doi2bibtex(doi, **kwargs): # def isbn2bibtex(isbn, **kwargs): # def _is_arxiv_oldstyle(arxiv_id): # def _extract_arxiv_id(entry): # def arxiv2bibtex(arxiv_id, try_doi=True, ui=None): # # Path: pubs/apis.py # def _is_arxiv_oldstyle(arxiv_id): # return re.match(r"(arxiv\:)?[a-z\-]+\/[0-9]+(v[0-9]+)?", arxiv_id.lower()) is not None # # def _extract_arxiv_id(entry): # pattern = r"http[s]?://arxiv.org/abs/(?P<entry_id>.+)" # return re.search(pattern, entry['id']).groupdict()['entry_id'] , which may include functions, classes, or code. Output only the next line.
self.assertIsInstance(bib, ustr)
Given snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals class APITests(unittest.TestCase): @mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get) def test_readme(self, reqget): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import mock import dotdot import mock_requests from pubs.p3 import ustr from pubs import apis from pubs.apis import _is_arxiv_oldstyle, _extract_arxiv_id and context: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): # # Path: pubs/apis.py # class ReferenceNotFoundError(Exception): # def get_bibentry_from_api(id_str, id_type, try_doi=True, ui=None, raw=False): # def _get_request(url, headers=None): # def doi2bibtex(doi, **kwargs): # def isbn2bibtex(isbn, **kwargs): # def _is_arxiv_oldstyle(arxiv_id): # def _extract_arxiv_id(entry): # def arxiv2bibtex(arxiv_id, try_doi=True, ui=None): # # Path: pubs/apis.py # def _is_arxiv_oldstyle(arxiv_id): # return re.match(r"(arxiv\:)?[a-z\-]+\/[0-9]+(v[0-9]+)?", arxiv_id.lower()) is not None # # def _extract_arxiv_id(entry): # pattern = r"http[s]?://arxiv.org/abs/(?P<entry_id>.+)" # return re.search(pattern, entry['id']).groupdict()['entry_id'] which might include code, classes, or functions. Output only the next line.
apis.doi2bibtex('10.1007/s00422-012-0514-6')
Given the code snippet: <|code_start|> bib = apis.get_bibentry_from_api('1312.2021', 'arXiv') entry = bib[list(bib)[0]] self.assertEqual(entry['arxiv_doi'], '10.1103/INVALIDDOI.89.084044') @mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get) def test_arxiv_good_doi(self, reqget): """Get the DOI bibtex instead of the arXiv one if possible""" bib = apis.get_bibentry_from_api('1710.08557', 'arXiv') entry = bib[list(bib)[0]] self.assertTrue(not 'arxiv_doi' in entry) self.assertEqual(entry['doi'], '10.1186/s12984-017-0305-3') self.assertEqual(entry['title'].lower(), 'on neuromechanical approaches for the study of biological and robotic grasp and manipulation') @mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get) def test_arxiv_good_doi_force_arxiv(self, reqget): bib = apis.get_bibentry_from_api('1710.08557', 'arXiv', try_doi=False) entry = bib[list(bib)[0]] self.assertEqual(entry['arxiv_doi'], '10.1186/s12984-017-0305-3') self.assertEqual(entry['title'].lower(), 'on neuromechanical approaches for the study of biological grasp and\nmanipulation') class TestArxiv2BibtexLocal(unittest.TestCase): """Test arXiv 2 Bibtex connection; those tests don't require a connection""" def test_oldstyle_pattern(self): """Test that we can accurately differentiate between old and new style arXiv ids.""" # old-style arXiv ids for arxiv_id in ['cs/9301113', 'math/9201277v3', 'astro-ph/9812133', 'cond-mat/0604612', 'hep-ph/0702007v10', 'arXiv:physics/9403001' ]: <|code_end|> , generate the next line using the imports in this file: import unittest import mock import dotdot import mock_requests from pubs.p3 import ustr from pubs import apis from pubs.apis import _is_arxiv_oldstyle, _extract_arxiv_id and context (functions, classes, or occasionally code) from other files: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): # # Path: pubs/apis.py # class ReferenceNotFoundError(Exception): # def get_bibentry_from_api(id_str, id_type, try_doi=True, ui=None, raw=False): # def _get_request(url, headers=None): # def doi2bibtex(doi, **kwargs): # def isbn2bibtex(isbn, **kwargs): # def _is_arxiv_oldstyle(arxiv_id): # def _extract_arxiv_id(entry): # def arxiv2bibtex(arxiv_id, try_doi=True, ui=None): # # Path: pubs/apis.py # def _is_arxiv_oldstyle(arxiv_id): # return re.match(r"(arxiv\:)?[a-z\-]+\/[0-9]+(v[0-9]+)?", arxiv_id.lower()) is not None # # def _extract_arxiv_id(entry): # pattern = r"http[s]?://arxiv.org/abs/(?P<entry_id>.+)" # return re.search(pattern, entry['id']).groupdict()['entry_id'] . Output only the next line.
self.assertTrue(_is_arxiv_oldstyle(arxiv_id))
Given the code snippet: <|code_start|> entry = bib[list(bib)[0]] self.assertTrue(not 'arxiv_doi' in entry) self.assertEqual(entry['doi'], '10.1186/s12984-017-0305-3') self.assertEqual(entry['title'].lower(), 'on neuromechanical approaches for the study of biological and robotic grasp and manipulation') @mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get) def test_arxiv_good_doi_force_arxiv(self, reqget): bib = apis.get_bibentry_from_api('1710.08557', 'arXiv', try_doi=False) entry = bib[list(bib)[0]] self.assertEqual(entry['arxiv_doi'], '10.1186/s12984-017-0305-3') self.assertEqual(entry['title'].lower(), 'on neuromechanical approaches for the study of biological grasp and\nmanipulation') class TestArxiv2BibtexLocal(unittest.TestCase): """Test arXiv 2 Bibtex connection; those tests don't require a connection""" def test_oldstyle_pattern(self): """Test that we can accurately differentiate between old and new style arXiv ids.""" # old-style arXiv ids for arxiv_id in ['cs/9301113', 'math/9201277v3', 'astro-ph/9812133', 'cond-mat/0604612', 'hep-ph/0702007v10', 'arXiv:physics/9403001' ]: self.assertTrue(_is_arxiv_oldstyle(arxiv_id)) # new-style arXiv ids for arxiv_id in ['1808.00954', 'arXiv:1808.00953', '1808.0953', '1808.00954v1', 'arXiv:1808.00953v2', '1808.0953v42']: self.assertFalse(_is_arxiv_oldstyle(arxiv_id)) def test_extract_id(self): """Test that ids are correctly extracted""" <|code_end|> , generate the next line using the imports in this file: import unittest import mock import dotdot import mock_requests from pubs.p3 import ustr from pubs import apis from pubs.apis import _is_arxiv_oldstyle, _extract_arxiv_id and context (functions, classes, or occasionally code) from other files: # Path: pubs/p3.py # def input(): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _get_fake_stdio_ucontent(stdio): # def _print_message(self, message, file=None): # def _get_raw_stdout(): # def _get_raw_stderr(): # def u_maybe(s): # def __init__(self, *args, **kwargs): # def write(self, s): # def _fake_stdio(additional_out=False): # def _get_fake_stdio_ucontent(stdio): # def isbasestr(obj): # class StdIO(io.BytesIO): # class ArgumentParser(argparse.ArgumentParser): # class StdIO(io.BytesIO): # # Path: pubs/apis.py # class ReferenceNotFoundError(Exception): # def get_bibentry_from_api(id_str, id_type, try_doi=True, ui=None, raw=False): # def _get_request(url, headers=None): # def doi2bibtex(doi, **kwargs): # def isbn2bibtex(isbn, **kwargs): # def _is_arxiv_oldstyle(arxiv_id): # def _extract_arxiv_id(entry): # def arxiv2bibtex(arxiv_id, try_doi=True, ui=None): # # Path: pubs/apis.py # def _is_arxiv_oldstyle(arxiv_id): # return re.match(r"(arxiv\:)?[a-z\-]+\/[0-9]+(v[0-9]+)?", arxiv_id.lower()) is not None # # def _extract_arxiv_id(entry): # pattern = r"http[s]?://arxiv.org/abs/(?P<entry_id>.+)" # return re.search(pattern, entry['id']).groupdict()['entry_id'] . Output only the next line.
self.assertEqual(_extract_arxiv_id({'id': "http://arxiv.org/abs/0704.0010v1"}), "0704.0010v1")
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class TestGenerateCitekey(unittest.TestCase): def test_fails_on_empty_paper(self): with self.assertRaises(ValueError): <|code_end|> , predict the next line using imports from the current file: import unittest import copy import dotdot import fixtures from pubs import bibstruct and context including class names, function names, and sometimes code from other files: # Path: pubs/bibstruct.py # TYPE_KEY = 'ENTRYTYPE' # CONTROL_CHARS = ''.join(map(uchr, list(range(0, 32)) + list(range(127, 160)))) # CITEKEY_FORBIDDEN_CHARS = '@\'\\,#}{~%/ ' # '/' is OK for bibtex but forbidden # CITEKEY_EXCLUDE_RE = re.compile( # '[%s]' % re.escape(CONTROL_CHARS + CITEKEY_FORBIDDEN_CHARS)) # def str2citekey(s): # def check_citekey(citekey): # def verify_bibdata(bibdata): # def get_entry(bibdata): # def extract_citekey(bibdata): # def author_last(author_str): # def valid_citekey(citekey): # def generate_citekey(bibdata): # def extract_docfile(bibdata, remove=False): . Output only the next line.
bibstruct.generate_citekey(None)
Continue the code snippet: <|code_start|> def perf_color(): s = str(list(range(1000))) for _ in range(5000000): <|code_end|> . Use current file imports: import dotdot from pubs import color and context (classes, functions, or code) from other files: # Path: pubs/color.py # COLOR_LIST = {'black': '0', 'red': '1', 'green': '2', 'yellow': '3', 'blue': '4', # 'magenta': '5', 'cyan': '6', 'grey': '7', # 'brightblack': '8', 'brightred': '9', 'brightgreen': '10', # 'brightyellow': '11', 'brightblue': '12', 'brightmagenta': '13', # 'brightcyan': '14', 'brightgrey': '15', # 'darkgrey': '8', # == brightblack # 'gray': '7', 'darkgray': '8', 'brightgray': '15', # gray/grey spelling # 'purple': '5', # for compatibility reasons # 'white': '15' # == brightgrey # } # COLORS_OUT = generate_colors(sys.stdout, color=False, bold=False, italic=False) # COLORS_ERR = generate_colors(sys.stderr, color=False, bold=False, italic=False) # COLORS_OUT = generate_colors(sys.stdout, force_colors=force_colors, # color =conf['formating']['color'], # bold =conf['formating']['bold'], # italic=conf['formating']['italics']) # COLORS_ERR = generate_colors(sys.stderr, force_colors=force_colors, # color =conf['formating']['color'], # bold =conf['formating']['bold'], # italic=conf['formating']['italics']) # def _color_supported(stream, force=False): # def generate_colors(stream, color=True, bold=True, italic=True, force_colors=False): # def dye_out(s, color='end'): # def dye_err(s, color='end'): # def setup(conf, force_colors=False): # def undye(s): . Output only the next line.
color.dye_out(s, 'red')
Continue the code snippet: <|code_start|> for key in pulled.keys(): self.assertEqual(pulled[key], page99_bibentry['Page99'][key]) self.assertEqual(db.pull_bibentry('citekey1'), page99_bibentry) def test_existing_data(self): ende = endecoder.EnDecoder() page99_bibentry = ende.decode_bibdata(str_fixtures.bibtex_raw0) for db_class in [databroker.DataBroker, datacache.DataCache]: self.reset_fs() self.fs.add_real_directory(os.path.join(self.rootpath, 'testrepo'), read_only=False) db = db_class('testrepo', 'testrepo/doc', create=False) self.assertEqual(db.pull_bibentry('Page99'), page99_bibentry) for citekey in ['10.1371_journal.pone.0038236', '10.1371journal.pone.0063400', 'journal0063400']: db.pull_bibentry(citekey) db.pull_metadata(citekey) with self.assertRaises(IOError): db.pull_bibentry('citekey') with self.assertRaises(IOError): db.pull_metadata('citekey') db.add_doc('Larry99', 'docsdir://Page99.pdf') <|code_end|> . Use current file imports: import unittest import os import dotdot import fake_env import str_fixtures from pubs import content, databroker, datacache from pubs import endecoder and context (classes, functions, or code) from other files: # Path: pubs/content.py # class UnableToDecodeTextFile(Exception): # def __init__(self, path): # def __str__(self): # def _check_system_path_exists(path, fail=True): # def _check_system_path_is(nature, path, fail=True): # def system_path(path): # def _open(path, mode): # def check_file(path, fail=True): # def check_directory(path, fail=True): # def read_text_file(filepath, fail=True): # def read_binary_file(filepath, fail=True): # def remove_file(filepath): # def write_file(filepath, data, mode='w'): # def content_type(path): # def url_exists(url): # def check_content(path): # def _get_byte_url_content(path, ui=None): # def _dump_byte_url_content(source, target): # def get_content(path, ui=None): # def move_content(source, target, overwrite=False): # def copy_content(source, target, overwrite=False): # # Path: pubs/databroker.py # class DataBroker(object): # def __init__(self, pubsdir, docsdir, create=False): # def close(self): # def pull_cache(self, name): # def push_cache(self, name, data): # def pull_metadata(self, citekey): # def pull_bibentry(self, citekey): # def push_metadata(self, citekey, metadata): # def push_bibentry(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def citekeys(self): # def listing(self, filestats=True): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # def _notepath(self, citekey, extension): # def real_notepath(self, citekey, extension): # def remove_note(self, citekey, extension, silent=True): # def rename_note(self, old_citekey, new_citekey, extension): # # Path: pubs/datacache.py # class CacheEntry(object): # class CacheEntrySet(object): # class DataCache(object): # def __init__(self, data, timestamp): # def __init__(self, databroker, name): # def entries(self): # def flush(self, force=False): # def pull(self, citekey): # def push(self, citekey, data): # def push_to_cache(self, citekey, data): # def remove_from_cache(self, citekey): # def _try_pull_cache(self): # def _is_outdated(self, citekey): # def __init__(self, pubsdir, docsdir, create=False): # def close(self): # def databroker(self): # def metacache(self): # def bibcache(self): # def _create(self): # def flush_cache(self, force=False): # def pull_metadata(self, citekey): # def pull_bibentry(self, citekey): # def push_metadata(self, citekey, metadata): # def push_bibentry(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def citekeys(self): # def listing(self, filestats=True): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # def real_notepath(self, citekey, extension): # def remove_note(self, citekey, extension, silent=True): # def rename_note(self, old_citekey, new_citekey, extension): # # Path: pubs/endecoder.py # BP_ID_KEY = 'ID' # BP_ENTRYTYPE_KEY = 'ENTRYTYPE' # BP_ID_KEY = 'id' # BP_ENTRYTYPE_KEY = 'type' # BIBFIELD_ORDER = ['author', 'title', 'journal', 'institution', 'publisher', # 'year', 'month', 'number', 'volume', 'pages', 'url', 'link', # 'doi', 'note', 'abstract'] # def sanitize_citekey(record): # def customizations(record): # def __init__(self, error_msg, bibdata): # def encode_metadata(self, metadata): # def decode_metadata(self, metadata_raw): # def encode_bibdata(self, bibdata, ignore_fields=[]): # def _entry_to_bp_entry(self, key, entry, ignore_fields=[]): # def decode_bibdata(self, bibstr): # def _format_parsing_error(cls, e): # class EnDecoder(object): # class BibDecodingError(Exception): . Output only the next line.
self.assertTrue(content.check_file('testrepo/doc/Page99.pdf', fail=False))
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class TestDataBroker(fake_env.TestFakeFs): def test_databroker(self): ende = endecoder.EnDecoder() page99_metadata = ende.decode_metadata(str_fixtures.metadata_raw0) page99_bibentry = ende.decode_bibdata(str_fixtures.bibtex_raw0) <|code_end|> . Use current file imports: import unittest import os import dotdot import fake_env import str_fixtures from pubs import content, databroker, datacache from pubs import endecoder and context (classes, functions, or code) from other files: # Path: pubs/content.py # class UnableToDecodeTextFile(Exception): # def __init__(self, path): # def __str__(self): # def _check_system_path_exists(path, fail=True): # def _check_system_path_is(nature, path, fail=True): # def system_path(path): # def _open(path, mode): # def check_file(path, fail=True): # def check_directory(path, fail=True): # def read_text_file(filepath, fail=True): # def read_binary_file(filepath, fail=True): # def remove_file(filepath): # def write_file(filepath, data, mode='w'): # def content_type(path): # def url_exists(url): # def check_content(path): # def _get_byte_url_content(path, ui=None): # def _dump_byte_url_content(source, target): # def get_content(path, ui=None): # def move_content(source, target, overwrite=False): # def copy_content(source, target, overwrite=False): # # Path: pubs/databroker.py # class DataBroker(object): # def __init__(self, pubsdir, docsdir, create=False): # def close(self): # def pull_cache(self, name): # def push_cache(self, name, data): # def pull_metadata(self, citekey): # def pull_bibentry(self, citekey): # def push_metadata(self, citekey, metadata): # def push_bibentry(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def citekeys(self): # def listing(self, filestats=True): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # def _notepath(self, citekey, extension): # def real_notepath(self, citekey, extension): # def remove_note(self, citekey, extension, silent=True): # def rename_note(self, old_citekey, new_citekey, extension): # # Path: pubs/datacache.py # class CacheEntry(object): # class CacheEntrySet(object): # class DataCache(object): # def __init__(self, data, timestamp): # def __init__(self, databroker, name): # def entries(self): # def flush(self, force=False): # def pull(self, citekey): # def push(self, citekey, data): # def push_to_cache(self, citekey, data): # def remove_from_cache(self, citekey): # def _try_pull_cache(self): # def _is_outdated(self, citekey): # def __init__(self, pubsdir, docsdir, create=False): # def close(self): # def databroker(self): # def metacache(self): # def bibcache(self): # def _create(self): # def flush_cache(self, force=False): # def pull_metadata(self, citekey): # def pull_bibentry(self, citekey): # def push_metadata(self, citekey, metadata): # def push_bibentry(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def citekeys(self): # def listing(self, filestats=True): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # def real_notepath(self, citekey, extension): # def remove_note(self, citekey, extension, silent=True): # def rename_note(self, old_citekey, new_citekey, extension): # # Path: pubs/endecoder.py # BP_ID_KEY = 'ID' # BP_ENTRYTYPE_KEY = 'ENTRYTYPE' # BP_ID_KEY = 'id' # BP_ENTRYTYPE_KEY = 'type' # BIBFIELD_ORDER = ['author', 'title', 'journal', 'institution', 'publisher', # 'year', 'month', 'number', 'volume', 'pages', 'url', 'link', # 'doi', 'note', 'abstract'] # def sanitize_citekey(record): # def customizations(record): # def __init__(self, error_msg, bibdata): # def encode_metadata(self, metadata): # def decode_metadata(self, metadata_raw): # def encode_bibdata(self, bibdata, ignore_fields=[]): # def _entry_to_bp_entry(self, key, entry, ignore_fields=[]): # def decode_bibdata(self, bibstr): # def _format_parsing_error(cls, e): # class EnDecoder(object): # class BibDecodingError(Exception): . Output only the next line.
for db_class in [databroker.DataBroker, datacache.DataCache]:
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class TestDataBroker(fake_env.TestFakeFs): def test_databroker(self): ende = endecoder.EnDecoder() page99_metadata = ende.decode_metadata(str_fixtures.metadata_raw0) page99_bibentry = ende.decode_bibdata(str_fixtures.bibtex_raw0) <|code_end|> . Use current file imports: (import unittest import os import dotdot import fake_env import str_fixtures from pubs import content, databroker, datacache from pubs import endecoder) and context including class names, function names, or small code snippets from other files: # Path: pubs/content.py # class UnableToDecodeTextFile(Exception): # def __init__(self, path): # def __str__(self): # def _check_system_path_exists(path, fail=True): # def _check_system_path_is(nature, path, fail=True): # def system_path(path): # def _open(path, mode): # def check_file(path, fail=True): # def check_directory(path, fail=True): # def read_text_file(filepath, fail=True): # def read_binary_file(filepath, fail=True): # def remove_file(filepath): # def write_file(filepath, data, mode='w'): # def content_type(path): # def url_exists(url): # def check_content(path): # def _get_byte_url_content(path, ui=None): # def _dump_byte_url_content(source, target): # def get_content(path, ui=None): # def move_content(source, target, overwrite=False): # def copy_content(source, target, overwrite=False): # # Path: pubs/databroker.py # class DataBroker(object): # def __init__(self, pubsdir, docsdir, create=False): # def close(self): # def pull_cache(self, name): # def push_cache(self, name, data): # def pull_metadata(self, citekey): # def pull_bibentry(self, citekey): # def push_metadata(self, citekey, metadata): # def push_bibentry(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def citekeys(self): # def listing(self, filestats=True): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # def _notepath(self, citekey, extension): # def real_notepath(self, citekey, extension): # def remove_note(self, citekey, extension, silent=True): # def rename_note(self, old_citekey, new_citekey, extension): # # Path: pubs/datacache.py # class CacheEntry(object): # class CacheEntrySet(object): # class DataCache(object): # def __init__(self, data, timestamp): # def __init__(self, databroker, name): # def entries(self): # def flush(self, force=False): # def pull(self, citekey): # def push(self, citekey, data): # def push_to_cache(self, citekey, data): # def remove_from_cache(self, citekey): # def _try_pull_cache(self): # def _is_outdated(self, citekey): # def __init__(self, pubsdir, docsdir, create=False): # def close(self): # def databroker(self): # def metacache(self): # def bibcache(self): # def _create(self): # def flush_cache(self, force=False): # def pull_metadata(self, citekey): # def pull_bibentry(self, citekey): # def push_metadata(self, citekey, metadata): # def push_bibentry(self, citekey, bibdata): # def push(self, citekey, metadata, bibdata): # def remove(self, citekey): # def exists(self, citekey, meta_check=False): # def citekeys(self): # def listing(self, filestats=True): # def in_docsdir(self, docpath): # def real_docpath(self, docpath): # def add_doc(self, citekey, source_path, overwrite=False): # def remove_doc(self, docpath, silent=True): # def rename_doc(self, docpath, new_citekey): # def real_notepath(self, citekey, extension): # def remove_note(self, citekey, extension, silent=True): # def rename_note(self, old_citekey, new_citekey, extension): # # Path: pubs/endecoder.py # BP_ID_KEY = 'ID' # BP_ENTRYTYPE_KEY = 'ENTRYTYPE' # BP_ID_KEY = 'id' # BP_ENTRYTYPE_KEY = 'type' # BIBFIELD_ORDER = ['author', 'title', 'journal', 'institution', 'publisher', # 'year', 'month', 'number', 'volume', 'pages', 'url', 'link', # 'doi', 'note', 'abstract'] # def sanitize_citekey(record): # def customizations(record): # def __init__(self, error_msg, bibdata): # def encode_metadata(self, metadata): # def decode_metadata(self, metadata_raw): # def encode_bibdata(self, bibdata, ignore_fields=[]): # def _entry_to_bp_entry(self, key, entry, ignore_fields=[]): # def decode_bibdata(self, bibstr): # def _format_parsing_error(cls, e): # class EnDecoder(object): # class BibDecodingError(Exception): . Output only the next line.
for db_class in [databroker.DataBroker, datacache.DataCache]:
Given the following code snippet before the placeholder: <|code_start|> self.colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] self.gf = GoodnessOfFit() self.df = self.gf.so.df # Calculate global maximums self.gm = {} for run in self.df.run.unique(): self.gm[run] = self.gf.calc_global_max(run) print(self.gm) # Plot various subplots self.alpha() self.si() self.li() self.li_2() self.lum_min() self.lum_max() self.w_int_mean() self.w_int_std() self.legend() self.dm_igm_slope() self.dm_host() self.axes[3, 2].set_axis_off() # Plot run rectangles # self.runs() # Save plot plt.tight_layout() # rect=[0, 0, 0.98, 1]) plt.subplots_adjust(wspace=0.1) <|code_end|> , predict the next line using imports from the current file: from frbpoppy import hist from goodness_of_fit import GoodnessOfFit from matplotlib.lines import Line2D from scipy.optimize import curve_fit from tests.convenience import plot_aa_style, rel_path import matplotlib.pyplot as plt import numpy as np and context including class names, function names, and sometimes code from other files: # Path: frbpoppy/misc.py # def hist(parameter, bin_type='lin', n_bins=25, norm='max', edges=True, # bins=None): # """Bin up a parameter either in a lin or log space. # # Why is this not a standard option in numpy or matplotlib? # # Args: # parameter (array): To be binned # bin_type (str): Either 'lin', 'log' or 'ln' # n_bins (int): Number of bins. Can be overriden internally # norm (bool): Whether to normalise to 'max' or 'prob' or none # # Returns: # tuple: bin centers, values per bin # # """ # if isinstance(parameter, list): # parameter = np.array(parameter) # # if len(parameter) == 0: # return np.nan, np.nan # # # Drop NaN-values # parameter = parameter[~(np.isnan(parameter) | np.isinf(parameter))] # # # Determine number of bins # if n_bins != 25: # pass # elif len(parameter) < 50: # n_bins = 15 # elif len(parameter) > 500: # n_bins = 50 # # # Determine type of binning # if bin_type == 'lin': # _bins = n_bins # elif bin_type == 'log': # min_f = np.log10(np.min(parameter[parameter != 0])) # max_f = np.log10(max(parameter)) # _bins = np.logspace(min_f, max_f, n_bins) # elif bin_type == 'ln': # min_f = np.log(np.min(parameter[parameter != 0])) # max_f = np.log(max(parameter)) # _bins = np.logspace(min_f, max_f, n_bins, base=np.e) # # # Allow for custom bins # if bins is not None: # _bins = bins # # # Allow for probability weighting # weights = None # if norm == 'prob': # weights = np.ones(len(parameter)) / len(parameter) # # # Bin # n, bin_edges = np.histogram(parameter, bins=_bins, weights=weights) # # if norm == 'max': # n = n/max(n) # Normalise # # # Centre bins # bins = (bin_edges[:-1] + bin_edges[1:]) / 2 # # # Ensure there are edges on the outer bins of the histograms # if edges: # if bin_type == 'lin': # bin_dif = np.diff(bins)[-1] # bins = np.insert(bins, 0, bins[0] - bin_dif) # bins = np.insert(bins, len(bins), bins[-1] + bin_dif) # n = np.insert(n, 0, 0) # n = np.insert(n, len(n), 0) # else: # bin_dif = np.diff(np.log10(bins))[-1] # bins = np.insert(bins, 0, 10**(np.log10(bins[0])-bin_dif)) # bins = np.insert(bins, len(bins), 10**(np.log10(bins[-1])+bin_dif)) # n = np.insert(n, 0, 0) # n = np.insert(n, len(n), 0) # # return bins, n # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('./plots/mc/mc.pdf'))
Predict the next line for this snippet: <|code_start|>"""Functions for calculating the intensity of points in a beam.""" def get_beam_props(model, fwhm): """Get beam properties. Args: model (str): Which model to use. fwhm (float): FWHM [frac. deg]. Returns: beam_size, pixel_scale, beam_array """ # Set up beam arrays models = ('wsrt-apertif', 'parkes-htru', 'chime-frb', 'gaussian', 'airy', 'wsrt-apertif_real') if model in models: <|code_end|> with the help of current file imports: import numpy as np import frbpoppy.galacticops as go from scipy.special import j1 from frbpoppy.paths import paths and context from other files: # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): , which may contain function names, class names, or code. Output only the next line.
place = paths.models() + f'/beams/{model}.npy'
Using the snippet: <|code_start|> def __str__(self): """How to print the class.""" # Set up title f = '{:20.19} {:>10} {:>10} {:>10}\n' t = f.format(self.name, 'Days', f'{self.object_type.title()}s', '%') line = '-'*len(t.split('\n')[-2].strip()) + '\n' t += line def r(value, d=4): """Round a value""" return round(value, d) def per(value): """Calculate the percentage.""" return r(value/self.tot * 100) # Format rates days = r(self.days) t += f.format('Cosmic Population', days, r(self.tot), 100) t += f.format('Too late', days, r(self.late), per(self.late)) t += f.format('Outside survey', days, r(self.out), per(self.out)) t += f.format('Outside pointings', days, r(self.pointing), per(self.pointing)) t += f.format('Too faint', days, r(self.faint), per(self.faint)) t += f.format('Detected', days, r(self.det), per(self.det)) t += f.format('/Gpc^3', 365.25, r(self.vol, 2), '-') t += f.format('Expected', r(self.exp, 4), 1, '-') t += line <|code_end|> , determine the next line of code. You have imports: import numpy as np from frbpoppy.misc import pprint and context (class names, function names, or code) available: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) . Output only the next line.
return pprint(t, output=False)
Predict the next line for this snippet: <|code_start|>"""Calculate where null points of an Airy pattern lie.""" STEPSIZE = 1e-6 PLOT = True x_range = np.arange(0, 50, STEPSIZE) y_range = 4*(j1(x_range)/x_range)**2 nulls = [] # Find where curve changes direction ind = np.diff(np.sign(np.diff(y_range))) x_null = x_range[1:-1][ind > 0] y_null = y_range[1:-1][ind > 0] print(x_null) if PLOT: title = r"Bessel function over $\text{x}$" <|code_end|> with the help of current file imports: from scipy.special import j1 from tests.convenience import plot_aa_style, rel_path import matplotlib.pyplot as plt import numpy as np and context from other files: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) , which may contain function names, class names, or code. Output only the next line.
plot_aa_style()
Next line prediction: <|code_start|>"""Calculate where null points of an Airy pattern lie.""" STEPSIZE = 1e-6 PLOT = True x_range = np.arange(0, 50, STEPSIZE) y_range = 4*(j1(x_range)/x_range)**2 nulls = [] # Find where curve changes direction ind = np.diff(np.sign(np.diff(y_range))) x_null = x_range[1:-1][ind > 0] y_null = y_range[1:-1][ind > 0] print(x_null) if PLOT: title = r"Bessel function over $\text{x}$" plot_aa_style() fig = plt.figure() ax = fig.add_subplot(111) plt.title(title) plt.plot(x_range[::10], y_range[::10]) plt.scatter(x_null, y_null, marker='x') plt.yscale('log') plt.tight_layout() <|code_end|> . Use current file imports: (from scipy.special import j1 from tests.convenience import plot_aa_style, rel_path import matplotlib.pyplot as plt import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('./plots/null_sidelobes.pdf'))
Given the code snippet: <|code_start|>EXPECTED = {'parkes-htru': [9, 1549 / 0.551 / 24], # N_frbs, N_days 'wsrt-apertif': [9, 1100/24], # 1100 hours 'askap-fly': [20, 32840 / 8 / 24], 'arecibo-palfa': [1, 24.1], 'guppi': [0.4, 81], # 0.4 is my own assumption 'fast-crafts': [1, 1500/24], 'chime-frb': [2, 1], # My own assumption 'askap-incoh': [9, 45] # My own assumption } SURVEYS = ('parkes-htru', 'wsrt-apertif', 'askap-fly', 'fast-crafts', 'arecibo-palfa') ALPHAS = np.around(np.linspace(-0.5, -2.0, 7), decimals=2) def real_rates(surveys=SURVEYS): """Calculate the EXPECTED rates (all scaled to a survey).""" rates = {} scale_to = surveys[0] for surv in surveys: if surv not in EXPECTED: continue # Plot EXPECTED rate exp_n = EXPECTED[surv][0] exp_days = EXPECTED[surv][1] scale_n = EXPECTED[scale_to][0] scale_days = EXPECTED[scale_to][1] <|code_end|> , generate the next line using the imports in this file: import matplotlib.pyplot as plt import numpy as np from frbpoppy import poisson_interval from tests.convenience import plot_aa_style, rel_path and context (functions, classes, or occasionally code) from other files: # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
exp_min, exp_max = poisson_interval(exp_n, sigma=2)
Here is a snippet: <|code_start|> def real_rates(surveys=SURVEYS): """Calculate the EXPECTED rates (all scaled to a survey).""" rates = {} scale_to = surveys[0] for surv in surveys: if surv not in EXPECTED: continue # Plot EXPECTED rate exp_n = EXPECTED[surv][0] exp_days = EXPECTED[surv][1] scale_n = EXPECTED[scale_to][0] scale_days = EXPECTED[scale_to][1] exp_min, exp_max = poisson_interval(exp_n, sigma=2) exp = (exp_n/exp_days) / (scale_n/scale_days) exp_min *= (1/exp_days) / (scale_n/scale_days) exp_max *= (1/exp_days) / (scale_n/scale_days) rates[surv] = (exp, exp_min, exp_max) return rates def main(): """Plot real rate regions per alpha.""" <|code_end|> . Write the next line using the current file imports: import matplotlib.pyplot as plt import numpy as np from frbpoppy import poisson_interval from tests.convenience import plot_aa_style, rel_path and context from other files: # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) , which may include functions, classes, or code. Output only the next line.
plot_aa_style()
Predict the next line after this snippet: <|code_start|> exp = (exp_n/exp_days) / (scale_n/scale_days) exp_min *= (1/exp_days) / (scale_n/scale_days) exp_max *= (1/exp_days) / (scale_n/scale_days) rates[surv] = (exp, exp_min, exp_max) return rates def main(): """Plot real rate regions per alpha.""" plot_aa_style() rates = real_rates() for surv in rates: middle, top, bottom = rates[surv] left = min(ALPHAS) right = max(ALPHAS) x = [left, right, right, left] y = [top, top, bottom, bottom] plt.fill(x, y, alpha=0.25) plt.plot([left, right], [middle]*2, label=surv, linestyle='dashed') plt.xlabel(r'$\alpha_{\text{in}}$') plt.ylabel(rf'Events / {SURVEYS[0]}') plt.yscale('log') plt.legend() plt.gca().invert_xaxis() plt.tight_layout() <|code_end|> using the current file's imports: import matplotlib.pyplot as plt import numpy as np from frbpoppy import poisson_interval from tests.convenience import plot_aa_style, rel_path and any relevant context from other files: # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('./plots/rates_rm.pdf'))
Using the snippet: <|code_start|>"""Show frbpoppy matches analytical models and predict the event rates.""" REMAKE = True SIZE = 1e4 SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa') ELEMENTS = {'analytical': True, 'real': True, 'simple': False, 'complex': True} ALPHAS = np.around(np.linspace(-0.5, -2.0, 7), decimals=2) def plot(analytical=True, simple=False, complex=False, real=True): """Plot rates panel.""" surveys = SURVEYS # If needing two panels if simple and complex: <|code_end|> , determine the next line of code. You have imports: from matplotlib.lines import Line2D from matplotlib.patches import Patch from tests.convenience import plot_aa_style, rel_path from alpha_complex import complex_rates from alpha_real import real_rates from alpha_simple import simple_rates from alpha_analytical import analytical_rates import matplotlib.pyplot as plt import numpy as np and context (class names, function names, or code) available: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plot_aa_style(cols=2)
Predict the next line after this snippet: <|code_start|> elements = [] for i, surv in enumerate(surveys): c = cmap(i) line = Line2D([0], [0], color=c) label = surv elements.append((line, label)) # Add gap in legend elements.append((Line2D([0], [0], color='white'), '')) # Add line styles if analytical: n = 'analytical' elements.append((Line2D([0], [0], color='gray', linestyle='dotted'), n)) if simple: elements.append((Line2D([0], [0], color='gray'), 'simple')) elements.append((Line2D([0], [0], color='gray', linestyle='dashed'), 'complex')) # Add gap in legend elements.append((Line2D([0], [0], color='white'), '')) if real: elements.append((Patch(facecolor='gray', edgecolor='gray', alpha=0.6), 'real')) lines, labels = zip(*elements) plt.legend(lines, labels, bbox_to_anchor=(1.04, 0.5), loc="center left") <|code_end|> using the current file's imports: from matplotlib.lines import Line2D from matplotlib.patches import Patch from tests.convenience import plot_aa_style, rel_path from alpha_complex import complex_rates from alpha_real import real_rates from alpha_simple import simple_rates from alpha_analytical import analytical_rates import matplotlib.pyplot as plt import numpy as np and any relevant context from other files: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('plots/rates_overview.pdf'), bbox_inches='tight')
Predict the next line after this snippet: <|code_start|> df.loc[df.frb_name == name, 'rate'] = row.rate df.loc[df.frb_name == name, 'n_bursts'] = row.n_bursts df.loc[df.frb_name == name, 'exposure'] = row.exposure return df def poisson_interval(k, sigma=1): """ Use chi-squared info to get the poisson interval. Given a number of observed events, which range of observed events would have been just as likely given a particular interval? Based off https://stackoverflow.com/questions/14813530/ poisson-confidence-interval-with-numpy """ gauss = norm(0, 1).pdf a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) if isinstance(k, np.ndarray): low[k == 0] = 0. elif k == 0: low = 0.0 return low, high def plot_w_eff_rate(df): """Plot effective pulse width against rate.""" <|code_end|> using the current file's imports: from scipy.integrate import quad from scipy.stats import chi2, norm from frbcat import Frbcat from tests.convenience import plot_aa_style, rel_path import matplotlib.pyplot as plt import numpy as np import pandas as pd and any relevant context from other files: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plot_aa_style(cols=1)
Given the code snippet: <|code_start|> width = db.width width_err = (db.width_error_lower, db.width_error_upper) n_bursts = db.n_bursts rate = db.rate exposure = db.exposure.to_numpy() # Calculate error bars low, high = poisson_interval(n_bursts.to_numpy(), sigma=1) rate_err = (low/exposure, high/exposure) # Plot values plt.errorbar(width, rate, xerr=width_err, yerr=rate_err, marker='x', fmt='o') # Print correlation _width = width[~np.isnan(rate)] _rate = rate[~np.isnan(rate)] r = np.corrcoef(_width, _rate)[0, 1] print('Pearson correlation coefficient: ', r) r = np.corrcoef(np.log10(_width), np.log10(_rate))[0, 1] print('Pearson correlation coefficient in log10 space: ', r) plt.xlabel(r'Pulse Width (ms)') plt.ylabel(r'Rate (/hour)') if SCALE == 'log': plt.xscale('log') plt.yscale('log', nonposy='clip') plt.tight_layout() <|code_end|> , generate the next line using the imports in this file: from scipy.integrate import quad from scipy.stats import chi2, norm from frbcat import Frbcat from tests.convenience import plot_aa_style, rel_path import matplotlib.pyplot as plt import numpy as np import pandas as pd and context (functions, classes, or occasionally code) from other files: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('./plots/rate_w_eff_chime.pdf'))
Predict the next line after this snippet: <|code_start|> """Calculate the mean and std of a lognormal distribution. See https://en.wikipedia.org/wiki/Log-normal_distribution """ normal_std = np.sqrt(np.log(1 + (std_x**2/mean_x)**2)) normal_mean = np.log(mean_x**2 / np.sqrt(mean_x**2 + std_x**2)) return normal_mean, normal_std def lognormal(mean, std, shape): """Calculate the mean and std from the underlying distribution. See https://en.wikipedia.org/wiki/Log-normal_distribution """ mean, std = calc_lognormal_input(mean, std) return np.random.lognormal(mean, std, shape) fig, axes = plt.subplots(1, 1, sharey=True) mean = 2.71**2 std = 5 size = int(1e4) axes.set_xscale('log', basex=2.71) colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] data = lognormal(mean, std, size) <|code_end|> using the current file's imports: import numpy as np import matplotlib.pyplot as plt from frbpoppy import hist and any relevant context from other files: # Path: frbpoppy/misc.py # def hist(parameter, bin_type='lin', n_bins=25, norm='max', edges=True, # bins=None): # """Bin up a parameter either in a lin or log space. # # Why is this not a standard option in numpy or matplotlib? # # Args: # parameter (array): To be binned # bin_type (str): Either 'lin', 'log' or 'ln' # n_bins (int): Number of bins. Can be overriden internally # norm (bool): Whether to normalise to 'max' or 'prob' or none # # Returns: # tuple: bin centers, values per bin # # """ # if isinstance(parameter, list): # parameter = np.array(parameter) # # if len(parameter) == 0: # return np.nan, np.nan # # # Drop NaN-values # parameter = parameter[~(np.isnan(parameter) | np.isinf(parameter))] # # # Determine number of bins # if n_bins != 25: # pass # elif len(parameter) < 50: # n_bins = 15 # elif len(parameter) > 500: # n_bins = 50 # # # Determine type of binning # if bin_type == 'lin': # _bins = n_bins # elif bin_type == 'log': # min_f = np.log10(np.min(parameter[parameter != 0])) # max_f = np.log10(max(parameter)) # _bins = np.logspace(min_f, max_f, n_bins) # elif bin_type == 'ln': # min_f = np.log(np.min(parameter[parameter != 0])) # max_f = np.log(max(parameter)) # _bins = np.logspace(min_f, max_f, n_bins, base=np.e) # # # Allow for custom bins # if bins is not None: # _bins = bins # # # Allow for probability weighting # weights = None # if norm == 'prob': # weights = np.ones(len(parameter)) / len(parameter) # # # Bin # n, bin_edges = np.histogram(parameter, bins=_bins, weights=weights) # # if norm == 'max': # n = n/max(n) # Normalise # # # Centre bins # bins = (bin_edges[:-1] + bin_edges[1:]) / 2 # # # Ensure there are edges on the outer bins of the histograms # if edges: # if bin_type == 'lin': # bin_dif = np.diff(bins)[-1] # bins = np.insert(bins, 0, bins[0] - bin_dif) # bins = np.insert(bins, len(bins), bins[-1] + bin_dif) # n = np.insert(n, 0, 0) # n = np.insert(n, len(n), 0) # else: # bin_dif = np.diff(np.log10(bins))[-1] # bins = np.insert(bins, 0, 10**(np.log10(bins[0])-bin_dif)) # bins = np.insert(bins, len(bins), 10**(np.log10(bins[-1])+bin_dif)) # n = np.insert(n, 0, 0) # n = np.insert(n, len(n), 0) # # return bins, n . Output only the next line.
xy = hist(data, bin_type='log')
Using the snippet: <|code_start|>"""Plot corner plots showing best fit for rates. Linked with the ideas in cube.py -> generating a range of parameters. TODO: In progress """ # # Set parameters needed for generating a rate cube # GENERATE = False # PLOT = True vs = {'alpha': np.linspace(-1, -2, 5)[::-1][1:4], 'li': np.linspace(-2, 0, 5), # Luminosity function index 'si': np.linspace(-2, 2, 5)} # Spectral index SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa') def get_pops(alpha='*', li='*', si='*', survey='*'): filename = f'complex_alpha_{alpha}_lum_{li}_si_{si}_{survey}.p' <|code_end|> , determine the next line of code. You have imports: import numpy as np import os import matplotlib.pyplot as plt from glob import glob from matplotlib.colors import LogNorm from frbpoppy import paths, unpickle, poisson_interval from tests.convenience import plot_aa_style, rel_path from alpha_real import EXPECTED and context (class names, function names, or code) available: # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: frbpoppy/population.py # def unpickle(filename=None, uid=None): # """Quick function to unpickle a population. # # Args: # filename (str, optional): Define the path to the pickled population, # or give the population name # uid (str, optional): Unique Identifier # # Returns: # Population: Population class # # """ # # Find population file # if os.path.isfile(filename): # f = open(filename, 'rb') # else: # # Find standard population files # try: # name = filename.lower() # if uid: # name += f'_{uid}' # p = paths.populations() + f'{name}.p' # f = open(p, 'rb') # except FileNotFoundError: # s = 'Pickled population file "{0}" does not exist'.format(filename) # raise FileNotFoundError(s) # # # Unpickle # pop = pickle.load(f) # f.close() # return pop # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
filter = os.path.join(paths.populations(), filename)
Given the following code snippet before the placeholder: <|code_start|> 'li': np.linspace(-2, 0, 5), # Luminosity function index 'si': np.linspace(-2, 2, 5)} # Spectral index SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa') def get_pops(alpha='*', li='*', si='*', survey='*'): filename = f'complex_alpha_{alpha}_lum_{li}_si_{si}_{survey}.p' filter = os.path.join(paths.populations(), filename) pop_paths = glob(filter) pops = [] for path in pop_paths: if '_for_plotting' not in path: pops.append(unpickle(path)) return pops def make_mesh(x_par, y_par, survey): v = np.zeros([len(vs[x_par]), len(vs[y_par])]) print(x_par, y_par) for i, x_val in enumerate(vs[x_par]): for j, y_val in enumerate(vs[y_par]): print(x_val, y_val) pops = get_pops(survey=survey, **{x_par: x_val, y_par: y_val}) if pops: rates = [] for pop in pops: rate = pop.source_rate.det / pop.source_rate.days <|code_end|> , predict the next line using imports from the current file: import numpy as np import os import matplotlib.pyplot as plt from glob import glob from matplotlib.colors import LogNorm from frbpoppy import paths, unpickle, poisson_interval from tests.convenience import plot_aa_style, rel_path from alpha_real import EXPECTED and context including class names, function names, and sometimes code from other files: # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: frbpoppy/population.py # def unpickle(filename=None, uid=None): # """Quick function to unpickle a population. # # Args: # filename (str, optional): Define the path to the pickled population, # or give the population name # uid (str, optional): Unique Identifier # # Returns: # Population: Population class # # """ # # Find population file # if os.path.isfile(filename): # f = open(filename, 'rb') # else: # # Find standard population files # try: # name = filename.lower() # if uid: # name += f'_{uid}' # p = paths.populations() + f'{name}.p' # f = open(p, 'rb') # except FileNotFoundError: # s = 'Pickled population file "{0}" does not exist'.format(filename) # raise FileNotFoundError(s) # # # Unpickle # pop = pickle.load(f) # f.close() # return pop # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
rate_err = poisson_interval(pop.source_rate.det, sigma=1)
Given the following code snippet before the placeholder: <|code_start|>"""Plot corner plots showing best fit for rates. Linked with the ideas in cube.py -> generating a range of parameters. TODO: In progress """ # # Set parameters needed for generating a rate cube # GENERATE = False # PLOT = True vs = {'alpha': np.linspace(-1, -2, 5)[::-1][1:4], 'li': np.linspace(-2, 0, 5), # Luminosity function index 'si': np.linspace(-2, 2, 5)} # Spectral index SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa') def get_pops(alpha='*', li='*', si='*', survey='*'): filename = f'complex_alpha_{alpha}_lum_{li}_si_{si}_{survey}.p' filter = os.path.join(paths.populations(), filename) pop_paths = glob(filter) pops = [] for path in pop_paths: if '_for_plotting' not in path: <|code_end|> , predict the next line using imports from the current file: import numpy as np import os import matplotlib.pyplot as plt from glob import glob from matplotlib.colors import LogNorm from frbpoppy import paths, unpickle, poisson_interval from tests.convenience import plot_aa_style, rel_path from alpha_real import EXPECTED and context including class names, function names, and sometimes code from other files: # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: frbpoppy/population.py # def unpickle(filename=None, uid=None): # """Quick function to unpickle a population. # # Args: # filename (str, optional): Define the path to the pickled population, # or give the population name # uid (str, optional): Unique Identifier # # Returns: # Population: Population class # # """ # # Find population file # if os.path.isfile(filename): # f = open(filename, 'rb') # else: # # Find standard population files # try: # name = filename.lower() # if uid: # name += f'_{uid}' # p = paths.populations() + f'{name}.p' # f = open(p, 'rb') # except FileNotFoundError: # s = 'Pickled population file "{0}" does not exist'.format(filename) # raise FileNotFoundError(s) # # # Unpickle # pop = pickle.load(f) # f.close() # return pop # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
pops.append(unpickle(path))
Next line prediction: <|code_start|> return pops def make_mesh(x_par, y_par, survey): v = np.zeros([len(vs[x_par]), len(vs[y_par])]) print(x_par, y_par) for i, x_val in enumerate(vs[x_par]): for j, y_val in enumerate(vs[y_par]): print(x_val, y_val) pops = get_pops(survey=survey, **{x_par: x_val, y_par: y_val}) if pops: rates = [] for pop in pops: rate = pop.source_rate.det / pop.source_rate.days rate_err = poisson_interval(pop.source_rate.det, sigma=1) rate_err /= pop.source_rate.days if pop.source_rate.det == 0: rate = np.nan rates.append(rate) mean_rate = np.nanmean(rates) exp_rate = EXPECTED[survey][0]/EXPECTED[survey][1] v[i, j] = np.abs(mean_rate - exp_rate) return v.T for survey in SURVEYS: <|code_end|> . Use current file imports: (import numpy as np import os import matplotlib.pyplot as plt from glob import glob from matplotlib.colors import LogNorm from frbpoppy import paths, unpickle, poisson_interval from tests.convenience import plot_aa_style, rel_path from alpha_real import EXPECTED) and context including class names, function names, or small code snippets from other files: # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: frbpoppy/population.py # def unpickle(filename=None, uid=None): # """Quick function to unpickle a population. # # Args: # filename (str, optional): Define the path to the pickled population, # or give the population name # uid (str, optional): Unique Identifier # # Returns: # Population: Population class # # """ # # Find population file # if os.path.isfile(filename): # f = open(filename, 'rb') # else: # # Find standard population files # try: # name = filename.lower() # if uid: # name += f'_{uid}' # p = paths.populations() + f'{name}.p' # f = open(p, 'rb') # except FileNotFoundError: # s = 'Pickled population file "{0}" does not exist'.format(filename) # raise FileNotFoundError(s) # # # Unpickle # pop = pickle.load(f) # f.close() # return pop # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plot_aa_style()
Based on the snippet: <|code_start|> im = axes[2, 1].imshow(make_mesh('li', 'si', survey), **args) fig.colorbar(im, ax=axes[0, 2]) axes[1, 1].set_title(survey) axes[2, 0].set_xlabel('alpha') axes[2, 0].set_ylabel('si') axes[2, 1].set_xlabel('li') axes[2, 2].set_xlabel('si') axes[1, 0].set_ylabel('li') axes[0, 0].set_ylabel('alpha') axes[0, 1].set_axis_off() axes[0, 2].set_axis_off() axes[1, 2].set_axis_off() axes[0, 0].set_yticks([]) axes[1, 1].set_yticks([]) axes[2, 2].set_yticks([]) # Set up axes for ax in axes.flat: ax.label_outer() x_par = ax.get_xlabel() if x_par: ax.set_xticks(np.arange(len(vs[x_par]))) ax.set_xticklabels(vs[x_par]) y_par = ax.get_ylabel() if y_par: ax.set_yticks(np.arange(len(vs[y_par]))) ax.set_yticklabels(vs[y_par]) plt.tight_layout() <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import os import matplotlib.pyplot as plt from glob import glob from matplotlib.colors import LogNorm from frbpoppy import paths, unpickle, poisson_interval from tests.convenience import plot_aa_style, rel_path from alpha_real import EXPECTED and context (classes, functions, sometimes code) from other files: # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/misc.py # def poisson_interval(k, sigma=1): # """ # Use chi-squared info to get the poisson interval. # # Given a number of observed events, which range of observed events would # have been just as likely given a particular interval? # # Based off https://stackoverflow.com/questions/14813530/ # poisson-confidence-interval-with-numpy # """ # gauss = norm(0, 1).pdf # a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0] # low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2) # if k == 0: # low = 0.0 # # return low, high # # Path: frbpoppy/population.py # def unpickle(filename=None, uid=None): # """Quick function to unpickle a population. # # Args: # filename (str, optional): Define the path to the pickled population, # or give the population name # uid (str, optional): Unique Identifier # # Returns: # Population: Population class # # """ # # Find population file # if os.path.isfile(filename): # f = open(filename, 'rb') # else: # # Find standard population files # try: # name = filename.lower() # if uid: # name += f'_{uid}' # p = paths.populations() + f'{name}.p' # f = open(p, 'rb') # except FileNotFoundError: # s = 'Pickled population file "{0}" does not exist'.format(filename) # raise FileNotFoundError(s) # # # Unpickle # pop = pickle.load(f) # f.close() # return pop # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path(f'./plots/corner_{survey}.pdf'))
Using the snippet: <|code_start|>"""Compare rate calculations per alpha for the two askap settings.""" REMAKE = False SIZE = 1e4 SURVEYS = ['parkes-htru', 'askap-fly', 'askap-incoh'] ALPHAS = np.around(np.linspace(-0.2, -2.5, 7), decimals=2) def main(): """Get detection rates for surveys.""" complex = complex_rates(remake=REMAKE, alphas=ALPHAS, size=SIZE, surveys=SURVEYS) # Plot population event rates plot_rates(complex) def plot_rates(rates): """Plot detection rates for askap surveys.""" <|code_end|> , determine the next line of code. You have imports: import numpy as np import matplotlib.pyplot as plt from tests.convenience import plot_aa_style, rel_path from alpha_complex import complex_rates and context (class names, function names, or code) available: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plot_aa_style()
Using the snippet: <|code_start|> complex = complex_rates(remake=REMAKE, alphas=ALPHAS, size=SIZE, surveys=SURVEYS) # Plot population event rates plot_rates(complex) def plot_rates(rates): """Plot detection rates for askap surveys.""" plot_aa_style() fig, (ax1) = plt.subplots(1, 1) cmap = plt.get_cmap('tab10') ax1.set_xlim((min(ALPHAS)+.1, max(ALPHAS)-.1)) ax1.set_yscale('log', nonposy='mask') # Plot complex versus toy for i, surv in enumerate(SURVEYS): ax1.plot(ALPHAS, rates[surv], color=cmap(i+1), label=surv, linestyle='dashed') # Plot layout options # Set up axes ax1.set_xlabel(r'$\alpha_{\text{in}}$') ax1.invert_xaxis() ax1.set_ylabel('Events / htru') plt.legend() <|code_end|> , determine the next line of code. You have imports: import numpy as np import matplotlib.pyplot as plt from tests.convenience import plot_aa_style, rel_path from alpha_complex import complex_rates and context (class names, function names, or code) available: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('plots/askap_rates.pdf'), bbox_inches='tight')
Based on the snippet: <|code_start|> self.downloads = os.path.expanduser("~/Downloads") self.subfolders = ['data', 'frbcat', 'populations', 'surveys', 'models'] self.config = {s: '' for s in self.subfolders} def __str__(self): """Define how to print a path object to a console.""" s = 'Paths:' attributes = [] for e in self.subfolders: attr = '\n\t{0:12.11}{1:.60}'.format(e, getattr(self, e)()) attributes.append(attr) s += ''.join(attributes) return s def check(self, path): """Perform checks on path.""" # Just convient to have files ending in a slash if path[-1] != '/': path += '/' if not os.path.exists(path): <|code_end|> , predict the immediate next line with the help of imports: import os.path from frbpoppy.misc import pprint and context (classes, functions, sometimes code) from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) . Output only the next line.
pprint(f"Creating directory {path}")
Given the code snippet: <|code_start|> self.beam_pattern = 'perfect' # Un-used self.strategy = 'regular' # 'follow-up' not implemented if self.mount_type == 'transit': # Transit telescopes can't follow-up self.strategy = 'regular' # Set beam properties self.set_beam() # Set pointing properties self.set_pointings(mount_type=self.mount_type) def __str__(self): """Define how to print a survey object to a console.""" s = 'Survey properties:' attributes = [] for e in self.__dict__: attr = '\n\t{0:13.12}{1:.60}'.format(e, str(self.__dict__[e])) attributes.append(attr) s += ''.join(attributes) return s def read_survey_parameters(self): """Read in survey parameters.""" # Read the survey file <|code_end|> , generate the next line using the imports in this file: import numpy as np import os import pandas as pd import frbpoppy.galacticops as go import frbpoppy.pointings as pointings import frbpoppy.beam_dists as bd from frbpoppy.paths import paths and context (functions, classes, or occasionally code) from other files: # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): . Output only the next line.
path = os.path.join(paths.surveys(), 'surveys.csv')
Next line prediction: <|code_start|> M_BURSTS = 1100 N_DAYS = 50 N_SRCS = int(1e5) R = 5.7 K = 0.34 def get_probabilities(normalise=False): """Get the number of bursts per maximum time. Args: normalise (type): Whether to normalise at each maximum time, such that there's a number of bursts at each time stamp having a maximum probability of one. Returns: array: Number of bursts per maximum time. """ days = np.arange(1, N_DAYS, 1) m_bursts = np.arange(0, M_BURSTS, 1) xx, yy = np.meshgrid(m_bursts, days) prob = np.full((len(days), len(m_bursts)), np.nan) # Mask any frbs over the maximum time time = td.clustered(r=R, k=K, n_srcs=N_SRCS, n_days=N_DAYS, z=0) <|code_end|> . Use current file imports: (import numpy as np import matplotlib.pyplot as plt import frbpoppy.time_dists as td from matplotlib.colors import LogNorm from frbpoppy import pprint from tests.convenience import plot_aa_style, rel_path) and context including class names, function names, or small code snippets from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
pprint('Masking days')
Predict the next line for this snippet: <|code_start|> m_bursts = np.arange(0, M_BURSTS, 1) xx, yy = np.meshgrid(m_bursts, days) prob = np.full((len(days), len(m_bursts)), np.nan) # Mask any frbs over the maximum time time = td.clustered(r=R, k=K, n_srcs=N_SRCS, n_days=N_DAYS, z=0) pprint('Masking days') for i, day in reversed(list(enumerate(days))): time[(time > day)] = np.nan m_bursts = (~np.isnan(time)).sum(1) unique, counts = np.unique(m_bursts, return_counts=True) try: prob[(i, unique)] = counts except IndexError: pprint('Please ensure M is large enough.') exit() prob = prob.T/N_SRCS if normalise: # Normalise at each maximum time (highest chance becomes one) prob = prob / np.nanmax(prob, axis=0) return prob def plot(prob, show=False): """Plot the number of bursts seen over a maximum time.""" <|code_end|> with the help of current file imports: import numpy as np import matplotlib.pyplot as plt import frbpoppy.time_dists as td from matplotlib.colors import LogNorm from frbpoppy import pprint from tests.convenience import plot_aa_style, rel_path and context from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) , which may contain function names, class names, or code. Output only the next line.
plot_aa_style(cols=2)
Given the code snippet: <|code_start|> if normalise: # Normalise at each maximum time (highest chance becomes one) prob = prob / np.nanmax(prob, axis=0) return prob def plot(prob, show=False): """Plot the number of bursts seen over a maximum time.""" plot_aa_style(cols=2) days = np.arange(1, N_DAYS, 1) m_bursts = np.arange(0, M_BURSTS, 1) prob[np.isnan(prob)] = 0 fig, ax = plt.subplots() extent = [min(days)-0.5, max(days)+0.5, min(m_bursts), max(m_bursts)] plt.imshow(prob, norm=LogNorm(), origin='lower', aspect='auto', interpolation='none', extent=extent) plt.colorbar(orientation='vertical') ax.set_title('Probability of M bursts within time') ax.set_xlabel('Maximum time (days)') ax.set_ylabel('M bursts') plt.tight_layout() if show: plt.show() else: <|code_end|> , generate the next line using the imports in this file: import numpy as np import matplotlib.pyplot as plt import frbpoppy.time_dists as td from matplotlib.colors import LogNorm from frbpoppy import pprint from tests.convenience import plot_aa_style, rel_path and context (functions, classes, or occasionally code) from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('./plots/prob_m_bursts.pdf'))
Predict the next line for this snippet: <|code_start|> def plot(*pops, files=[], tns=False, show=True, mute=True, port=5006, print_command=False): """ Plot populations with bokeh. Has to save populations before plotting. Args: *pops (Population, optional): Add the populations you would like to see plotted files (list, optional): List of population files to plot. tns (bool, optional): Whether to plot tns parameters. Defaults to True show (bool, optional): Whether to display the plot or not. Mainly used for debugging purposes. Defaults to True. mute (bool): Show output from Bokeh or not port (int): The port on which to launch Bokeh print_command (bool): Whether to show the command do_plot is running """ if len(pops) > 0: # Save populations for pop in pops: if type(pop) == str: name = pop else: # Check whether empty population if pop.n_sources() < 1: <|code_end|> with the help of current file imports: import os import subprocess import sys from frbpoppy.misc import pprint from frbpoppy.paths import paths and context from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): , which may contain function names, class names, or code. Output only the next line.
pprint(f'Skipping {pop.name} population as no sources')
Based on the snippet: <|code_start|> files (list, optional): List of population files to plot. tns (bool, optional): Whether to plot tns parameters. Defaults to True show (bool, optional): Whether to display the plot or not. Mainly used for debugging purposes. Defaults to True. mute (bool): Show output from Bokeh or not port (int): The port on which to launch Bokeh print_command (bool): Whether to show the command do_plot is running """ if len(pops) > 0: # Save populations for pop in pops: if type(pop) == str: name = pop else: # Check whether empty population if pop.n_sources() < 1: pprint(f'Skipping {pop.name} population as no sources') continue pop.name = pop.name.lower() if '_for_plotting' not in pop.name: pop.name += '_for_plotting' name = pop.name pop.save() # Save location file_name = name + '.p' <|code_end|> , predict the immediate next line with the help of imports: import os import subprocess import sys from frbpoppy.misc import pprint from frbpoppy.paths import paths and context (classes, functions, sometimes code) from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): . Output only the next line.
out = os.path.join(paths.populations(), file_name)
Here is a snippet: <|code_start|>"""Check a powerlaw implementation generates the right numbers.""" POWER = -1 SIZE = 1e5 pl = gen_dists.powerlaw(1e35, 1e40, POWER, int(SIZE)) minx = min(pl) maxx = max(pl) bins = 10 ** np.linspace(np.log10(minx), np.log10(maxx), 50) hist, edges = np.histogram(pl, bins=bins) <|code_end|> . Write the next line using the current file imports: import numpy as np import matplotlib.pyplot as plt from frbpoppy import gen_dists from tests.convenience import plot_aa_style, rel_path and context from other files: # Path: frbpoppy/gen_dists.py # def powerlaw(low, high, power, shape=1): # def sample(n_gen): # def accept(pl): # def trunc_norm(mean, std, shape=1, low=0, high=np.inf): # def log10normal(mean, std, shape): # def calc_lognormal_input(mean_x, std_x): # def lognormal(mean, std, shape): # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) , which may include functions, classes, or code. Output only the next line.
plot_aa_style()
Continue the code snippet: <|code_start|> POWER = -1 SIZE = 1e5 pl = gen_dists.powerlaw(1e35, 1e40, POWER, int(SIZE)) minx = min(pl) maxx = max(pl) bins = 10 ** np.linspace(np.log10(minx), np.log10(maxx), 50) hist, edges = np.histogram(pl, bins=bins) plot_aa_style() fig = plt.figure() ax = fig.add_subplot(111) plt.step(edges[:-1], hist, where='mid') # Overplot the expected line xlims = ax.get_xlim() xs = np.array([np.log10(edges[0]), np.log10(edges[-2])]) ys = POWER*(xs-xs[0])+np.log10(hist[0]) ax.plot(10**xs, 10**ys, 'r:', label=f'Expected distribution') plt.legend() plt.xscale('log') plt.yscale('log') ax.set_ylim(1, SIZE) plt.grid() <|code_end|> . Use current file imports: import numpy as np import matplotlib.pyplot as plt from frbpoppy import gen_dists from tests.convenience import plot_aa_style, rel_path and context (classes, functions, or code) from other files: # Path: frbpoppy/gen_dists.py # def powerlaw(low, high, power, shape=1): # def sample(n_gen): # def accept(pl): # def trunc_norm(mean, std, shape=1, low=0, high=np.inf): # def log10normal(mean, std, shape): # def calc_lognormal_input(mean_x, std_x): # def lognormal(mean, std, shape): # # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('plots/powerlaw.pdf'))
Next line prediction: <|code_start|>"""Do things with frbcat.""" class TNS(BaseTNS): """ Add frbpoppy functionality to Frbcat. Get the pandas dataframe with Frbcat().df """ def __init__(self, frbpoppy=True, **kwargs): """Initialize.""" <|code_end|> . Use current file imports: (import pandas as pd import IPython; IPython.embed() from frbcat import TNS as BaseTNS from frbpoppy.misc import pprint from frbpoppy.paths import paths from frbpoppy.population import Population) and context including class names, function names, or small code snippets from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/population.py # class Population: # """Class to hold a population of FRBs.""" # # def __init__(self): # """Initializing.""" # # Population properties # self.name = None # # # Frequency emission limits [MHz] # self.f_max = None # self.f_min = None # # # Store FRB sources # self.frbs = FRBs() # self.uid = None # Unique Identifier # # def __str__(self): # """Define how to print a population object to a console.""" # s = 'Population properties:' # # # TODO: Code this to print all properties # # return s # # def to_df(self): # """Gather source values into a pandas dataframe.""" # df = self.frbs.to_df() # return df # # def save(self, path=None): # """ # Write out source properties as data file. # # Args: # path (str): Path to which to save. # """ # if path is None: # # Check if a population has been a survey name # if not self.name: # file_name = 'pop' # else: # file_name = self.name.lower() # # if self.uid: # file_name += f'_{self.uid}' # # path = paths.populations() + f'{file_name}.p' # # self.to_pickle(path) # # def to_csv(self, path): # """Write a population to a csv file. # # Args: # path (str): Path to which to write # # """ # df = self.frbs.to_df() # df.to_csv(path) # # def to_pickle(self, path): # """Write a population to a pickled file for future use. # # Args: # path (str): Path to which to write # # """ # output = open(path, 'wb') # pickle.dump(self, output, 2) # output.close() # # def n_sources(self): # """Return the number of FRB sources.""" # return len(self.frbs.ra) # # def n_srcs(self): # return self.n_sources() # # def n_bursts(self): # """Return the number of bursts.""" # try: # Will only work for a repeater population # n = np.count_nonzero(~np.isnan(self.frbs.time)) # except TypeError: # n = self.n_sources() # return n # # def n_repeaters(self): # """Return the numer of repeaters in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) > 1) # except TypeError: # return 0 # # def n_rep(self): # return self.n_repeaters() # # def n_one_offs(self): # """Return the numer of one-offs in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) <= 1) # except TypeError: # return self.n_sources() # # def n_oneoffs(self): # """Return the numer of one-offs in a population.""" # return self.n_one_offs() . Output only the next line.
super(TNS, self).__init__(**kwargs, path=paths.frbcat())
Next line prediction: <|code_start|> self.df.at[pmsurv, 'survey'] = 'parkes-pmsurv' htru = cond('Parkes') & (self.df[c].dt.year > 2008) htru &= (self.df[c].dt.year < 2015) self.df.at[htru, 'survey'] = 'parkes-htru' # This means the default survey for Parkes is superb! superb = cond('Parkes') & (self.df[c].dt.year >= 2015) self.df.at[superb, 'survey'] = 'parkes-superb' # Manually add some tricky ones self.df.at[self.df.name == 'FRB 20010125A', 'survey'] = 'parkes-swmb' self.df.at[self.df.name == 'FRB 20150807A', 'survey'] = 'parkes-party' ppta = [171209, 171209, 180309, 180309, 180311, 180311, 180714, 180714] for frb in ppta: mask = self.df.name == f'FRB 20{frb}A' self.df.at[mask, 'survey'] = 'parkes-ppta' # Check whether any FRBs have not yet been assigned no_surveys = self.df['survey'].isnull() if interrupt and any(no_surveys): pprint(f'There are {sum(no_surveys)} FRBs with undefined surveys') m = 'TNS().match_surveys() in frbpoppy/tns.py should be updated' pprint(m) def to_pop(self, df=None): """ Convert to a Population object. """ if not isinstance(df, pd.DataFrame): df = self.df <|code_end|> . Use current file imports: (import pandas as pd import IPython; IPython.embed() from frbcat import TNS as BaseTNS from frbpoppy.misc import pprint from frbpoppy.paths import paths from frbpoppy.population import Population) and context including class names, function names, or small code snippets from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/population.py # class Population: # """Class to hold a population of FRBs.""" # # def __init__(self): # """Initializing.""" # # Population properties # self.name = None # # # Frequency emission limits [MHz] # self.f_max = None # self.f_min = None # # # Store FRB sources # self.frbs = FRBs() # self.uid = None # Unique Identifier # # def __str__(self): # """Define how to print a population object to a console.""" # s = 'Population properties:' # # # TODO: Code this to print all properties # # return s # # def to_df(self): # """Gather source values into a pandas dataframe.""" # df = self.frbs.to_df() # return df # # def save(self, path=None): # """ # Write out source properties as data file. # # Args: # path (str): Path to which to save. # """ # if path is None: # # Check if a population has been a survey name # if not self.name: # file_name = 'pop' # else: # file_name = self.name.lower() # # if self.uid: # file_name += f'_{self.uid}' # # path = paths.populations() + f'{file_name}.p' # # self.to_pickle(path) # # def to_csv(self, path): # """Write a population to a csv file. # # Args: # path (str): Path to which to write # # """ # df = self.frbs.to_df() # df.to_csv(path) # # def to_pickle(self, path): # """Write a population to a pickled file for future use. # # Args: # path (str): Path to which to write # # """ # output = open(path, 'wb') # pickle.dump(self, output, 2) # output.close() # # def n_sources(self): # """Return the number of FRB sources.""" # return len(self.frbs.ra) # # def n_srcs(self): # return self.n_sources() # # def n_bursts(self): # """Return the number of bursts.""" # try: # Will only work for a repeater population # n = np.count_nonzero(~np.isnan(self.frbs.time)) # except TypeError: # n = self.n_sources() # return n # # def n_repeaters(self): # """Return the numer of repeaters in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) > 1) # except TypeError: # return 0 # # def n_rep(self): # return self.n_repeaters() # # def n_one_offs(self): # """Return the numer of one-offs in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) <= 1) # except TypeError: # return self.n_sources() # # def n_oneoffs(self): # """Return the numer of one-offs in a population.""" # return self.n_one_offs() . Output only the next line.
pop = Population()
Here is a snippet: <|code_start|> Args: lat (float): Latitude of observatory in radians. dec (array): Declination of celestial object in radians. unit (str): 'deg' or 'rad' beamsize (float): Beam size in sq. deg Returns: float: Fraction of time above horizon in fractional days """ if unit == 'deg': lat = np.deg2rad(lat) dec = np.deg2rad(dec) times = np.ones_like(dec) lim = np.pi/2. - lat always_visible = dec > lim never_visible = dec < -lim sometimes_visible = ((dec > -lim) & (dec < lim)) sm = sometimes_visible times[sm] = 2*np.rad2deg(np.arccos(-np.tan(dec[sm])*np.tan(lat)))/360. times[always_visible] = 1. times[never_visible] = 0. return times if TEST_TRANSIT: <|code_end|> . Write the next line using the current file imports: import numpy as np import matplotlib.pyplot as plt import os from tests.convenience import plot_aa_style, rel_path and context from other files: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) , which may include functions, classes, or code. Output only the next line.
plot_aa_style()
Based on the snippet: <|code_start|> """ if unit == 'deg': lat = np.deg2rad(lat) dec = np.deg2rad(dec) times = np.ones_like(dec) lim = np.pi/2. - lat always_visible = dec > lim never_visible = dec < -lim sometimes_visible = ((dec > -lim) & (dec < lim)) sm = sometimes_visible times[sm] = 2*np.rad2deg(np.arccos(-np.tan(dec[sm])*np.tan(lat)))/360. times[always_visible] = 1. times[never_visible] = 0. return times if TEST_TRANSIT: plot_aa_style() latitude_obs = 52. # deg decs = np.linspace(-90, 90, 100) lat = latitude_obs times = calc_transit_time(lat, decs) plt.ylabel('Fraction of day at which visible') plt.xlabel('Declination sources') plt.plot(decs, times) plt.tight_layout() <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import matplotlib.pyplot as plt import os from tests.convenience import plot_aa_style, rel_path and context (classes, functions, sometimes code) from other files: # Path: tests/convenience.py # def plot_aa_style(cols=1): # """Use a plotting style specifically for Astronomy & Astrophyiscs.""" # # Use a style file # dir = os.path.abspath(os.path.dirname(__file__)) # style_file = os.path.join(dir, './aa.mplstyle') # plt.style.use(style_file) # # # Check whether interactive backend is present # if os.name == 'posix' and "DISPLAY" not in os.environ: # # On a cluster # plt.switch_backend('Agg') # # Use just the basic latex package allowing \text to be used # plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' # # if cols == 2: # plt.rcParams["figure.figsize"] = (5.75373, 3.556) # # def rel_path(path): # """Return the relative path name for this directory.""" # return os.path.join(os.path.abspath(os.path.dirname(__file__)), path) . Output only the next line.
plt.savefig(rel_path('./plots/transit_times.pdf'))
Given snippet: <|code_start|> class NE2001Table: """Create/use a NE2001 lookup table for dispersion measure.""" def __init__(self, test=False): """Initializing.""" self.test = test self.set_file_name() # Setup database self.db = False self.step = 0.1 self.rounding = 2 # For parallel processes self.temp_path = None if self.test: self.step = 0.1 if os.path.exists(self.file_name): os.remove(self.file_name) if os.path.exists(self.file_name) and self.test is False: self.db = True else: # Calculations take quite some time # Provide a way for people to quit try: self.create_table() except KeyboardInterrupt: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import numpy as np import sqlite3 import sys import frbpoppy.galacticops as go from scipy.integrate import quad from tqdm import tqdm from joblib import Parallel, delayed from frbpoppy.misc import pprint from frbpoppy.paths import paths and context: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): which might include code, classes, or functions. Output only the next line.
pprint('Losing all progress in calculations')
Predict the next line for this snippet: <|code_start|> # Setup database self.db = False self.step = 0.1 self.rounding = 2 # For parallel processes self.temp_path = None if self.test: self.step = 0.1 if os.path.exists(self.file_name): os.remove(self.file_name) if os.path.exists(self.file_name) and self.test is False: self.db = True else: # Calculations take quite some time # Provide a way for people to quit try: self.create_table() except KeyboardInterrupt: pprint('Losing all progress in calculations') os.remove(self.file_name) if self.temp: os.remove(self.temp_path) sys.exit() def set_file_name(self): """Determine filename.""" <|code_end|> with the help of current file imports: import os import numpy as np import sqlite3 import sys import frbpoppy.galacticops as go from scipy.integrate import quad from tqdm import tqdm from joblib import Parallel, delayed from frbpoppy.misc import pprint from frbpoppy.paths import paths and context from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): , which may contain function names, class names, or code. Output only the next line.
uni_mods = os.path.join(paths.models(), 'universe/')
Predict the next line after this snippet: <|code_start|> """Match up frbs with surveys.""" # Merge survey names surf = os.path.join(self.path, 'paper_survey.csv') self._surveys = pd.read_csv(surf) cols = ['frb_name', 'pub_description'] self.df = pd.merge(self.df, self._surveys, on=cols, how='left') # Clean up possible unnamed columns self.df = self.df.loc[:, ~self.df.columns.str.contains('unnamed')] # Add single survey instruments # Bit rough, but will work in a pinch def cond(t): return (self.df.telescope == t) & (self.df.survey.isnull()) self.df.at[cond('wsrt-apertif'), 'survey'] = 'wsrt-apertif' self.df.at[cond('askap'), 'survey'] = 'askap-incoh' self.df.at[cond('chime'), 'survey'] = 'chime' self.df.at[cond('srt'), 'survey'] = 'srt' self.df.at[cond('effelsberg'), 'survey'] = 'effelsberg' self.df.at[cond('gbt'), 'survey'] = 'guppi' self.df.at[cond('fast'), 'survey'] = 'crafts' # Check whether any FRBs have not yet been assigned no_surveys = self.df['survey'].isnull() if interrupt and any(no_surveys): cols = ['pub_description', 'frb_name'] ns_df = self.df[no_surveys].drop_duplicates(subset=cols, keep='first') <|code_end|> using the current file's imports: import os import pandas as pd import IPython from frbcat import Frbcat as PureFrbcat from frbpoppy.misc import pprint from frbpoppy.paths import paths from frbpoppy.population import Population and any relevant context from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/population.py # class Population: # """Class to hold a population of FRBs.""" # # def __init__(self): # """Initializing.""" # # Population properties # self.name = None # # # Frequency emission limits [MHz] # self.f_max = None # self.f_min = None # # # Store FRB sources # self.frbs = FRBs() # self.uid = None # Unique Identifier # # def __str__(self): # """Define how to print a population object to a console.""" # s = 'Population properties:' # # # TODO: Code this to print all properties # # return s # # def to_df(self): # """Gather source values into a pandas dataframe.""" # df = self.frbs.to_df() # return df # # def save(self, path=None): # """ # Write out source properties as data file. # # Args: # path (str): Path to which to save. # """ # if path is None: # # Check if a population has been a survey name # if not self.name: # file_name = 'pop' # else: # file_name = self.name.lower() # # if self.uid: # file_name += f'_{self.uid}' # # path = paths.populations() + f'{file_name}.p' # # self.to_pickle(path) # # def to_csv(self, path): # """Write a population to a csv file. # # Args: # path (str): Path to which to write # # """ # df = self.frbs.to_df() # df.to_csv(path) # # def to_pickle(self, path): # """Write a population to a pickled file for future use. # # Args: # path (str): Path to which to write # # """ # output = open(path, 'wb') # pickle.dump(self, output, 2) # output.close() # # def n_sources(self): # """Return the number of FRB sources.""" # return len(self.frbs.ra) # # def n_srcs(self): # return self.n_sources() # # def n_bursts(self): # """Return the number of bursts.""" # try: # Will only work for a repeater population # n = np.count_nonzero(~np.isnan(self.frbs.time)) # except TypeError: # n = self.n_sources() # return n # # def n_repeaters(self): # """Return the numer of repeaters in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) > 1) # except TypeError: # return 0 # # def n_rep(self): # return self.n_repeaters() # # def n_one_offs(self): # """Return the numer of one-offs in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) <= 1) # except TypeError: # return self.n_sources() # # def n_oneoffs(self): # """Return the numer of one-offs in a population.""" # return self.n_one_offs() . Output only the next line.
pprint('It seems there are new FRBs!')
Given the code snippet: <|code_start|>"""Do things with frbcat.""" class Frbcat(PureFrbcat): """ Add frbpoppy functionality to Frbcat. Get the pandas dataframe with Frbcat().df """ def __init__(self, frbpoppy=True, repeat_bursts=False, mute=False, **kwargs): """Initialize.""" <|code_end|> , generate the next line using the imports in this file: import os import pandas as pd import IPython from frbcat import Frbcat as PureFrbcat from frbpoppy.misc import pprint from frbpoppy.paths import paths from frbpoppy.population import Population and context (functions, classes, or occasionally code) from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/population.py # class Population: # """Class to hold a population of FRBs.""" # # def __init__(self): # """Initializing.""" # # Population properties # self.name = None # # # Frequency emission limits [MHz] # self.f_max = None # self.f_min = None # # # Store FRB sources # self.frbs = FRBs() # self.uid = None # Unique Identifier # # def __str__(self): # """Define how to print a population object to a console.""" # s = 'Population properties:' # # # TODO: Code this to print all properties # # return s # # def to_df(self): # """Gather source values into a pandas dataframe.""" # df = self.frbs.to_df() # return df # # def save(self, path=None): # """ # Write out source properties as data file. # # Args: # path (str): Path to which to save. # """ # if path is None: # # Check if a population has been a survey name # if not self.name: # file_name = 'pop' # else: # file_name = self.name.lower() # # if self.uid: # file_name += f'_{self.uid}' # # path = paths.populations() + f'{file_name}.p' # # self.to_pickle(path) # # def to_csv(self, path): # """Write a population to a csv file. # # Args: # path (str): Path to which to write # # """ # df = self.frbs.to_df() # df.to_csv(path) # # def to_pickle(self, path): # """Write a population to a pickled file for future use. # # Args: # path (str): Path to which to write # # """ # output = open(path, 'wb') # pickle.dump(self, output, 2) # output.close() # # def n_sources(self): # """Return the number of FRB sources.""" # return len(self.frbs.ra) # # def n_srcs(self): # return self.n_sources() # # def n_bursts(self): # """Return the number of bursts.""" # try: # Will only work for a repeater population # n = np.count_nonzero(~np.isnan(self.frbs.time)) # except TypeError: # n = self.n_sources() # return n # # def n_repeaters(self): # """Return the numer of repeaters in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) > 1) # except TypeError: # return 0 # # def n_rep(self): # return self.n_repeaters() # # def n_one_offs(self): # """Return the numer of one-offs in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) <= 1) # except TypeError: # return self.n_sources() # # def n_oneoffs(self): # """Return the numer of one-offs in a population.""" # return self.n_one_offs() . Output only the next line.
super().__init__(self, path=paths.frbcat(), **kwargs)
Here is a snippet: <|code_start|> if interrupt and any(no_surveys): cols = ['pub_description', 'frb_name'] ns_df = self.df[no_surveys].drop_duplicates(subset=cols, keep='first') pprint('It seems there are new FRBs!') m = " - Frbcat doesn't know which *survey* was running when the " m += "FRB was seen" pprint(m) m = " - To use these recent detections, please link the FRB to a " m += "survey by:" pprint(m) pprint(' - Adding these frbs to {}'.format(surf)) for i, r in ns_df[cols].iterrows(): title, name = r if isinstance(title, str): title = title.replace('\n', '') print(f'"{title}","{name}",""') def to_pop(self, df=None): """ Convert to a Population object. Please ensure self.clean() has been run first. """ if not isinstance(df, pd.DataFrame): df = self.df <|code_end|> . Write the next line using the current file imports: import os import pandas as pd import IPython from frbcat import Frbcat as PureFrbcat from frbpoppy.misc import pprint from frbpoppy.paths import paths from frbpoppy.population import Population and context from other files: # Path: frbpoppy/misc.py # def pprint(*s, output=True): # """Hack to make for more informative print statements.""" # f = inspect.stack()[1][1].split('/')[-1] # m = '{:13.13} |'.format(f) # # if output: # print(m, *s) # else: # lines = [] # for e in s: # lines.append('\n'.join([f'{m} {f}' for f in e.split('\n')])) # return '\n'.join(lines) # # Path: frbpoppy/paths.py # class Paths(): # def __init__(self): # def __str__(self): # def check(self, path): # def store(self, name, default, *args): # def data(self, *args): # def populations(self, *args): # def surveys(self, *args): # def models(self, *args): # def frbcat(self, *args): # # Path: frbpoppy/population.py # class Population: # """Class to hold a population of FRBs.""" # # def __init__(self): # """Initializing.""" # # Population properties # self.name = None # # # Frequency emission limits [MHz] # self.f_max = None # self.f_min = None # # # Store FRB sources # self.frbs = FRBs() # self.uid = None # Unique Identifier # # def __str__(self): # """Define how to print a population object to a console.""" # s = 'Population properties:' # # # TODO: Code this to print all properties # # return s # # def to_df(self): # """Gather source values into a pandas dataframe.""" # df = self.frbs.to_df() # return df # # def save(self, path=None): # """ # Write out source properties as data file. # # Args: # path (str): Path to which to save. # """ # if path is None: # # Check if a population has been a survey name # if not self.name: # file_name = 'pop' # else: # file_name = self.name.lower() # # if self.uid: # file_name += f'_{self.uid}' # # path = paths.populations() + f'{file_name}.p' # # self.to_pickle(path) # # def to_csv(self, path): # """Write a population to a csv file. # # Args: # path (str): Path to which to write # # """ # df = self.frbs.to_df() # df.to_csv(path) # # def to_pickle(self, path): # """Write a population to a pickled file for future use. # # Args: # path (str): Path to which to write # # """ # output = open(path, 'wb') # pickle.dump(self, output, 2) # output.close() # # def n_sources(self): # """Return the number of FRB sources.""" # return len(self.frbs.ra) # # def n_srcs(self): # return self.n_sources() # # def n_bursts(self): # """Return the number of bursts.""" # try: # Will only work for a repeater population # n = np.count_nonzero(~np.isnan(self.frbs.time)) # except TypeError: # n = self.n_sources() # return n # # def n_repeaters(self): # """Return the numer of repeaters in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) > 1) # except TypeError: # return 0 # # def n_rep(self): # return self.n_repeaters() # # def n_one_offs(self): # """Return the numer of one-offs in a population.""" # try: # return np.sum((~np.isnan(self.frbs.time)).sum(1) <= 1) # except TypeError: # return self.n_sources() # # def n_oneoffs(self): # """Return the numer of one-offs in a population.""" # return self.n_one_offs() , which may include functions, classes, or code. Output only the next line.
pop = Population()
Based on the snippet: <|code_start|> def test_generate_name(): class SomeTestClass(object): pass def some_test_function(): pass <|code_end|> , predict the immediate next line with the help of imports: from tensorprob import utilities and context (classes, functions, sometimes code) from other files: # Path: tensorprob/utilities.py # NAME_COUNTERS = defaultdict(lambda: 0) # def generate_name(obj): # def __init__(self, getter): # def __get__(self, instance, owner): # def grouper(iterable, n=2, fillvalue=None): # def flatten(l): # def is_finite(obj): # def pairwise(iterable): # def set_logp_to_neg_inf(X, logp, bounds): # def find_common_bounds(bounds_1, bounds_2): # class classproperty(object): . Output only the next line.
assert utilities.generate_name(SomeTestClass) == 'SomeTestClass_1'
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import class Min_Func: def __init__(self, f, names): self.f = f self.func_code = make_func_code(names) self.func_defaults = None def __call__(self, *args): return self.f(args) <|code_end|> with the help of current file imports: import numpy as np import iminuit from .base import BaseOptimizer from ..optimization_result import OptimizationResult from iminuit.util import make_func_code and context from other files: # Path: tensorprob/optimizers/base.py # class BaseOptimizer(object): # # def __init__(self, session=None): # self._session = session or tf.Session() # # def minimize_impl(self, objective, gradient, inits, bounds): # raise NotImplementedError # # def minimize(self, variables, cost, gradient=None, bounds=None): # # Check if variables is iterable # if not isinstance(variables, Iterable): # raise ValueError("Variables parameter is not iterable") # # for v in variables: # if not isinstance(v, tf.Variable): # raise ValueError("Parameter {} is not a tensorflow variable".format(v)) # # inits = self._session.run(variables) # # def objective(xs): # feed_dict = {k: v for k, v in zip(variables, xs)} # # Cast just in case the user-supplied function returns something else # val = np.float64(self._session.run(cost, feed_dict=feed_dict)) # logger.debug('Objective: {} {}'.format(val, xs)) # return val # # if gradient is not None: # def gradient_(xs): # feed_dict = {k: v for k, v in zip(variables, xs)} # # Cast just in case the user-supplied function returns something else # val = np.array(self._session.run(gradient, feed_dict=feed_dict)) # logger.debug('Gradient: {} {}'.format(val, xs)) # return val # approx_grad = False # else: # gradient_ = None # # if bounds: # min_bounds = [] # for current in bounds: # lower, upper = current # # if isinstance(lower, tf.Tensor) or isinstance(upper, tf.Tensor): # raise NotImplementedError("Specifying variable bounds to optimizers is not yet supported") # # # Translate inf to None, which is what this minimizer understands # if lower is not None and np.isinf(lower): # lower = None # if upper is not None and np.isinf(upper): # upper = None # # This optimizer likes to evaluate the function at the boundaries. # # Slightly move the bounds so that the edges are not included. # if lower is not None: # lower = lower + 1e-10 # if upper is not None: # upper = upper - 1e-10 # # min_bounds.append((lower, upper)) # else: # min_bounds = None # # return self.minimize_impl(objective, gradient_, inits, min_bounds) # # # @property # def session(self): # return self._session # # @session.setter # def session(self, session): # self._session = session # # Path: tensorprob/optimization_result.py # class OptimizationResult(dict): # # def __getattr__(self, name): # try: # return self[name] # except KeyError: # raise AttributeError(name) # # __setattr__ = dict.__setitem__ # __delattr__ = dict.__delitem__ # # def __repr__(self): # if self.keys(): # header = '\n' + self.__class__.__name__ + ':\n' # m = max(map(len, list(self.keys()))) + 1 # return header + '\n'.join([k.rjust(m) + ': ' + repr(v) # for k, v in sorted(self.items())]) # else: # return self.__class__.__name__ + "()" , which may contain function names, class names, or code. Output only the next line.
class MigradOptimizer(BaseOptimizer):
Based on the snippet: <|code_start|> all_kwargs['limit_' + n] = b if gradient: def mygrad_func(*x): out = gradient(x) return out else: mygrad_func = None def objective_(x): val = objective(x) if np.isnan(val) or np.isinf(val): return 1e10 return val m = self.iminuit.Minuit( Min_Func(objective_, names), grad_fcn=mygrad_func, print_level=print_level, errordef=1, **all_kwargs ) m.set_strategy(2) a, b = m.migrad() x = [] for name in names: x.append(m.values[name]) <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import iminuit from .base import BaseOptimizer from ..optimization_result import OptimizationResult from iminuit.util import make_func_code and context (classes, functions, sometimes code) from other files: # Path: tensorprob/optimizers/base.py # class BaseOptimizer(object): # # def __init__(self, session=None): # self._session = session or tf.Session() # # def minimize_impl(self, objective, gradient, inits, bounds): # raise NotImplementedError # # def minimize(self, variables, cost, gradient=None, bounds=None): # # Check if variables is iterable # if not isinstance(variables, Iterable): # raise ValueError("Variables parameter is not iterable") # # for v in variables: # if not isinstance(v, tf.Variable): # raise ValueError("Parameter {} is not a tensorflow variable".format(v)) # # inits = self._session.run(variables) # # def objective(xs): # feed_dict = {k: v for k, v in zip(variables, xs)} # # Cast just in case the user-supplied function returns something else # val = np.float64(self._session.run(cost, feed_dict=feed_dict)) # logger.debug('Objective: {} {}'.format(val, xs)) # return val # # if gradient is not None: # def gradient_(xs): # feed_dict = {k: v for k, v in zip(variables, xs)} # # Cast just in case the user-supplied function returns something else # val = np.array(self._session.run(gradient, feed_dict=feed_dict)) # logger.debug('Gradient: {} {}'.format(val, xs)) # return val # approx_grad = False # else: # gradient_ = None # # if bounds: # min_bounds = [] # for current in bounds: # lower, upper = current # # if isinstance(lower, tf.Tensor) or isinstance(upper, tf.Tensor): # raise NotImplementedError("Specifying variable bounds to optimizers is not yet supported") # # # Translate inf to None, which is what this minimizer understands # if lower is not None and np.isinf(lower): # lower = None # if upper is not None and np.isinf(upper): # upper = None # # This optimizer likes to evaluate the function at the boundaries. # # Slightly move the bounds so that the edges are not included. # if lower is not None: # lower = lower + 1e-10 # if upper is not None: # upper = upper - 1e-10 # # min_bounds.append((lower, upper)) # else: # min_bounds = None # # return self.minimize_impl(objective, gradient_, inits, min_bounds) # # # @property # def session(self): # return self._session # # @session.setter # def session(self, session): # self._session = session # # Path: tensorprob/optimization_result.py # class OptimizationResult(dict): # # def __getattr__(self, name): # try: # return self[name] # except KeyError: # raise AttributeError(name) # # __setattr__ = dict.__setitem__ # __delattr__ = dict.__delitem__ # # def __repr__(self): # if self.keys(): # header = '\n' + self.__class__.__name__ + ':\n' # m = max(map(len, list(self.keys()))) + 1 # return header + '\n'.join([k.rjust(m) + ': ' + repr(v) # for k, v in sorted(self.items())]) # else: # return self.__class__.__name__ + "()" . Output only the next line.
return OptimizationResult(
Given the following code snippet before the placeholder: <|code_start|> super(ScipyLBFGSBOptimizer, self).__init__(**kwargs) def minimize_impl(self, objective, gradient, inits, bounds): if gradient is None: approx_grad = True else: approx_grad = False self.niter = 0 def callback(xs): self.niter += 1 if self.verbose: if self.niter % 50 == 0: print('iter ', '\t'.join([x.name.split(':')[0] for x in variables])) print('{: 4d} {}'.format(self.niter, '\t'.join(map(str, xs)))) if self.callback is not None: self.callback(xs) results = fmin_l_bfgs_b( objective, inits, m=self.m, fprime=gradient, factr=self.factr, pgtol=self.pgtol, callback=callback, approx_grad=approx_grad, bounds=bounds, ) <|code_end|> , predict the next line using imports from the current file: import numpy as np import tensorflow as tf from scipy.optimize import fmin_l_bfgs_b from ..optimization_result import OptimizationResult from .base import BaseOptimizer and context including class names, function names, and sometimes code from other files: # Path: tensorprob/optimization_result.py # class OptimizationResult(dict): # # def __getattr__(self, name): # try: # return self[name] # except KeyError: # raise AttributeError(name) # # __setattr__ = dict.__setitem__ # __delattr__ = dict.__delitem__ # # def __repr__(self): # if self.keys(): # header = '\n' + self.__class__.__name__ + ':\n' # m = max(map(len, list(self.keys()))) + 1 # return header + '\n'.join([k.rjust(m) + ': ' + repr(v) # for k, v in sorted(self.items())]) # else: # return self.__class__.__name__ + "()" # # Path: tensorprob/optimizers/base.py # class BaseOptimizer(object): # # def __init__(self, session=None): # self._session = session or tf.Session() # # def minimize_impl(self, objective, gradient, inits, bounds): # raise NotImplementedError # # def minimize(self, variables, cost, gradient=None, bounds=None): # # Check if variables is iterable # if not isinstance(variables, Iterable): # raise ValueError("Variables parameter is not iterable") # # for v in variables: # if not isinstance(v, tf.Variable): # raise ValueError("Parameter {} is not a tensorflow variable".format(v)) # # inits = self._session.run(variables) # # def objective(xs): # feed_dict = {k: v for k, v in zip(variables, xs)} # # Cast just in case the user-supplied function returns something else # val = np.float64(self._session.run(cost, feed_dict=feed_dict)) # logger.debug('Objective: {} {}'.format(val, xs)) # return val # # if gradient is not None: # def gradient_(xs): # feed_dict = {k: v for k, v in zip(variables, xs)} # # Cast just in case the user-supplied function returns something else # val = np.array(self._session.run(gradient, feed_dict=feed_dict)) # logger.debug('Gradient: {} {}'.format(val, xs)) # return val # approx_grad = False # else: # gradient_ = None # # if bounds: # min_bounds = [] # for current in bounds: # lower, upper = current # # if isinstance(lower, tf.Tensor) or isinstance(upper, tf.Tensor): # raise NotImplementedError("Specifying variable bounds to optimizers is not yet supported") # # # Translate inf to None, which is what this minimizer understands # if lower is not None and np.isinf(lower): # lower = None # if upper is not None and np.isinf(upper): # upper = None # # This optimizer likes to evaluate the function at the boundaries. # # Slightly move the bounds so that the edges are not included. # if lower is not None: # lower = lower + 1e-10 # if upper is not None: # upper = upper - 1e-10 # # min_bounds.append((lower, upper)) # else: # min_bounds = None # # return self.minimize_impl(objective, gradient_, inits, min_bounds) # # # @property # def session(self): # return self._session # # @session.setter # def session(self, session): # self._session = session . Output only the next line.
ret = OptimizationResult()
Given the code snippet: <|code_start|> logFull('CeWebUi:index') if self.user_agent() == 'x': return 0 try: srv_ver = open(TWISTER_PATH + '/server/version.txt').read().strip() except: srv_ver = '-' srv_type = self.project.server_init['ce_server_type'] ip_port = cherrypy.request.headers['Host'] machine = platform.uname()[1] system = ' '.join(platform.linux_distribution()) users = self.project.list_users() output = Template(filename=TWISTER_PATH + '/server/template/rest_main.htm') return output.render(srv_type=srv_type, srv_ver=srv_ver,\ ip_port=ip_port, machine=machine, system=system, users=users) @cherrypy.expose def users(self, user=''): """ list all users """ logFull('CeWebUi:users') if self.user_agent() == 'x': return 0 if not user: raise cherrypy.HTTPRedirect('/web/#tab_users') host = cherrypy.request.headers['Host'] rev_dict = dict((v, k) for k, v in EXEC_STATUS.iteritems()) <|code_end|> , generate the next line using the imports in this file: import os, sys import json import platform import mako import cherrypy from mako.template import Template from binascii import unhexlify as decode from common.constants import STATUS_INVALID, EXEC_STATUS from common.helpers import calcMemory, calcCpu, dirList from common.tsclogging import logWarning, logFull, logDebug, LOG_FILE and context (functions, classes, or occasionally code) from other files: # Path: common/constants.py # STATUS_INVALID = 8 # Invalid status # # EXEC_STATUS = {'stopped':STATUS_STOP, 'paused':STATUS_PAUSED, 'running':STATUS_RUNNING, 'resume':STATUS_RESUME, # 'invalid':STATUS_INVALID, 'interact': STATUS_INTERACT, 'restart': STATUS_RESTART} . Output only the next line.
int_status = self.project.get_user_info(user, 'status') or STATUS_INVALID
Given snippet: <|code_start|> """ Initial page """ logFull('CeWebUi:index') if self.user_agent() == 'x': return 0 try: srv_ver = open(TWISTER_PATH + '/server/version.txt').read().strip() except: srv_ver = '-' srv_type = self.project.server_init['ce_server_type'] ip_port = cherrypy.request.headers['Host'] machine = platform.uname()[1] system = ' '.join(platform.linux_distribution()) users = self.project.list_users() output = Template(filename=TWISTER_PATH + '/server/template/rest_main.htm') return output.render(srv_type=srv_type, srv_ver=srv_ver,\ ip_port=ip_port, machine=machine, system=system, users=users) @cherrypy.expose def users(self, user=''): """ list all users """ logFull('CeWebUi:users') if self.user_agent() == 'x': return 0 if not user: raise cherrypy.HTTPRedirect('/web/#tab_users') host = cherrypy.request.headers['Host'] <|code_end|> , continue by predicting the next line. Consider current file imports: import os, sys import json import platform import mako import cherrypy from mako.template import Template from binascii import unhexlify as decode from common.constants import STATUS_INVALID, EXEC_STATUS from common.helpers import calcMemory, calcCpu, dirList from common.tsclogging import logWarning, logFull, logDebug, LOG_FILE and context: # Path: common/constants.py # STATUS_INVALID = 8 # Invalid status # # EXEC_STATUS = {'stopped':STATUS_STOP, 'paused':STATUS_PAUSED, 'running':STATUS_RUNNING, 'resume':STATUS_RESUME, # 'invalid':STATUS_INVALID, 'interact': STATUS_INTERACT, 'restart': STATUS_RESTART} which might include code, classes, or functions. Output only the next line.
rev_dict = dict((v, k) for k, v in EXEC_STATUS.iteritems())
Predict the next line after this snippet: <|code_start|> class SendTest(BaseTest): def setUp(self): super(SendTest,self).setUp() <|code_end|> using the current file's imports: from test_base import BaseTest, load_msg from mock import patch from smtplib import SMTP from deliver.send import Sender and any relevant context from other files: # Path: deliver/send.py # class Sender: # ''' # Class that is responsible of sending emails. It uses a specified SMTP server. # ''' # # def __init__(self, config): # self._cfg = config # # def send(self, msg, *recipients): # ''' # Sends the given UnicodeMessage to each of the specified recipients. # ''' # assert isinstance(msg, UnicodeMessage) # for recipient in recipients: # assert isinstance(recipient, unicode) # self._send(msg, *recipients) # # def _send(self, msg, *recipients): # ''' # Sends the given UnicodeMessage to each of # the specified recipients. # # The emails are sent from the specified server, using the specified address. The subject # is modified to include a subject prefix if it is not already there. # ''' # msg.replace_header('Subject', self._prepare_subject(msg['Subject'])) # msg.replace_header('From', self.get_address()) # msg.replace_header('Reply-To', self.get_address()) # logging.debug('email ready to be sent: %s', msg['Message-Id']) # for recipient in recipients: # logger.debug('Sending message to %s', recipient) # s = smtplib.SMTP(self._cfg['smtp_server']) # msg.replace_header('To', recipient) # s.sendmail(self.get_address(), recipient, msg.as_string()) # s.quit() # # def get_address(self): # '''Gets the address used by this sender''' # return self._cfg['sender'] # # def _prepare_subject(self, subject): # '''Modifies the given subject to include a prefix if it is not already there''' # if self._cfg['subject_prefix'] in subject: # return subject # return self._cfg['subject_prefix'] + ' ' + subject . Output only the next line.
self.sender = Sender(self.config)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class ConverterDigestTest(BaseTest): '''Tests for the DigestMessage class''' def setUp(self): super(ConverterDigestTest,self).setUp() self.msg = DigestMessage([]) def test_find_text(self): <|code_end|> , predict the immediate next line with the help of imports: from deliver.tests.test_base import BaseTest, load_msg from deliver.converter.digest import DigestMessage and context (classes, functions, sometimes code) from other files: # Path: deliver/tests/test_base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # from test_data.test_config import py # self.config = py.copy() # # def tearDown(self): # super(BaseTest,self).tearDown() # if os.path.isfile(self.config['db_name']): # os.remove(self.config['db_name']) # # def load_msg(fileName): # '''Loads the message contained in the given file and returns it as # an UnicodeMessage.''' # return UnicodeMessage(email.message_from_file(open_data(fileName))) # # Path: deliver/converter/digest.py # class DigestMessage(UnicodeMessage): # ''' # This is a class used to build a digest from a list of emails. All # the emails are summarized in a single body of plain text. Any # other attachments or extra content is ignored. # ''' # # def __init__(self, msg_list): # ''' # Builds a summary mail from the given list and passes it to the # UnicodeMessage constructor. # ''' # for msg in msg_list: # if not isinstance(msg, UnicodeMessage): # raise TypeError('msg is not a Message') # # super(DigestMessage,self).__init__(self._build_mail(msg_list)) # self._complete_headers() # # def _complete_headers(self): # '''Fill the headers of the mail''' # complete_headers(self, u'Digest for %s' % datetime.now(), 'digest') # # def _build_mail(self, msg_list): # '''Returns a mail that contains all the given mails as a single text''' # return build_text_mail(self._merge_mails(msg_list)) # # def _merge_mails(self, msg_list): # ''' # Merge the content of all the given mails into one unicode # string that can be used as the payload of the digest mail. # ''' # space = u'\n' * 2 # messages = [(msg['Subject'], self._find_text(msg)) for msg in msg_list] # messages = [u'==== ' + subject + u' ====' # + space + payload for subject, payload in messages] # return (space + (u'*' * 75) + space).join(messages) # # def _find_text(self, msg): # ''' # Returns the plain text part in a message. If no plain text is # present, any other text is returned. If there is no text part # at all, an empty string is returned. # # The text is decoded and returned as an unicode string. # ''' # fallback = u'' # for part in msg.walk(): # if 'text' == part.get_content_maintype(): # if part.get_content_subtype() == 'plain': # return part.get_payload(decode=True) # fallback = part.get_payload(decode=True) # return fallback . Output only the next line.
self.assertEqual(self.msg._find_text(load_msg('sample5')), u'á')
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class ConverterDigestTest(BaseTest): '''Tests for the DigestMessage class''' def setUp(self): super(ConverterDigestTest,self).setUp() <|code_end|> , determine the next line of code. You have imports: from deliver.tests.test_base import BaseTest, load_msg from deliver.converter.digest import DigestMessage and context (class names, function names, or code) available: # Path: deliver/tests/test_base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # from test_data.test_config import py # self.config = py.copy() # # def tearDown(self): # super(BaseTest,self).tearDown() # if os.path.isfile(self.config['db_name']): # os.remove(self.config['db_name']) # # def load_msg(fileName): # '''Loads the message contained in the given file and returns it as # an UnicodeMessage.''' # return UnicodeMessage(email.message_from_file(open_data(fileName))) # # Path: deliver/converter/digest.py # class DigestMessage(UnicodeMessage): # ''' # This is a class used to build a digest from a list of emails. All # the emails are summarized in a single body of plain text. Any # other attachments or extra content is ignored. # ''' # # def __init__(self, msg_list): # ''' # Builds a summary mail from the given list and passes it to the # UnicodeMessage constructor. # ''' # for msg in msg_list: # if not isinstance(msg, UnicodeMessage): # raise TypeError('msg is not a Message') # # super(DigestMessage,self).__init__(self._build_mail(msg_list)) # self._complete_headers() # # def _complete_headers(self): # '''Fill the headers of the mail''' # complete_headers(self, u'Digest for %s' % datetime.now(), 'digest') # # def _build_mail(self, msg_list): # '''Returns a mail that contains all the given mails as a single text''' # return build_text_mail(self._merge_mails(msg_list)) # # def _merge_mails(self, msg_list): # ''' # Merge the content of all the given mails into one unicode # string that can be used as the payload of the digest mail. # ''' # space = u'\n' * 2 # messages = [(msg['Subject'], self._find_text(msg)) for msg in msg_list] # messages = [u'==== ' + subject + u' ====' # + space + payload for subject, payload in messages] # return (space + (u'*' * 75) + space).join(messages) # # def _find_text(self, msg): # ''' # Returns the plain text part in a message. If no plain text is # present, any other text is returned. If there is no text part # at all, an empty string is returned. # # The text is decoded and returned as an unicode string. # ''' # fallback = u'' # for part in msg.walk(): # if 'text' == part.get_content_maintype(): # if part.get_content_subtype() == 'plain': # return part.get_payload(decode=True) # fallback = part.get_payload(decode=True) # return fallback . Output only the next line.
self.msg = DigestMessage([])
Given snippet: <|code_start|># This script creates a Distributor and updates regularly its status, # until a SIGTERM signal is received. The program is not interrupted # directly, to avoid inconsistent state. As a config file, it takes # the config.py file that is in the same directory. logger = logging.getLogger(__name__) distributor = None run = True def prepare(test_mode=False): ''' Creates a new instance of the distributor. Sets up the signal management. test_mode (optional) whether the test mode should be used or not. If so, the normal reader is replaced with a mock that always return zero messages ''' global distributor <|code_end|> , continue by predicting the next line. Consider current file imports: import time import signal import logging from config import py from deliver.distribute import OnlineDistributor from mock import Mock from deliver.read import Reader and context: # Path: deliver/distribute.py # class OnlineDistributor(Distributor): # ''' # Distributes mails in "real-time". # # There is one public method, update. When it is called, the server is polled. If new mails have # arrived, they are processed and resent to the members of the list. Afterward, the mails # are deleted, but only if the resend process finished successfully. # # If the subject is in a special format, instead of resending the # mail, a DownloadMessage is generated and sent back. # ''' # # def __init__(self, config): # super(OnlineDistributor,self).__init__(config) # self._reader = Reader(config) # # def update(self): # ''' # Update the distribution list. Every new message in the server is processed and resent to the # members of the list. If the resend is successful the new messages are deleted. # ''' # logger.debug('update is called') # # try: # self._reader.connect() # except Exception as e: # logger.info('connect failed with the exception: %s', e) # return False # # ids = self._reader.new_messages() # for id in ids: # msg = self._reader.get(id) # if self._isvalid(msg): # self._process(msg) # self._reader.delete(id) # self._reader.disconnect() # logger.debug('update is finished') # return len(ids) != 0 # # def _process(self, msg): # ''' # Redirects to the correct action based on the subject of the # message. # ''' # subject = msg['Subject'] # # if subject.lower().startswith('get'): # logger.debug('calling _download_and_send') # self._download_and_send(subject, msg) # else: # logger.debug('calling _resend') # self._resend(msg) # # def _download_and_send(self, subject, msg): # ''' # Creates a new DownloadMessage based on the subject and sends # it back to the sender. # # The format of the subject must be: GET 'url'. # ''' # id = self._store.archive(msg) # sender = self._find_sender_email(msg) # url = self._get_download_url(subject) # # if url is not None: # logger.info('Downloading message for %s with url %s', sender, url) # self._sender.send(DownloadMessage(url), sender) # self._store.mark_as_sent(id) # # def _get_download_url(self, subject): # ''' # Returns the url to download from the subject of the message, # or None if no url could be found. # ''' # subject = subject.lower().strip(' ') # parts = re.split(r'\s+', subject) # if len(parts) != 2: # logger.error('_get_download_url, %s has no valid url', subject) # return None # return parts[1] # # def _resend(self, msg): # ''' # Sends a message to the appropriate members of the list after processing it. # ''' # self._edit_msg(msg) # id = self._store.archive(msg) # sender = self._find_sender_email(msg) # self._sender.send(msg, *self._mgr.active_members(sender)) # self._store.digest(id, *self._mgr.digest_members(sender)) # self._store.mark_as_sent(id) # # def _edit_msg(self, msg): # ''' # Processes a message and returns it. The following steps are taken for each part of the # message that can be interpreted as text: # # - A header and a footer are added, both using the encoding of the payload. # - The payload has all the email hosts removed. # # The parts are separated with newlines, which depend on whether the message is plain text or # other (like HTML). # ''' # header = self._create_header(msg) # footer = self._create_footer(msg) # for editable in self._find_actual_text(msg): # nl = u'\n' if editable.get_content_subtype() == 'plain' else u'<br>' # editable.set_payload((nl * 2).join([ # nl.join(header), # EMAIL.sub(anonymize_email, editable.get_clean_payload(self._cfg['forbidden_words'])), # nl.join(footer)])) # # def _choose_intro(self): # '''Randomly chooses an introduction text from the configuration.''' # return random.choice(self._cfg['introductions']) # # def _create_footer(self, msg): # ''' # Creates a footer for the message, returned as a list of strings. The footer contains the # name of the list, a randomly chosen quote and the program id. # ''' # return [FOOTER_DIVIDER, # self._cfg['real_name'], # random.choice(self._cfg['quotes']), # self._powered_by()] # # def _powered_by(self): # ''' # Returns the program id, which consists of the name, version, and description of this sw. # ''' # name = self._manifest['name'] # version = self._manifest['version'] # description = self._manifest['description'] # return u'Powered by %s %s, %s' % (name, version, description) which might include code, classes, or functions. Output only the next line.
distributor = OnlineDistributor(py)
Using the snippet: <|code_start|> class ReadTest(BaseTest): def setUp(self): super(ReadTest,self).setUp() <|code_end|> , determine the next line of code. You have imports: from test_base import BaseTest from mock import patch from poplib import POP3 from deliver.read import Reader and context (class names, function names, or code) available: # Path: deliver/read.py # class Reader: # ''' # Class that is responsible for receiving/deleting mails from a specified POP3 account. # # To use the methods of this class, it is necessary to call the connect method beforehand. # After finishing with the processing, it is recommended to call the disconnect method. Otherwise, # updates to the underlying mail account, such as new messages, will be missed. Deleted messages # are not really deleted until the disconnection, either. # ''' # # def __init__(self, config): # self._cfg = config # # # def connect(self): # '''Connects to the server, which allows the other methods to be called.''' # self._s = poplib.POP3(self._cfg['pop_server']) # self._check(self._s.user(self._cfg['sender'])) # self._check(self._s.pass_(self._cfg['password'])) # # def disconnect(self): # '''Disconnects from the server, committing the changes.''' # self._check(self._s.quit()) # # def new_messages(self): # ''' # Gets a list of the ids (ints) of the new messages in the server, # sorted by ascending order. # ''' # st, msg_list, _ = self._s.list() # self._check(st) # logger.debug('new_messages: %s', msg_list) # return sorted(int(msg.split(' ')[0]) for msg in msg_list) # # def get(self, id): # '''Gets the message identified by the given id as a UnicodeMessage.''' # st, lines, _ = self._s.retr(id) # self._check(st) # return UnicodeMessage(email.message_from_string('\r\n'.join(lines))) # # def delete(self, id): # '''Marks the message identified by the given id for removal.''' # self._check(self._s.dele(id)) # # def _check(self, st): # ''' # Checks the given return code. If there is an error, it is logged. # ''' # if not st.startswith('+OK'): # logger.error('failed operation: %s', st) . Output only the next line.
self.reader = Reader(self.config)
Here is a snippet: <|code_start|> class ConverterDownloadTest(BaseTest): '''Tests for the DownloadMessage class''' def setUp(self): super(ConverterDownloadTest,self).setUp() def _msg(self, urlopen, url, content): if isinstance(content, file): content = content.read() f = Mock() urlopen.return_value = f f.read.return_value = content return DownloadMessage(url) @patch('urllib2.urlopen') def test_sanitize(self, urlopen): url = 'http://www.google.com' msg = self._msg(urlopen, url, '') self.assertEqual(msg._sanitize(url), url) @patch('urllib2.urlopen') def test_sanitize_add_protocol(self, urlopen): url = 'www.google.com' msg = self._msg(urlopen, url, '') self.assertEqual(msg._sanitize(url), 'http://' + url) @patch('urllib2.urlopen') def test_build_mail(self, urlopen): url = 'www.google.com' <|code_end|> . Write the next line using the current file imports: import urllib2 from deliver.tests.test_base import BaseTest, open_data from mock import patch, Mock from deliver.converter.download import DownloadMessage and context from other files: # Path: deliver/tests/test_base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # from test_data.test_config import py # self.config = py.copy() # # def tearDown(self): # super(BaseTest,self).tearDown() # if os.path.isfile(self.config['db_name']): # os.remove(self.config['db_name']) # # def open_data(fileName): # ''' # Opens the given file, which resides in the folder where all the # test data is. # ''' # return open(os.path.join('test_data', fileName)) # # Path: deliver/converter/download.py # class DownloadMessage(UnicodeMessage): # ''' # This class is used to build a mail that contains an attachment, # which is a website downloaded from the given url. # ''' # # def __init__(self, url): # ''' # Builds a mail, downloading the given url in the process and # saving it as an attachment. # ''' # self.url = self._sanitize(url) # super(DownloadMessage,self).__init__(self._build_mail()) # self._complete_headers() # pass # # def _sanitize(self, url): # ''' # Returns the given url as something that can be used by # urlopen. # ''' # if not url.startswith('http://'): # url = 'http://' + url # return url # # def _complete_headers(self): # '''Fill the headers of the mail''' # complete_headers(self, u'Download of %s' % self.url, 'download') # # def _build_mail(self): # ''' # Download the given url and build an attachment with the # contents. In case that the download fails, a text mail with # the error is built instead. # ''' # success, dl = self._download_url(self.url) # if not success: # return build_text_mail(dl) # # msg = MIMEMultipart() # msg.attach(build_text_mail(u'Downloaded website included as an attachment')) # part = MIMEBase('application', "octet-stream") # part.set_payload(dl) # email.Encoders.encode_base64(part) # part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'website.html') # msg.attach(part) # return msg # # def _download_url(self, url): # ''' # Return a tuple (status, content), with content being the # content of the url as a string, and status a boolean marking # whether the download was succesful or not.''' # try: # web = urllib2.urlopen(url) # except Exception as e: # result = (False, to_unicode(str(e))) # else: # result = (True, web.read()) # return result , which may include functions, classes, or code. Output only the next line.
msg = self._msg(urlopen, url, open_data('google.html'))
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class ConverterDownloadTest(BaseTest): '''Tests for the DownloadMessage class''' def setUp(self): super(ConverterDownloadTest,self).setUp() def _msg(self, urlopen, url, content): if isinstance(content, file): content = content.read() f = Mock() urlopen.return_value = f f.read.return_value = content <|code_end|> , predict the immediate next line with the help of imports: import urllib2 from deliver.tests.test_base import BaseTest, open_data from mock import patch, Mock from deliver.converter.download import DownloadMessage and context (classes, functions, sometimes code) from other files: # Path: deliver/tests/test_base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # from test_data.test_config import py # self.config = py.copy() # # def tearDown(self): # super(BaseTest,self).tearDown() # if os.path.isfile(self.config['db_name']): # os.remove(self.config['db_name']) # # def open_data(fileName): # ''' # Opens the given file, which resides in the folder where all the # test data is. # ''' # return open(os.path.join('test_data', fileName)) # # Path: deliver/converter/download.py # class DownloadMessage(UnicodeMessage): # ''' # This class is used to build a mail that contains an attachment, # which is a website downloaded from the given url. # ''' # # def __init__(self, url): # ''' # Builds a mail, downloading the given url in the process and # saving it as an attachment. # ''' # self.url = self._sanitize(url) # super(DownloadMessage,self).__init__(self._build_mail()) # self._complete_headers() # pass # # def _sanitize(self, url): # ''' # Returns the given url as something that can be used by # urlopen. # ''' # if not url.startswith('http://'): # url = 'http://' + url # return url # # def _complete_headers(self): # '''Fill the headers of the mail''' # complete_headers(self, u'Download of %s' % self.url, 'download') # # def _build_mail(self): # ''' # Download the given url and build an attachment with the # contents. In case that the download fails, a text mail with # the error is built instead. # ''' # success, dl = self._download_url(self.url) # if not success: # return build_text_mail(dl) # # msg = MIMEMultipart() # msg.attach(build_text_mail(u'Downloaded website included as an attachment')) # part = MIMEBase('application', "octet-stream") # part.set_payload(dl) # email.Encoders.encode_base64(part) # part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'website.html') # msg.attach(part) # return msg # # def _download_url(self, url): # ''' # Return a tuple (status, content), with content being the # content of the url as a string, and status a boolean marking # whether the download was succesful or not.''' # try: # web = urllib2.urlopen(url) # except Exception as e: # result = (False, to_unicode(str(e))) # else: # result = (True, web.read()) # return result . Output only the next line.
return DownloadMessage(url)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class OfflineDistributeTest(BaseTest): def setUp(self): super(OfflineDistributeTest,self).setUp() <|code_end|> , determine the next line of code. You have imports: from test_base import BaseTest, load_msg, get_msg, archive_msg, get_digests from mock import Mock from datetime import datetime, timedelta from deliver.distribute import OfflineDistributor from deliver.send import Sender and context (class names, function names, or code) available: # Path: deliver/distribute.py # class OfflineDistributor(Distributor): # ''' # Distributes deferred mails (digests) # # There is one public method, update. When it is called, the list of # users with pending emails is retrieved from the Store. For each of # these users, the pending mails are retrieved. A digest mail is # built from them and sent to the user. # ''' # # def __init__(self, config): # super(OfflineDistributor,self).__init__(config) # # def update(self): # ''' # Update the pending digests. For each user with pending # digests, a mail is built and sent to them. # ''' # logger.debug('update is called') # self._store.discard_old_digests(self._cfg['digest_age_limit']) # users = self._store.users_with_pending_digests() # for user in users: # messages = self._store.messages_for_user(user) # msg = DigestMessage(messages) # self._sender.send(msg, user) # self._store.mark_digest_as_sent(user) # logger.debug('update is finished') # return len(users) != 0 # # Path: deliver/send.py # class Sender: # ''' # Class that is responsible of sending emails. It uses a specified SMTP server. # ''' # # def __init__(self, config): # self._cfg = config # # def send(self, msg, *recipients): # ''' # Sends the given UnicodeMessage to each of the specified recipients. # ''' # assert isinstance(msg, UnicodeMessage) # for recipient in recipients: # assert isinstance(recipient, unicode) # self._send(msg, *recipients) # # def _send(self, msg, *recipients): # ''' # Sends the given UnicodeMessage to each of # the specified recipients. # # The emails are sent from the specified server, using the specified address. The subject # is modified to include a subject prefix if it is not already there. # ''' # msg.replace_header('Subject', self._prepare_subject(msg['Subject'])) # msg.replace_header('From', self.get_address()) # msg.replace_header('Reply-To', self.get_address()) # logging.debug('email ready to be sent: %s', msg['Message-Id']) # for recipient in recipients: # logger.debug('Sending message to %s', recipient) # s = smtplib.SMTP(self._cfg['smtp_server']) # msg.replace_header('To', recipient) # s.sendmail(self.get_address(), recipient, msg.as_string()) # s.quit() # # def get_address(self): # '''Gets the address used by this sender''' # return self._cfg['sender'] # # def _prepare_subject(self, subject): # '''Modifies the given subject to include a prefix if it is not already there''' # if self._cfg['subject_prefix'] in subject: # return subject # return self._cfg['subject_prefix'] + ' ' + subject . Output only the next line.
self.distributor = OfflineDistributor(self.config)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class OfflineDistributeTest(BaseTest): def setUp(self): super(OfflineDistributeTest,self).setUp() self.distributor = OfflineDistributor(self.config) <|code_end|> . Use current file imports: from test_base import BaseTest, load_msg, get_msg, archive_msg, get_digests from mock import Mock from datetime import datetime, timedelta from deliver.distribute import OfflineDistributor from deliver.send import Sender and context (classes, functions, or code) from other files: # Path: deliver/distribute.py # class OfflineDistributor(Distributor): # ''' # Distributes deferred mails (digests) # # There is one public method, update. When it is called, the list of # users with pending emails is retrieved from the Store. For each of # these users, the pending mails are retrieved. A digest mail is # built from them and sent to the user. # ''' # # def __init__(self, config): # super(OfflineDistributor,self).__init__(config) # # def update(self): # ''' # Update the pending digests. For each user with pending # digests, a mail is built and sent to them. # ''' # logger.debug('update is called') # self._store.discard_old_digests(self._cfg['digest_age_limit']) # users = self._store.users_with_pending_digests() # for user in users: # messages = self._store.messages_for_user(user) # msg = DigestMessage(messages) # self._sender.send(msg, user) # self._store.mark_digest_as_sent(user) # logger.debug('update is finished') # return len(users) != 0 # # Path: deliver/send.py # class Sender: # ''' # Class that is responsible of sending emails. It uses a specified SMTP server. # ''' # # def __init__(self, config): # self._cfg = config # # def send(self, msg, *recipients): # ''' # Sends the given UnicodeMessage to each of the specified recipients. # ''' # assert isinstance(msg, UnicodeMessage) # for recipient in recipients: # assert isinstance(recipient, unicode) # self._send(msg, *recipients) # # def _send(self, msg, *recipients): # ''' # Sends the given UnicodeMessage to each of # the specified recipients. # # The emails are sent from the specified server, using the specified address. The subject # is modified to include a subject prefix if it is not already there. # ''' # msg.replace_header('Subject', self._prepare_subject(msg['Subject'])) # msg.replace_header('From', self.get_address()) # msg.replace_header('Reply-To', self.get_address()) # logging.debug('email ready to be sent: %s', msg['Message-Id']) # for recipient in recipients: # logger.debug('Sending message to %s', recipient) # s = smtplib.SMTP(self._cfg['smtp_server']) # msg.replace_header('To', recipient) # s.sendmail(self.get_address(), recipient, msg.as_string()) # s.quit() # # def get_address(self): # '''Gets the address used by this sender''' # return self._cfg['sender'] # # def _prepare_subject(self, subject): # '''Modifies the given subject to include a prefix if it is not already there''' # if self._cfg['subject_prefix'] in subject: # return subject # return self._cfg['subject_prefix'] + ' ' + subject . Output only the next line.
self.sender = Mock(spec=Sender)
Using the snippet: <|code_start|> curdir = None def init_d(): global curdir curdir = os.path.abspath(os.path.curdir) return Daemon(name='deliver', catch_all_log=curdir, pid_dir=curdir) def run(): daemon = init_d() daemon.start() # Undo some of the changes done by start, otherwise it won't work os.chdir(curdir) <|code_end|> , determine the next line of code. You have imports: import argparse import os from supay import Daemon from updater import prepare, loop and context (class names, function names, or code) available: # Path: updater.py # def prepare(test_mode=False): # ''' # Creates a new instance of the distributor. Sets up the signal # management. # # test_mode (optional) whether the test mode should be used or # not. If so, the normal reader is replaced with a mock that always # return zero messages # ''' # global distributor # distributor = OnlineDistributor(py) # # if test_mode: # from mock import Mock # from deliver.read import Reader # reader = Mock(spec=Reader) # reader.new_messages.return_value = [] # distributor._reader = reader # # signal.signal(signal.SIGTERM, terminate) # # def loop(): # ''' # Loops indefinitely, updating the distributor and then sleeping for # a defined time. # ''' # print 'Starting...' # sleep = py['sleep_interval'] # # try: # while run: # success = update() # sleep = sleeping_time(sleep, success) # time.sleep(sleep) # except Exception: # logging.exception('Oh noes! Exception') . Output only the next line.
prepare()
Predict the next line after this snippet: <|code_start|> curdir = None def init_d(): global curdir curdir = os.path.abspath(os.path.curdir) return Daemon(name='deliver', catch_all_log=curdir, pid_dir=curdir) def run(): daemon = init_d() daemon.start() # Undo some of the changes done by start, otherwise it won't work os.chdir(curdir) prepare() <|code_end|> using the current file's imports: import argparse import os from supay import Daemon from updater import prepare, loop and any relevant context from other files: # Path: updater.py # def prepare(test_mode=False): # ''' # Creates a new instance of the distributor. Sets up the signal # management. # # test_mode (optional) whether the test mode should be used or # not. If so, the normal reader is replaced with a mock that always # return zero messages # ''' # global distributor # distributor = OnlineDistributor(py) # # if test_mode: # from mock import Mock # from deliver.read import Reader # reader = Mock(spec=Reader) # reader.new_messages.return_value = [] # distributor._reader = reader # # signal.signal(signal.SIGTERM, terminate) # # def loop(): # ''' # Loops indefinitely, updating the distributor and then sleeping for # a defined time. # ''' # print 'Starting...' # sleep = py['sleep_interval'] # # try: # while run: # success = update() # sleep = sleeping_time(sleep, success) # time.sleep(sleep) # except Exception: # logging.exception('Oh noes! Exception') . Output only the next line.
loop()
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class MemberMgrTest(BaseTest): def setUp(self): super(MemberMgrTest,self).setUp() <|code_end|> . Use current file imports: (from test_base import BaseTest from deliver.members import MemberMgr) and context including class names, function names, or small code snippets from other files: # Path: deliver/members.py # class MemberMgr: # ''' # Class that is responsible of dealing with the members of the list. # # The members are stored as a json file. An example is found in the # members.json.example file. # ''' # # def __init__(self, config): # self._members = json.load(codecs.open(config['members'], 'r', 'utf-8')) # # def _choose_email_address(self, member) : # ''' # Chooses an email address from the mail hash for the given # member, by using the send_to key. If the key is not defined # for the member, default is used as the key.''' # send_to = member['send_to'] if member.has_key('send_to') else 'default' # email = member['email'][send_to] # logger.debug('_choose_email_address for %s took %s', member['name'], email) # return email # # def _member_query(self, exclude = u'', active=True, digest=False): # ''' # Returns a generator will all the members that fulfill the given conditions. # # optional exclude the address that should not appear in the results # # optional active whether the user should be active or not # # optional digest whether the user should receive messages as a digest or not # # If a member does not contain one of the attributes used for # the query (active, digest), it is considered to have a False # value. # ''' # # Normalize # exclude = exclude.lower() # return (self._choose_email_address(member) for member in self._members['members'] # if member.get('active', False) is active and member.get('digest', False) is digest # and not self._is_email_for_member(member, exclude)) # # def active_members(self, sender = u''): # ''' # Returns a list with the email addresses of all the active # members of the list, as unicode strings. Users in digest mode # are excluded. # # Optional sender the sender, who should be excluded from the # results. # ''' # return list(self._member_query(exclude=sender)) # # def digest_members(self, sender = u''): # ''' # Returns a list with the email addresses of all the active # members of the list that are also digest users, as unicode # strings. # # Optional sender the sender, who should be excluded from the # results. # ''' # return list(self._member_query(exclude=sender, digest=True)) # # def _is_email_for_member(self, member, email): # ''' # Returns true if the given email is one of the defined mails # for the given member, and false otherwise. # ''' # for m in member['email'].values(): # if m.lower() in email: # return True # return False # # def find_member(self, email): # ''' # Returns the member with the given email address, or None if # there is not one. # ''' # # Normalize # email = email.lower() # try: # member = (m for m in self._members['members'] # if self._is_email_for_member(m,email)).next() # except StopIteration: # logger.error('find_member for %s had no results', email) # return None # logger.debug('find_member found %s', member) # return member # # def iswhitelisted(self, addr): # '''Checks if the given email address appears in the # whitelist.''' # return addr.lower() in self._members['whitelist'] # # def isblacklisted(self, addr): # '''Checks if the given email address appears in the # blacklist.''' # return addr.lower() in self._members['blacklist'] # # def choose_name(self, member): # '''Randomly chooses a name for the given member, between her # name and aliases.''' # if member.has_key('aliases'): # return random.choice([member['name']] + member['aliases']) # return member['name'] . Output only the next line.
self.memberMgr = MemberMgr(self.config)
Predict the next line after this snippet: <|code_start|> class BaseDBWrapper(object): def _create_tables(self): metadata = MetaData() metadata.bind = self.engine self.messages = self._create_table('messages', metadata, Column('id', String(192), index=True, primary_key=True), Column('content', Text, nullable=False), Column('received_at', DateTime, nullable=False), Column('sent_at', DateTime)) self.digests = self._create_table('digests', metadata, Column('msg_id', String(192), ForeignKey('messages.id', ondelete='cascade'), primary_key=True), Column('send_to', String(192), index=True, primary_key=True), Column('scheduled_at', DateTime, nullable=False), Column('sent_at', DateTime)) metadata.bind = self.engine metadata.create_all(self.engine) clear_mappers() <|code_end|> using the current file's imports: from sqlalchemy import * from sqlalchemy.orm import mapper, clear_mappers, create_session, relationship, backref from deliver.db.models.message import Message from deliver.db.models.digest import Digest and any relevant context from other files: # Path: deliver/db/models/message.py # class Message(object): # # def __init__(self, id, content, received_at, sent_at=None): # self.id = id # self.content = content.as_string() # self.received_at = received_at # self.sent_at = sent_at # # @property # def parsed_content(self): # ''' # Returns the email content as a UnicodeMessage object # ''' # return UnicodeMessage( # email.message_from_string(self.content.encode('utf-8'))) # # def __repr__(self): # return '<Message(id=%s, received_at=%s, sent_at=%s)>' \ # % (self.id, self.received_at, self.sent_at) # # Path: deliver/db/models/digest.py # class Digest(object): # # def __init__(self, msg_id, send_to, scheduled_at, sent_at=None): # self.msg_id = msg_id # self.send_to = send_to # self.scheduled_at = scheduled_at # self.sent_at = sent_at # # def __repr__(self): # return '<Digest(msg_id=%s, send_to=%s, scheduled_at=%s, sent_at=%s)>' \ # % (self.msg_id, self.send_to, self.scheduled_at, self.sent_at) . Output only the next line.
mapper(Message, self.messages, properties={
Based on the snippet: <|code_start|> class BaseDBWrapper(object): def _create_tables(self): metadata = MetaData() metadata.bind = self.engine self.messages = self._create_table('messages', metadata, Column('id', String(192), index=True, primary_key=True), Column('content', Text, nullable=False), Column('received_at', DateTime, nullable=False), Column('sent_at', DateTime)) self.digests = self._create_table('digests', metadata, Column('msg_id', String(192), ForeignKey('messages.id', ondelete='cascade'), primary_key=True), Column('send_to', String(192), index=True, primary_key=True), Column('scheduled_at', DateTime, nullable=False), Column('sent_at', DateTime)) metadata.bind = self.engine metadata.create_all(self.engine) clear_mappers() mapper(Message, self.messages, properties={ <|code_end|> , predict the immediate next line with the help of imports: from sqlalchemy import * from sqlalchemy.orm import mapper, clear_mappers, create_session, relationship, backref from deliver.db.models.message import Message from deliver.db.models.digest import Digest and context (classes, functions, sometimes code) from other files: # Path: deliver/db/models/message.py # class Message(object): # # def __init__(self, id, content, received_at, sent_at=None): # self.id = id # self.content = content.as_string() # self.received_at = received_at # self.sent_at = sent_at # # @property # def parsed_content(self): # ''' # Returns the email content as a UnicodeMessage object # ''' # return UnicodeMessage( # email.message_from_string(self.content.encode('utf-8'))) # # def __repr__(self): # return '<Message(id=%s, received_at=%s, sent_at=%s)>' \ # % (self.id, self.received_at, self.sent_at) # # Path: deliver/db/models/digest.py # class Digest(object): # # def __init__(self, msg_id, send_to, scheduled_at, sent_at=None): # self.msg_id = msg_id # self.send_to = send_to # self.scheduled_at = scheduled_at # self.sent_at = sent_at # # def __repr__(self): # return '<Digest(msg_id=%s, send_to=%s, scheduled_at=%s, sent_at=%s)>' \ # % (self.msg_id, self.send_to, self.scheduled_at, self.sent_at) . Output only the next line.
'digests': relationship(Digest, backref='msg')
Next line prediction: <|code_start|># -*- coding: utf-8 -*- class ConverterTest(BaseTest): '''Tests for the UnicodeMessage class''' def setUp(self): super(ConverterTest,self).setUp() <|code_end|> . Use current file imports: (from deliver.tests.test_base import BaseTest, load_msg, load_all_msg) and context including class names, function names, or small code snippets from other files: # Path: deliver/tests/test_base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # from test_data.test_config import py # self.config = py.copy() # # def tearDown(self): # super(BaseTest,self).tearDown() # if os.path.isfile(self.config['db_name']): # os.remove(self.config['db_name']) # # def load_msg(fileName): # '''Loads the message contained in the given file and returns it as # an UnicodeMessage.''' # return UnicodeMessage(email.message_from_file(open_data(fileName))) # # def load_all_msg(): # '''Loads all the available sample messages and returns them as a list.''' # return [load_msg(fileName) for fileName in ['sample', 'sample2', # 'sample3', # 'sample4', # content base64 # 'sample5', # content base64 utf-8 # 'sample6', # empty content # 'sample7', # invalid sender # 'sample8', # whitelisted sender # 'sample9', # blacklisted sender # 'sample10', # get www.google.com # 'sample11', # no header/body encoding # 'sample13' # msg without subject # ]] . Output only the next line.
self.msg = load_msg('sample3')
Using the snippet: <|code_start|> def test_get_payload_empty(self): self.msg = load_msg('sample6') self._test_get(u'\n', u'\n') def test_clean_word_no_replace(self): self.assertEqual(self.msg._clean_word(u'panic', {}), u'panic') def test_clean_word_replace(self): self.assertEqual(self.msg._clean_word(u'panic', {u'panic' : u'don\'t'}), u'don\'t') def test_clean_word_replace_case(self): self.assertEqual(self.msg._clean_word(u'Panic', {u'panic' : u'don\'t'}), u'don\'t') def test_clean_word_replace_special_chars(self): self.assertEqual(self.msg._clean_word(u'Pánico', {u'pánico' : u'don\'t'}), u'don\'t') def test_clean_word_surrounded(self): self.assertEqual(self.msg._clean_word(u'*Pánico*?', {u'pánico' : u'don\'t'}), u'*don\'t*?') def test_get_clean_payload(self): words = self.config['forbidden_words'] payload = self.get_clean_text(words) for word in words.keys(): self.assertFalse(word in payload, 'word %s was not removed' % word) for replacement in words.values(): self.assertTrue(replacement in payload, 'word %s was not inserted' % word) def test_walk(self): <|code_end|> , determine the next line of code. You have imports: from deliver.tests.test_base import BaseTest, load_msg, load_all_msg and context (class names, function names, or code) available: # Path: deliver/tests/test_base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # from test_data.test_config import py # self.config = py.copy() # # def tearDown(self): # super(BaseTest,self).tearDown() # if os.path.isfile(self.config['db_name']): # os.remove(self.config['db_name']) # # def load_msg(fileName): # '''Loads the message contained in the given file and returns it as # an UnicodeMessage.''' # return UnicodeMessage(email.message_from_file(open_data(fileName))) # # def load_all_msg(): # '''Loads all the available sample messages and returns them as a list.''' # return [load_msg(fileName) for fileName in ['sample', 'sample2', # 'sample3', # 'sample4', # content base64 # 'sample5', # content base64 utf-8 # 'sample6', # empty content # 'sample7', # invalid sender # 'sample8', # whitelisted sender # 'sample9', # blacklisted sender # 'sample10', # get www.google.com # 'sample11', # no header/body encoding # 'sample13' # msg without subject # ]] . Output only the next line.
for mail in load_all_msg():
Predict the next line after this snippet: <|code_start|> @register.filter(name="format_links") @safe def format_links(value, arg=None): value = link_regex.sub(r'<a href="\2" target=_new>\1</a>', value) return value @register.filter(name="format_autolinks") @safe def format_autolinks(value, arg=None): value = autolink_regex.sub(r'\1<a href="\2" target="_new">\2</a>', value) return value # TODO(tyler): Combine these with validate user_regex = re.compile( r'@([a-zA-Z][a-zA-Z0-9]{%d,%d})' % (clean.NICK_MIN_LENGTH - 1, clean.NICK_MAX_LENGTH - 1) ) channel_regex = re.compile( r'#([a-zA-Z][a-zA-Z0-9]{%d,%d})' % (clean.NICK_MIN_LENGTH - 1, clean.NICK_MAX_LENGTH - 1) ) @register.filter(name="format_actor_links") @safe def format_actor_links(value, request=None): """Formats usernames / channels """ value = re.sub(user_regex, lambda match: '<a href="%s">@%s</a>' % ( <|code_end|> using the current file's imports: import datetime import re from markdown import markdown2 from django import template from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe from django.utils.html import escape from django.utils.timesince import timesince from common.util import create_nonce, safe, display_nick, url_nick from common import clean from common import models and any relevant context from other files: # Path: common/models.py # PRIVACY_PRIVATE = 1 # PRIVACY_CONTACTS = 2 # PRIVACY_PUBLIC = 3 # ACTOR_ALLOWED_EXTRA = ('contact_count', # 'follower_count', # 'icon', # 'description', # 'member_count', # 'admin_count', # 'given_name', # 'family_name' # ) # ACTOR_LIMITED_EXTRA = ('icon', # 'description', # 'given_name', # 'family_name' # ) # def _get_actor_type_from_nick(nick): # def _get_actor_urlnick_from_nick(nick): # def _to_api(v): # def to_api(self): # def __init__(self, parent=None, key_name=None, _app=None, **kw): # def key_from(cls, **kw): # def _remove_from_cache(self): # def put(self): # def save(self): # def delete(self): # def get_by_key_name(cls, key_names, parent=None): # def db_get_count(cls): # def reset_cache(cls): # def enable_cache(cls, enabled = True): # def reset_get_count(cls): # def gql(cls, *args, **kw): # def Query(cls): # def mark_as_deleted(self): # def is_deleted(self): # def actor_url(nick, actor_type, path='', request=None, mobile=False): # def url(self, path="", request=None, mobile=False): # def shortnick(self): # def display_nick(self): # def to_api(self): # def to_api_limited(self): # def is_channel(self): # def is_public(self): # def is_restricted(self): # def __repr__(self): # def stream_entry_keyname(self): # def to_string(self): # def url(self): # def to_string(self): # def is_public(self): # def is_restricted(self): # def keyname(self): # def url(self, with_anchor=True, request=None, mobile=False): # def keyname(self): # def title(self): # def is_comment(self): # def is_channel(self): # def entry_actor(self): # def is_subscribed(self): # class ApiMixinModel(aed_models.BaseModel): # class CachingModel(ApiMixinModel): # class DeletedMarkerModel(CachingModel): # class AbuseReport(CachingModel): # class Activation(CachingModel): # class Actor(DeletedMarkerModel): # class Image(CachingModel): # class InboxEntry(CachingModel): # class Invite(CachingModel): # class KeyValue(CachingModel): # class OAuthAccessToken(CachingModel): # class OAuthConsumer(CachingModel): # class OAuthNonce(CachingModel): # class OAuthRequestToken(CachingModel): # class Presence(CachingModel): # class Task(CachingModel): # class Relation(CachingModel): # class Stream(DeletedMarkerModel): # class StreamEntry(DeletedMarkerModel): # class Subscription(CachingModel): . Output only the next line.
models.actor_url(match.group(1), 'user', request=request),
Next line prediction: <|code_start|> try: except ImportError: etree = None class FixturesTestCase(test.TestCase): fixtures = ['actors', 'streams', 'contacts', 'streamentries', 'inboxentries', 'subscriptions', 'oauthconsumers', 'invites', 'emails', 'ims', 'activations', 'oauthaccesstokens'] passwords = {'obligated@example.com': 'bar', 'popular@example.com': 'baz', 'celebrity@example.com': 'baz', 'boyfriend@example.com': 'baz', 'girlfriend@example.com': 'baz', 'annoying@example.com': 'foo', 'unpopular@example.com': 'foo', 'hermit@example.com': 'baz', 'broken@example.com': 'baz', 'CapitalPunishment@example.com': 'baz', 'root@example.com': 'fakepassword', 'hotness@example.com': 'fakepassword'}; def setUp(self): settings.DEBUG = False <|code_end|> . Use current file imports: (import urlparse import sys import xml.etree.ElementTree as etree import xml.parsers.expat from beautifulsoup import BeautifulSoup from django import http from django import test from django.conf import settings from django.test import client from common import clean from common import memcache from common import profile from common import util from common.protocol import sms from common.protocol import xmpp from common.test import util as test_util) and context including class names, function names, or small code snippets from other files: # Path: common/protocol/xmpp.py # class JID(object): # class XmppMessage(object): # class XmppConnection(base.Connection): # def __init__(self, node, host, resource=None): # def from_uri(cls, uri): # def base(self): # def full(self): # def __init__(self, sender, target, message): # def from_request(cls, request): # def send_message(self, to_jid_list, message, html_message=None, # atom_message=None): # # Path: common/test/util.py # def get_url(s): # def get_relative_url(s): # def exhaust_queue(nick): # def exhaust_queue_any(): # def send_message(self, to_jid_list, message, html_message=None, # atom_message=None): # def send_message(self, to_list, message): # def __init__(self, **kw): # def REQUEST(self): # def __init__(self, *args, **kw): # def _get_valid(self, key): # def set(self, key, value, time=0): # def set_multi(self, mapping, time=0, key_prefix=''): # def add(self, key, value, time=0): # def add_multi(self, mapping, time=0, key_prefix=''): # def incr(self, key, delta=1): # def decr(self, key, delta=1): # def delete(self, key, seconds=0): # def delete_multi(self, keys, key_prefix=''): # def get(self, key): # def get_multi(self, keys, key_prefix=''): # def __init__(self, module, **kw): # def override(self): # def reset(self): # def override_clock(module, **kw): # def __init__(self, **kw): # def override(self): # def reset(self): # def override(**kw): # class TestXmppConnection(xmpp.XmppConnection): # class TestSmsConnection(sms.SmsConnection): # class FakeRequest(object): # class FakeMemcache(object): # class ClockOverride(object): # class SettingsOverride(object): . Output only the next line.
xmpp.XmppConnection = test_util.TestXmppConnection