Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|>""" Multi-backend ContentsManager. """ from __future__ import unicode_literals @outside_root_to_404 def _resolve_path(path, manager_dict): """ Resolve a path based on a dictionary of manager prefixes. Returns a triple of (prefix, manager, manager_relative_path). """ <|c...
path = normalize_api_path(path)
Continue the code snippet: <|code_start|> def _wrapper(self, old_path, new_path, *args, **kwargs): old_prefix, old_mgr, old_mgr_path = _resolve_path( old_path, self.managers ) new_prefix, new_mgr, new_mgr_path = _resolve_path( new_path, self.managers, ) ...
class HybridContentsManager(ContentsManager):
Given snippet: <|code_start|> ) if old_mgr is not new_mgr: # TODO: Consider supporting this via get+delete+save. raise HTTPError( 400, "Can't move files between backends ({old} -> {new})".format( old=old_path, ...
manager_classes = Dict(
Predict the next line for this snippet: <|code_start|>from __future__ import with_statement # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfi...
target_metadata = metadata
Given the code snippet: <|code_start|>def test_notebook(name): """ Make a test notebook for the given name. """ nb = new_notebook() nb.cells.append(new_code_cell("'code_' + '{}'".format(name))) nb.cells.append(new_raw_cell("raw_{}".format(name))) nb.cells.append(new_markdown_cell('markdown_{...
path=api_path_join(dirname, nbname),
Predict the next line after this snippet: <|code_start|># encoding: utf-8 """ Utilities for testing. """ from __future__ import unicode_literals TEST_DB_URL = os.environ.get('PGCONTENTS_TEST_DB_URL') if TEST_DB_URL is None: TEST_DB_URL = "postgresql://{user}@/pgcontents_testing".format( user=getuser(), ...
return FernetEncryption(Fernet(Fernet.generate_key()))
Given the code snippet: <|code_start|> user=getuser(), ) def make_fernet(): return FernetEncryption(Fernet(Fernet.generate_key())) def _norm_unicode(s): """Normalize unicode strings""" return normalize('NFC', py3compat.cast_unicode(s)) @contextmanager def assertRaisesHTTPError(testcase, sta...
unexpected_tables = set(metadata.tables) - set(_tables)
Here is a snippet: <|code_start|> @nottest def drop_testing_db_tables(): """ Drop all tables from the testing db. """ engine = create_engine(TEST_DB_URL) conn = engine.connect() trans = conn.begin() conn.execute('DROP SCHEMA IF EXISTS pgcontents CASCADE') conn.execute('DROP TABLE IF EXI...
nb.cells.append(new_code_cell("'code_' + '{}'".format(name)))
Next line prediction: <|code_start|>@nottest def drop_testing_db_tables(): """ Drop all tables from the testing db. """ engine = create_engine(TEST_DB_URL) conn = engine.connect() trans = conn.begin() conn.execute('DROP SCHEMA IF EXISTS pgcontents CASCADE') conn.execute('DROP TABLE IF EX...
nb.cells.append(new_markdown_cell('markdown_{}'.format(name)))
Given the following code snippet before the placeholder: <|code_start|> migrate_testing_db() @nottest def drop_testing_db_tables(): """ Drop all tables from the testing db. """ engine = create_engine(TEST_DB_URL) conn = engine.connect() trans = conn.begin() conn.execute('DROP SCHEMA IF ...
nb = new_notebook()
Given the code snippet: <|code_start|> @nottest def drop_testing_db_tables(): """ Drop all tables from the testing db. """ engine = create_engine(TEST_DB_URL) conn = engine.connect() trans = conn.begin() conn.execute('DROP SCHEMA IF EXISTS pgcontents CASCADE') conn.execute('DROP TABLE IF...
nb.cells.append(new_raw_cell("raw_{}".format(name)))
Given the code snippet: <|code_start|> @nottest def remigrate_test_schema(): """ Drop recreate the test db schema. """ drop_testing_db_tables() migrate_testing_db() @nottest def drop_testing_db_tables(): """ Drop all tables from the testing db. """ engine = create_engine(TEST_DB_U...
upgrade(TEST_DB_URL, revision)
Next line prediction: <|code_start|> ---------- fernet : cryptography.fernet.Fernet The Fernet object to use for encryption. Methods ------- encrypt : callable[bytes -> bytes] decrypt : callable[bytes -> bytes] Notes ----- ``cryptography.fernet.MultiFernet`` can be used inste...
raise CorruptedFile(e)
Predict the next line for this snippet: <|code_start|>""" Utilities for running migrations. """ @contextmanager def temp_alembic_ini(alembic_dir_location, sqlalchemy_url): """ Temporarily write an alembic.ini file for use with alembic migration scripts. """ with TemporaryDirectory() as tempdir: ...
ALEMBIC_INI_TEMPLATE.format(
Based on the snippet: <|code_start|>""" Utilities for running migrations. """ @contextmanager def temp_alembic_ini(alembic_dir_location, sqlalchemy_url): """ Temporarily write an alembic.ini file for use with alembic migration scripts. """ with TemporaryDirectory() as tempdir: alembic_in...
with temp_alembic_ini(ALEMBIC_DIR_LOCATION, db_url) as alembic_ini:
Based on the snippet: <|code_start|>""" Tests for notebook encryption utilities. """ class TestEncryption(TestCase): def test_fernet_derivation(self): pws = [u'currentpassword', u'oldpassword', None] # This must be Unicode, so we use the `u` prefix to support py2. user_id = u'4e322fa20...
current_crypto = single_password_crypto_factory(pws[0])(user_id)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.small.routes =============================== A small ``Flask-Via`` example Flask application. """ routes = [ <|code_end|> , determine the next line of code. You have imports: from flask_via.examples.small import views from flask.ext.vi...
default.Functional('/', views.home),
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ tests.test_routers.test_restful ================================ Unit tests for the Flask-Restful resource router. """ class TestRestfulRouter(unittest.TestCase): def setUp(self): self.app = mock.MagicMock() def test_add_to_app_ra...
resource = restful.Resource('/', mock.MagicMock())
Given snippet: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.blueprints.baz.routes ======================================== A blueprint ``Flask-Via`` example Flask application. """ routes = [ <|code_end|> , continue by predicting the next line. Consider current file imports: from flask_via.examples...
default.Functional('/', views.baz),
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.small.foo.routes =================================== A small ``Flask-Via`` example Flask application. """ routes = [ <|code_end|> , generate the next line using the imports in this file: from flask_via.examples.small.foo import vi...
default.Functional('/foo', views.foo),
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.include.foo.routes ===================================== A include ``Flask-Via`` example Flask application. """ routes = [ <|code_end|> using the current file's imports: from flask_via.examples.include.foo.views...
Pluggable('/bar', BarView, 'bar'),
Given snippet: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.include.foo.routes ===================================== A include ``Flask-Via`` example Flask application. """ routes = [ Pluggable('/bar', BarView, 'bar'), <|code_end|> , continue by predicting the next line. Consider current file imp...
Pluggable('/baz', BazView, 'baz'),
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.include.foo.routes ===================================== A include ``Flask-Via`` example Flask application. """ routes = [ <|code_end|> , predict the next line using imports from the current file: ...
Pluggable('/foo', FooView, 'foo'),
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.include.foo.routes ===================================== A include ``Flask-Via`` example Flask application. """ routes = [ Pluggable('/foo', FooView, 'foo'), <|code_end|> , predict the next line...
Pluggable('/faz', FazView, 'faz'),
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.include.foo.routes ===================================== A include ``Flask-Via`` example Flask application. """ routes = [ Pluggable('/foo', FooView, 'foo'), Pluggable('/faz', FazView, 'faz'), <|code_end|> , predict the immed...
Functional('/flop', flop),
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ tests.test_routers.test_admin ============================= Unit tests for the Flask-Admin admin router. """ class TestRestfulRouter(unittest.TestCase): def setUp(self): self.app = mock.MagicMock() def test_add_to_app_raises_not_implem...
resource = admin.AdminRoute(mock.MagicMock())
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ flask_via.examples.blueprints.foo.routes ======================================== A blueprint ``Flask-Via`` example Flask application. """ routes = [ <|code_end|> using the current file's imports: from flask_via.examples.blueprint...
default.Functional('/baz', views.baz),
Next line prediction: <|code_start|> service_api = Blueprint('service_api', __name__) @service_api.route('', methods=['GET']) @login_required def get_services(): """ Gets the list of services. """ # TODO: pagination return jsonify(Service.all()) @service_api.route('/<int:service_id>', methods=[...
form = ServiceForm()
Predict the next line for this snippet: <|code_start|> service_api = Blueprint('service_api', __name__) @service_api.route('', methods=['GET']) @login_required def get_services(): """ Gets the list of services. """ # TODO: pagination <|code_end|> with the help of current file imports: from flask im...
return jsonify(Service.all())
Continue the code snippet: <|code_start|>def get_services(): """ Gets the list of services. """ # TODO: pagination return jsonify(Service.all()) @service_api.route('/<int:service_id>', methods=['GET']) @required_access('admin') def get_service(service_id): """ Gets a service. """ r...
category=Category.get(form.category.data)
Using the snippet: <|code_start|> service_api = Blueprint('service_api', __name__) @service_api.route('', methods=['GET']) @login_required def get_services(): """ Gets the list of services. """ # TODO: pagination return jsonify(Service.all()) @service_api.route('/<int:service_id>', methods=['GE...
@required_access('admin')
Predict the next line after this snippet: <|code_start|> service_api = Blueprint('service_api', __name__) @service_api.route('', methods=['GET']) @login_required def get_services(): """ Gets the list of services. """ # TODO: pagination <|code_end|> using the current file's imports: from flask impor...
return jsonify(Service.all())
Given snippet: <|code_start|>service_api = Blueprint('service_api', __name__) @service_api.route('', methods=['GET']) @login_required def get_services(): """ Gets the list of services. """ # TODO: pagination return jsonify(Service.all()) @service_api.route('/<int:service_id>', methods=['GET']) @...
return api_error(form.errors)
Predict the next line for this snippet: <|code_start|>"""user name organization Revision ID: 7ee0d022e8d6 Revises: 3e7e65c44fc2 Create Date: 2016-08-22 22:27:02.630331 """ # revision identifiers, used by Alembic. revision = '7ee0d022e8d6' down_revision = '3e7e65c44fc2' branch_labels = None depends_on = None def u...
User.__table__.update()
Predict the next line for this snippet: <|code_start|> .join(cls.responses) \ .filter(Response.user_id == provider.id) \ .order_by(desc(cls.created_at)) \ .distinct().all() return [alert.to_provider_json(provider) for alert in alerts] def provider_has_permissi...
return extend(self.to_json(), dict(
Predict the next line for this snippet: <|code_start|> .filter(ProviderNotified.provider_id == provider.id) \ .order_by(desc(cls.created_at)) \ .distinct().all() return [alert.to_provider_json(provider) for alert in alerts] @classmethod def get_responded_alerts_for_pr...
created_at=to_local_datetime(self.created_at),
Using the snippet: <|code_start|> category_api = Blueprint('category_api', __name__) @category_api.route('', methods=['GET']) @login_required def get_categories(): """ Gets the list of categories. """ # TODO: pagination return jsonify(Category.all()) @category_api.route('/<int:category_id>', me...
form = CategoryForm()
Continue the code snippet: <|code_start|> category_api = Blueprint('category_api', __name__) @category_api.route('', methods=['GET']) @login_required def get_categories(): """ Gets the list of categories. """ # TODO: pagination <|code_end|> . Use current file imports: from flask import Blueprint, re...
return jsonify(Category.all())
Given the following code snippet before the placeholder: <|code_start|> name = form.name.data description = form.description.data category = Category(name=name, description=description) category.save() return '', 201 @category_api.route('/<int:category_id>', methods=['PUT']) @required_access('adm...
service = Service.get(data['id'])
Given the code snippet: <|code_start|> category_api = Blueprint('category_api', __name__) @category_api.route('', methods=['GET']) @login_required def get_categories(): """ Gets the list of categories. """ # TODO: pagination return jsonify(Category.all()) @category_api.route('/<int:category_id>...
@required_access('admin')
Predict the next line after this snippet: <|code_start|> category_api = Blueprint('category_api', __name__) @category_api.route('', methods=['GET']) @login_required def get_categories(): """ Gets the list of categories. """ # TODO: pagination <|code_end|> using the current file's imports: from flas...
return jsonify(Category.all())
Predict the next line after this snippet: <|code_start|>category_api = Blueprint('category_api', __name__) @category_api.route('', methods=['GET']) @login_required def get_categories(): """ Gets the list of categories. """ # TODO: pagination return jsonify(Category.all()) @category_api.route('/<...
return api_error(form.errors)
Here is a snippet: <|code_start|>def mark_need_resolved(need_id): """ Resolve a need and close an alert if necessary. Send out a message stating the alert was closed as well. """ need = Need.get(need_id) # Check validity of need_id if not need: return api_error('Need not found') ...
resolve_need(need)
Given the following code snippet before the placeholder: <|code_start|> @need_api.route('/<int:need_id>') @required_access('advocate', 'admin') def get_need(need_id): need = Need.get(need_id) if not need: return api_error('Need not found') if not current_user.is_admin and current_user.id != need.ale...
form = ResolveNeedForm(need=need)
Next line prediction: <|code_start|> need_api = Blueprint('need_api', __name__) @need_api.route('/<int:need_id>') @required_access('advocate', 'admin') def get_need(need_id): <|code_end|> . Use current file imports: (from datetime import datetime from flask import Blueprint from flask.ext.login import current_user...
need = Need.get(need_id)
Predict the next line after this snippet: <|code_start|> need_api = Blueprint('need_api', __name__) @need_api.route('/<int:need_id>') @required_access('advocate', 'admin') def get_need(need_id): need = Need.get(need_id) if not need: <|code_end|> using the current file's imports: from datetime import datet...
return api_error('Need not found')
Given the code snippet: <|code_start|> need_api = Blueprint('need_api', __name__) @need_api.route('/<int:need_id>') @required_access('advocate', 'admin') def get_need(need_id): need = Need.get(need_id) if not need: return api_error('Need not found') if not current_user.is_admin and current_user....
return jsonify(need.to_advocate_json())
Next line prediction: <|code_start|> try: except: celery = Celery('15thnight', broker=CELERY_BROKER) def init_app(app): TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskB...
mailer.send(message)
Next line prediction: <|code_start|>"""sort order not null Revision ID: 3e7e65c44fc2 Revises: 368b199625d8 Create Date: 2016-08-21 03:05:06.778204 """ # revision identifiers, used by Alembic. revision = '3e7e65c44fc2' down_revision = '368b199625d8' branch_labels = None depends_on = None def upgrade(): ### co...
Category.__table__.update()
Predict the next line after this snippet: <|code_start|>"""sort order not null Revision ID: 3e7e65c44fc2 Revises: 368b199625d8 Create Date: 2016-08-21 03:05:06.778204 """ # revision identifiers, used by Alembic. revision = '3e7e65c44fc2' down_revision = '368b199625d8' branch_labels = None depends_on = None def u...
Service.__table__.update()
Next line prediction: <|code_start|># useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with INSPIRE-SCHEMAS; ...
assert validate(record['addresses'], subschema) is None
Predict the next line after this snippet: <|code_start|># # You should have received a copy of the GNU General Public License # along with INSPIRE-SCHEMAS; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive...
result = ConferenceReader(record).city
Based on the snippet: <|code_start|> from __future__ import absolute_import, division, print_function class SeminarBuilder(RecordBuilder): """Seminar record builder.""" _collections = ['Seminars'] @staticmethod def _prepare_url(value, description=None): """Build url dict satysfying url.yml...
@filter_empty_parameters
Given the code snippet: <|code_start|> Args: captioned (boolean) """ if captioned is not None: self.record['captioned'] = captioned def set_end_datetime(self, date=None): """ Args: date (str) """ if date is not None: ...
value=sanitize_html(value)
Predict the next line for this snippet: <|code_start|> """Conferences builder class and related code.""" from __future__ import absolute_import, division, print_function class SeminarBuilder(RecordBuilder): """Seminar record builder.""" _collections = ['Seminars'] @staticmethod def _prepare_url(v...
validate(self.record, 'seminars')
Continue the code snippet: <|code_start|> from __future__ import absolute_import, division, print_function class ConferenceBuilder(RecordBuilder): """Conference record builder.""" _collections = ['Conferences'] @staticmethod def _prepare_url(value, description=None): """Build url dict saty...
@filter_empty_parameters
Predict the next line after this snippet: <|code_start|> """ if date is not None: self.record['closing_date'] = normalize_date(date=date) def set_core(self, core=True): """Set core flag. Args: core (bool): define a core article """ self.record...
value=sanitize_html(value)
Given snippet: <|code_start|> """Conferences builder class and related code.""" from __future__ import absolute_import, division, print_function class ConferenceBuilder(RecordBuilder): """Conference record builder.""" _collections = ['Conferences'] @staticmethod def _prepare_url(value, descriptio...
validate(self.record, 'conferences')
Given the code snippet: <|code_start|># as an Intergovernmental Organization or submit itself to any jurisdiction. from __future__ import absolute_import, division, print_function class RecordBuilder(object): """Base record builder.""" _collections = [] def __init__(self, record=None, source=None): ...
if element not in EMPTIES:
Given the code snippet: <|code_start|># MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. from __future__ import absolute_import, division, print_functi...
@filter_empty_parameters
Given the code snippet: <|code_start|> return schema_data inspire_format_checker = draft4_format_checker inspire_format_checker.checks('date', raises=ValueError)(PartialDate.loads) inspire_format_checker.checks('uri-reference', raises=ValueError)( partial(rfc3987.parse, rule='URI_reference') ) inspire_format_c...
raise SchemaKeyNotFound(data=data)
Next line prediction: <|code_start|> """ stripped_path = path.split(os.path.sep, 1)[1:] return ''.join(stripped_path) def _schema_to_normalized_path(schema): """Pass doctests. Extracts the path from the url, makes sure to get rid of any '..' in the path and adds the ...
raise SchemaNotFound(schema=schema)
Given the following code snippet before the placeholder: <|code_start|> uid (string): a UID string schema (string): try to resolve to schema Returns: Tuple[string, string]: a tuple (uid, schema) where: - uid: the UID normalized to comply with the id.json schema - schema: a sc...
raise SchemaUIDConflict(schema, uid)
Given the code snippet: <|code_start|> return func_wrapper def author_id_normalize_and_schema(uid, schema=None): """Detect and normalize an author UID schema. Args: uid (string): a UID string schema (string): try to resolve to schema Returns: Tuple[string, string]: a tuple (ui...
raise UnknownUIDSchema(uid)
Based on the snippet: <|code_start|># Copyright (C) 2014-2017 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # INS...
class AuthorBuilder(RecordBuilder):
Given snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with INSPIRE. If not, see <http://www.gnu.org/licenses/>. # # In applying this license, CERN does not w...
@filter_empty_parameters
Given snippet: <|code_start|> self.record, 'publication_info.year[0]', default='' )) @property def is_published(self): """Return True if a record is published. We say that a record is published if it is citeable, which means that it has enough...
is_citeable(self.record['publication_info'])
Predict the next line for this snippet: <|code_start|> example_path = os.path.join(FIXTURES_PATH, schema_name + '_example.json') with open(example_path) as example_fd: data = json.loads(example_fd.read()) return data def change_something(data): for key, elem in data.items(): if isinsta...
api.validate(data=example_data, schema=schema_name)
Predict the next line for this snippet: <|code_start|># MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Jobs builder class and related code.""" fr...
@filter_empty_parameters
Next line prediction: <|code_start|> Args: value (str): Url itself. description (str): Description of the url. """ entry = self._prepare_url(value, description) self._append_to('urls', entry) @filter_empty_parameters def set_deadline(self, deadline): ...
self.record['description'] = sanitize_html(description)
Using the snippet: <|code_start|># along with INSPIRE-SCHEMAS; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmenta...
validate(self.record, 'jobs')
Predict the next line after this snippet: <|code_start|> self.obj = signature def _ensure_field(self, field_name, value): if field_name not in self.obj: self.obj[field_name] = value def _ensure_list_field(self, field_name, value): if value: self._ensure_field(fie...
@filter_empty_parameters
Given snippet: <|code_start|> self._ensure_list_field('emails', email) @filter_empty_parameters def set_full_name(self, full_name): self._ensure_field('full_name', normalize_name(full_name)) @filter_empty_parameters def _add_uid(self, uid, schema): self._ensure_list_field('ids',...
uid, schema = author_id_normalize_and_schema(uid, schema)
Given snippet: <|code_start|> @filter_empty_parameters def set_full_name(self, full_name): self._ensure_field('full_name', normalize_name(full_name)) @filter_empty_parameters def _add_uid(self, uid, schema): self._ensure_list_field('ids', { 'value': uid, 'schema'...
except UnknownUIDSchema:
Given snippet: <|code_start|>"""Generate a restructured text document that describes built-in magsystems and save it to this module's docstring for the purpose of including in sphinx documentation via the automodule directive.""" lines = ['', ' '.join([10*'=', 60*'=', 35*'=', 15*'=']), '{0:10} {...
for m in _MAGSYSTEMS.get_loaders_metadata():
Based on the snippet: <|code_start|> # Read header line for item in line.split(delim): colnames.append(item.strip()) cols.append([]) readingdata = True continue # Now we're reading data items = line.split(delim) for...
name_to_band = {name: get_bandpass(name, r)
Using the snippet: <|code_start|> Filename. format : {'ascii', 'salt2', 'snana', 'json'}, optional Format of file. Default is 'ascii'. 'salt2' is the new format available in snfit version >= 2.3.0. delim : str, optional **[ascii only]** Character used to separate entries on a line...
data = dict_to_array(data)
Here is a snippet: <|code_start|>"""Generate a restructured text document that describes built-in bandpasses and save it to this module's docstring for the purpose of including in sphinx documentation via the automodule directive.""" __all__ = [] # so that bandpass_table is not documented. # string.ascii_letters in...
bandpass_meta = _BANDPASSES.get_loaders_metadata()
Next line prediction: <|code_start|> lines.append(".. [{0}] {1}".format(refkey, ref)) return "\n".join(lines) # ----------------------------------------------------------------------------- # Build the module docstring # Get the names of all filtersets setnames = [] for m in bandpass_meta: setname = m...
bandpass_interpolator_meta = _BANDPASS_INTERPOLATORS.get_loaders_metadata()
Using the snippet: <|code_start|> self._phase = phase self._wave = wave # ensure that fluxes are on the same scale flux2 = flux1.max() / flux2.max() * flux2 self._model_flux1 = RectBivariateSpline(phase, wave, flux1, kx=3, ky=3) self._model_flux2 = RectBivariateS...
DATADIR.abspath('models/nugent/sn1a_flux.v1.2.dat'))
Given snippet: <|code_start|> self._wave_unit = u.AA # internally, flux is in F_lambda: if unit != FLAMBDA_UNIT: self.flux = unit.to(FLAMBDA_UNIT, self.flux, u.spectral_density(u.AA, self.wave)) self._unit = FLAMBDA_UNIT # Set up inter...
band = get_bandpass(band)
Predict the next line after this snippet: <|code_start|> of the spectrum. The result is a weighted sum of the spectral flux density values (weighted by transmission values). Parameters ---------- band : Bandpass or str Bandpass object or name of registered bandpass. ...
return np.sum(wave * trans * f) * dwave / HC_ERG_AA
Continue the code snippet: <|code_start|> def bandflux(self, band): """Perform synthentic photometry in a given bandpass. The bandpass transmission is interpolated onto the wavelength grid of the spectrum. The result is a weighted sum of the spectral flux density values (weighted by ...
SPECTRUM_BANDFLUX_SPACING)
Based on the snippet: <|code_start|>class SpectrumModel(object): """A model spectrum, representing wavelength and spectral density values. Parameters ---------- wave : list_like Wavelength values. flux : list_like Spectral flux density values. wave_unit : `~astropy.units.Unit` ...
if unit != FLAMBDA_UNIT:
Next line prediction: <|code_start|> def bandflux(self, band): """Perform synthentic photometry in a given bandpass. The bandpass transmission is interpolated onto the wavelength grid of the spectrum. The result is a weighted sum of the spectral flux density values (weighted by tran...
wave, dwave = integration_grid(band.minwave(), band.maxwave(),
Using the snippet: <|code_start|> """Test downloading all of the builtins These tests download lots of files (~1.2 GB as of Oct. 12, 2021) so they aren't included by default with the regular tests. They can be run with `tox -e builtins`. This will make sure that the downloads happen in a clean environment without an...
bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()]
Given the code snippet: <|code_start|> """Test downloading all of the builtins These tests download lots of files (~1.2 GB as of Oct. 12, 2021) so they aren't included by default with the regular tests. They can be run with `tox -e builtins`. This will make sure that the downloads happen in a clean environment witho...
_BANDPASS_INTERPOLATORS.get_loaders_metadata()]
Given the following code snippet before the placeholder: <|code_start|> """Test downloading all of the builtins These tests download lots of files (~1.2 GB as of Oct. 12, 2021) so they aren't included by default with the regular tests. They can be run with `tox -e builtins`. This will make sure that the downloads ha...
magsystems = [i['name'] for i in _MAGSYSTEMS.get_loaders_metadata()]
Continue the code snippet: <|code_start|> """Test downloading all of the builtins These tests download lots of files (~1.2 GB as of Oct. 12, 2021) so they aren't included by default with the regular tests. They can be run with `tox -e builtins`. This will make sure that the downloads happen in a clean environment wi...
sources = [(i['name'], i['version']) for i in _SOURCES.get_loaders_metadata()]
Predict the next line after this snippet: <|code_start|> Notes ----- ``skynoise`` is the image background contribution to the flux measurement error (in units corresponding to the specified zeropoint and zeropoint system). To get the error on a given measurement, ``skynoise`` is added in quadratu...
colname = alias_map(observations.colnames, OBSERVATIONS_ALIASES,
Predict the next line after this snippet: <|code_start|> # when this test was written (does not test whether the number is # correct) assert len(z) == 14 # check that all values are indeed between the input limits. zarr = np.array(z) assert np.all((zarr > 0.) & (zarr < 0.25)) def test_realize_...
model = sncosmo.Model(source=flatsource())
Predict the next line for this snippet: <|code_start|> """Effect with transmission 0 below cutoff wavelength, 1 above. Useful for testing behavior with redshift.""" _param_names = ['stepwave'] param_names_latex = [r'\lambda_{s}'] def __init__(self, minwave, maxwave, stepwave=10000.): self._...
registry.register(self.source, name="testsource",
Next line prediction: <|code_start|>"""Generate a restructured text document that describes built-in sources and save it to this module's docstring for the purpose of including in sphinx documentation via the automodule directive.""" lines = [ '', ' '.join([30*'=', 7*'=', 10*'=', 27*'=', 30*'=', 7*'=', 20*...
for m in _SOURCES.get_loaders_metadata():
Continue the code snippet: <|code_start|> # Descriptions for docstring only. _photdata_descriptions = { 'time': 'Time of observation in days', 'band': 'Bandpass of observation', 'flux': 'Flux of observation', 'fluxerr': 'Gaussian uncertainty on flux', 'zp': 'Zeropoint corresponding to flux', 'zp...
for colname in PHOTDATA_ALIASES:
Based on the snippet: <|code_start|> Parameters ---------- data : `~astropy.table.Table`, dict, `~numpy.ndarray` Astropy Table, dictionary of arrays or structured numpy array containing the "correct" column names. """ def __init__(self, data): # get column names in input dat...
self.band[i] = get_bandpass(band_orig[i])
Given the following code snippet before the placeholder: <|code_start|> newdata.zpsys = self.zpsys[key] newdata.fluxcov = (None if self.fluxcov is None else self.fluxcov[np.ix_(key, key)]) return newdata def normalized(self, zp=25., zpsys='ab'): """Return ...
normmagsys = get_magsystem(zpsys)
Here is a snippet: <|code_start|>class PhotometricData(object): """Internal standardized representation of photometric data table. Has attributes ``time``, ``band``, ``flux``, ``fluxerr``, ``zp`` and ``zpsys``, which are all numpy arrays of the same length sorted by ``time``. ``band`` is an array of Ba...
mapping = alias_map(colnames, PHOTDATA_ALIASES,
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # ============================================================================== # Stores an io-implied do list class IODoList(BasicRepr): # Stores '(obj1, obj2, ..., objn, i=1, n) def __init__(self,sParOpen, obj1, sComma1): s...
self.lObj = DoubleList(l1=[obj1], l2=[sComma1])
Predict the next line after this snippet: <|code_start|> line_type=self.CONT_STATEMENT # check for macro-token types (string literals, continuation # markers,statement separators (;) and trailing comments) col_num = self.Tokenise(line_num,col_num,everything[j]) # if...
sOld=AttributeString(sOld)
Predict the next line for this snippet: <|code_start|> everything = self.re_all_tokens.findall(line) spacing = self.re_all_tokens.split(line) for j in range(len(everything)): space_len = len(spacing[j]) space_text = lstrip(spacing[j]) if space_text!='': ...
self.AppendAttribute(Comment(remainder, (line_num, col_num)))