Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> the client identifier and redirection URI.
**state**
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
:param uri: The full redirect URL back to the client.
... | raise MismatchingStateError() |
Continue the code snippet: <|code_start|> once, the authorization server MUST deny the request and SHOULD
revoke (when possible) all tokens previously issued based on
that authorization code. The authorization code is bound to
the client identifier and redirection URI.
... | raise MissingCodeError("Missing code parameter in response.") |
Given the code snippet: <|code_start|> "code" and "token".
:param client_id: The client identifier as described in `Section 2.2`_.
:param redirect_uri: The client provided URI to redirect back to after
authorization as described in `Section 3.1.2`_.
:param s... | raise InsecureTransportError() |
Given snippet: <|code_start|> state between the request and callback. The authorization
server includes this value when redirecting the user-agent
back to the client. The parameter SHOULD be used for
preventing cross-site request forgery as descri... | params.append(('scope', list_to_scope(scope))) |
Continue the code snippet: <|code_start|> expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
**scope**
OPTIONAL, if identical to the scope ... | params['scope'] = scope_to_list(params['scope']) |
Given the code snippet: <|code_start|> :param response_type: To indicate which OAuth 2 grant/flow is required,
"code" and "token".
:param client_id: The client identifier as described in `Section 2.2`_.
:param redirect_uri: The client provided URI to redirect back to after
... | if not is_secure_transport(uri): |
Continue the code snippet: <|code_start|>
class BaseEndpoint(object):
def __init__(self):
self._available = True
self._catch_errors = False
@property
def available(self):
return self._available
@available.setter
def available(self, available):
self._available = a... | e = TemporarilyUnavailableError() |
Given snippet: <|code_start|>
@available.setter
def available(self, available):
self._available = available
@property
def catch_errors(self):
return self._catch_errors
@catch_errors.setter
def catch_errors(self, catch_errors):
self._catch_errors = catch_errors
def cat... | error = ServerError() |
Given snippet: <|code_start|> @property
def available(self):
return self._available
@available.setter
def available(self, available):
self._available = available
@property
def catch_errors(self):
return self._catch_errors
@catch_errors.setter
def catch_errors(se... | except FatalClientError: |
Next line prediction: <|code_start|> self._catch_errors = False
@property
def available(self):
return self._available
@available.setter
def available(self, available):
self._available = available
@property
def catch_errors(self):
return self._catch_errors
@... | except OAuth2Error: |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming and providing OAuth 2.0 RFC6749.
"""
from __future__ import absolute_import, unicode_literals
<|code_end|>
. Use current file import... | class TokenEndpoint(BaseEndpoint): |
Using the snippet: <|code_start|> unrecognized request parameters. Request and response parameters
MUST NOT be included more than once::
# Delegated to each grant type.
.. _`Appendix B`: http://tools.ietf.org/html/rfc6749#appendix-B
"""
def __init__(self, default_grant_type, default_token... | @catch_errors_and_unavailability |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming and providing OAuth 2.0 RFC6749.
"""
from __future__ import absolute_import, unicode_literals
<|code_end|>
, determine the next line of... | class ResourceEndpoint(BaseEndpoint): |
Continue the code snippet: <|code_start|> # For most cases, returning a 403 should suffice.
The method in which the client utilizes the access token to
authenticate with the resource server depends on the type of access
token issued by the authorization server. Typically, it involves
using the ... | @catch_errors_and_unavailability |
Based on the snippet: <|code_start|> '/\*[^*]*WHITELIST = (\{.*?\})\s*\*/', rawrules, flags=re.DOTALL)
return set(json.loads(m.group(1)) if m else [])
def get_rules(self):
rawrules = self._recursive_fetch(self.rules_url)
try:
if type(rawrules) is unicode:
... | cachefile = os.path.join(settings.CACHEDIR, cachefile) |
Given snippet: <|code_start|>
try:
except ImportError:
class TestWebMalwareScanner(TestCase):
def _load_file_rules(self, path):
args = namedtuple('Args', 'rules')(rules=path)
return Files(args=args).get()
def setUp(self):
settings.CACHEDIR = '/tmp'
settings.LAST_RUN_FILE = '... | self.state_file = scan.scanpath_to_runfile(self.target_path) |
Given the following code snippet before the placeholder: <|code_start|>
try:
except ImportError:
class TestWebMalwareScanner(TestCase):
def _load_file_rules(self, path):
args = namedtuple('Args', 'rules')(rules=path)
return Files(args=args).get()
def setUp(self):
<|code_end|>
, predict the ... | settings.CACHEDIR = '/tmp' |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
class TestWebMalwareScanner(TestCase):
def _load_file_rules(self, path):
args = namedtuple('Args', 'rules')(rules=path)
<|code_end|>
with the help of current file imports:
import os
import time
import mock
from unittest... | return Files(args=args).get() |
Continue the code snippet: <|code_start|>
try:
except ImportError:
# speed up repeated tests, depends on py2/3 pickle version
try:
requests_cache.install_cache('rulesets-{0}'.format(sys.version_info[0]), expire_after=3600 * 24)
except ImportError:
pass
settings.CACHEDIR = '/cachedir'
openmock = mwscan.rulese... | provobj = providers[provider]() |
Predict the next line after this snippet: <|code_start|> # no other way to count unfortunately
got_numrules = len(list(iter(rules)))
got_numwhitelist = len(whitelist)
assert type(rules).__name__ == 'Rules', \
'wrong type: %s' % type(rules).__name__
assert got_numrule... | self.rp = RulesProvider() |
Given the following code snippet before the placeholder: <|code_start|>
try:
except ImportError:
# speed up repeated tests, depends on py2/3 pickle version
try:
requests_cache.install_cache('rulesets-{0}'.format(sys.version_info[0]), expire_after=3600 * 24)
except ImportError:
pass
<|code_end|>
, predict the... | settings.CACHEDIR = '/cachedir' |
Continue the code snippet: <|code_start|> 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 this program; if... | parser.add_argument('--excludefile', help=argparse.SUPPRESS, default=settings.DEFAULT_EXCLUDEFILE) |
Continue the code snippet: <|code_start|> (at your option) any later version.
This program is distributed in the hope that it will be 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 de... | parser.add_argument('-s', '--ruleset', choices=sorted(providers.keys()), default='mwscan', help='Download and use from upstream') |
Predict the next line for this snippet: <|code_start|>
# Register your models here.
class CompetitionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Meta:
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from competition.models import Competition... | model = Competition |
Based on the snippet: <|code_start|>
# Register your models here.
class CompetitionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Meta:
model = Competition
class ChallengeAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Meta:
<|code_end|>
,... | model = Challenge |
Given the code snippet: <|code_start|>
# Register your models here.
class CompetitionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Meta:
model = Competition
class ChallengeAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Meta:
mode... | admin.site.register(ChallengeFile) |
Next line prediction: <|code_start|>
def ctf_sidebar(request):
context = {
'sidebar': {
<|code_end|>
. Use current file imports:
(from competition.models import Competition)
and context including class names, function names, or small code snippets from other files:
# Path: competition/models.py
# class ... | 'ctfs': Competition.objects.only('name', 'slug') |
Predict the next line after this snippet: <|code_start|>
holder = ButtonHolder(
Submit('submit', 'Submit'),
Reset('reset', 'Reset'),
css_class='text-right'
)
self.add_helper.layout = Layout(
Fieldset(
'Add a challenge',
... | model = Challenge |
Here is a snippet: <|code_start|>
button_holder = ButtonHolder(
Submit('submit', 'Submit'),
Reset('reset', 'Reset'),
css_class='text-right'
)
self.add_helper.layout = Layout(
Fieldset(
'Add a competition',
'name',
... | model = Competition |
Given the code snippet: <|code_start|>
self.update_helper = FormHelper()
self.update_helper.form_id = 'update-file'
self.update_helper.form_method = 'post'
self.update_helper.form_action = ''
holder = ButtonHolder(
Submit('submit', 'Submit'),
Reset('reset... | model = ChallengeFile |
Next line prediction: <|code_start|>
try:
# not required since it's included, but...
except ImportError:
@login_required
@require_GET
def chart_data(request, ctf_slug):
<|code_end|>
. Use current file imports:
(import json
import datetime as dt
from django.contrib.auth.decorators import login_required
from dja... | ctf = get_object_or_404(Competition.objects.prefetch_related('challenges'), slug=ctf_slug) |
Given the code snippet: <|code_start|>
try:
# not required since it's included, but...
except ImportError:
@login_required
@require_GET
def chart_data(request, ctf_slug):
ctf = get_object_or_404(Competition.objects.prefetch_related('challenges'), slug=ctf_slug)
challenges = ctf.challenges
# compute... | solved_challenges = challenges.filter(progress=Challenge.SOLVED) |
Given the following code snippet before the placeholder: <|code_start|>
# Py2+3 unix time
if ctf.start_time is not None:
start_time = (ctf.start_time - dt.datetime(1970, 1, 1, tzinfo=UTC)).total_seconds()
else:
start_time = None
if ctf.end_time is not None:
end_time = (ctf.end_ti... | return JSONResponse(json.dumps(data)) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Pytest configuration."""
fr... | InvenioPIDStore(app) |
Predict the next line after this snippet: <|code_start|> $ ./app-teardown.sh
SPHINX-END
"""
from __future__ import absolute_import, print_function
# Create Flask application
app = Flask(__name__)
app.config.update(
DB_VERSIONING_USER_MODEL=None,
SECRET_KEY='test_key',
SECURITY_PASSWORD_HASH='pbkdf2... | InvenioPIDStore(app) |
Predict the next line for this snippet: <|code_start|>#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""DataCite PID provider."""
from __future__ import absolute_import
class RecordIdProviderV2(BaseProvider):
"""R... | default_status_with_obj = PIDStatus.REGISTERED |
Based on the snippet: <|code_start|>def test_recid_fetcher(app, db):
"""Test legacy recid fetcher."""
with app.app_context():
rec_uuid = uuid.uuid4()
data = {}
minted_pid = recid_minter(rec_uuid, data)
fetched_pid = recid_fetcher(rec_uuid, data)
assert minted_pid.pid_valu... | current_pidstore.register_fetcher('anothername', recid_minter) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Fetcher tests."""
from __future__ import abso... | fetched_pid = recid_fetcher(rec_uuid, data) |
Using the snippet: <|code_start|>#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Fetcher tests."""
from __future__ import absolute_import, print_function
def test_recid_fetcher(app, db):
"""Test legacy recid fet... | fetched_pid = recid_fetcher_v2(rec_uuid, data) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Fetcher tests."""
from __future__ import absolut... | minted_pid = recid_minter(rec_uuid, data) |
Predict the next line after this snippet: <|code_start|># This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Fetcher tests."""
from __future__ import absolute_i... | minted_pid = recid_minter_v2(rec_uuid, data) |
Given snippet: <|code_start|> return provider.pid
def recid_minter(record_uuid, data):
"""Mint record identifiers.
This is a minter specific for records.
With the help of
:class:`invenio_pidstore.providers.recordid.RecordIdProvider`, it creates
the PID instance with `rec` as predefined `object... | provider = RecordIdProvider.create( |
Continue the code snippet: <|code_start|>#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Persistent identifier minters."""
from __future__ import absolut... | provider = RecordIdProviderV2.create( |
Based on the snippet: <|code_start|>
FetchedPID = namedtuple('FetchedPID', ['provider', 'pid_type', 'pid_value'])
"""A pid fetcher."""
def recid_fetcher_v2(record_uuid, data):
"""Fetch a record's identifiers.
:param record_uuid: The record UUID.
:param data: The record metadata.
:returns: A :data:`i... | provider=RecordIdProvider, |
Given snippet: <|code_start|>
.. code-block:: python
def my_fetcher(record_uuid, data):
return FetchedPID(
provider=MyRecordIdProvider,
pid_type=MyRecordIdProvider.pid_type,
pid_value=extract_pid_value(data),
)
To see more about providers see :mod:`invenio_pidst... | provider=RecordIdProviderV2, |
Given the following code snippet before the placeholder: <|code_start|>
pid = recid_minter(rec_uuid, data)
assert pid
assert data[app.config['PIDSTORE_RECID_FIELD']] == pid.pid_value
assert pid.object_type == 'rec'
assert pid.object_uuid == rec_uuid
def test_recid_minter_v2(ap... | current_pidstore.register_minter('anothername', recid_minter) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Minter tests."""
from __future__ import absol... | pid = recid_minter(rec_uuid, data) |
Given the code snippet: <|code_start|># under the terms of the MIT License; see LICENSE file for more details.
"""Minter tests."""
from __future__ import absolute_import, print_function
def test_recid_minter(app, db):
"""Test legacy recid minter."""
with app.app_context():
rec_uuid = uuid.uuid4()
... | pid = recid_minter_v2(rec_uuid, data) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2019 CERN.
# Copyright (C) 2019 Northwestern University.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""... | default_status = PIDStatus.NEW |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Record identifier model tests."""
from __futu... | assert RecordIdentifier.next() == 1 |
Next line prediction: <|code_start|>
def _tsmi(dataset):
out = (dataset.red + dataset.green) * 0.0001 / 2
return out.where(out>0, 0)
def tsm(dataset_in, clean_mask=None, no_data=0):
"""
Calculate Total Suspended Matter (TSM) for water.
Parameters
----------
dataset_in: xarray.Dataset
... | clean_mask = create_default_clean_mask(dataset_in) |
Next line prediction: <|code_start|> dataset_in: xarray.Dataset
A dataset retrieved from the Data Cube; should contain:
coordinates: time, latitude, longitude
variables: variables to be mosaicked (e.g. red, green, and blue bands)
clean_mask: np.ndarray
An ndarray of the same shape... | clean_mask = create_default_clean_mask(dataset_in) |
Given the following code snippet before the placeholder: <|code_start|> """
return (ds.swir1 - ds.nir) / (ds.swir1 + ds.nir)
def DBSI(ds, normalize=True):
"""
Computes the Dry Bare-Soil Index as defined in the paper "Applying
Built-Up and Bare-Soil Indices from Landsat 8 to Cities in Dry Climates".... | dbsi = (ds.swir1 - ds.green) / (ds.swir1 + ds.green) - NDVI(ds) |
Given the code snippet: <|code_start|># This import is only for
def EVI(*args, **kwargs):
"""
Instead of this function, please use the EVI() function in vegetation.py.
"""
return _EVI_orig(*args, **kwargs)
def EVI2(*args, **kwargs):
"""
Instead of this function, please use the EVI2() functio... | return _NDVI_orig(*args, **kwargs) |
Predict the next line after this snippet: <|code_start|>
def landsat_clean_mask_invalid(dataset, platform, collection, level):
"""
Masks out invalid data according to the LANDSAT
surface reflectance specifications. See this document:
https://landsat.usgs.gov/sites/default/files/documents/ledaps_product_... | rng = get_range(platform, collection, level) |
Based on the snippet: <|code_start|> classified[_tmp2] = 0 #Node 34
_tmp = r1 & ~r11
r18 = ndi_52 <= 0.34
classified[_tmp & ~r18] = 0 #Node 36
_tmp &= r18
r19 = band1 <= 249.5
classified[_tmp & ~r19] = 0 #Node 38
_tmp &= r19
r20 = ndi_43 <= 0... | clean_mask = create_default_clean_mask(dataset_in) |
Given the following code snippet before the placeholder: <|code_start|> self.times = [
datetime(1999, 5, 6),
datetime(2006, 1, 2),
datetime(2006, 1, 16),
datetime(2015, 12, 31),
datetime(2016, 1, 1),
]
self.latitudes = [1, 2]
se... | cf_mask = dc_utilities.create_cfmask_clean_mask(dataset.cf_mask) |
Next line prediction: <|code_start|>
class TestChunker(unittest.TestCase):
def setUp(self):
self.negative_to_positive = (-1, 1)
self.positive_to_negative = (1, -1)
self.dates = [
datetime(2005, 1, 1), datetime(2006, 1, 1), datetime(2007, 5, 3), datetime(2014, 2, 1), datetime(2... | dc_chunker.create_geographic_chunks(longitude=self.positive_to_negative, latitude=self.positive_to_negative) |
Here is a snippet: <|code_start|> Fits a polynomial of any positive integer degree to some data - x and y. Returns predicted interpolation values.
Parameters
----------
x: list-like
The x values of the data to fit to.
y: list-like
The y values of the data to fit to.
x_smooth: lis... | n_harm=default_fourier_n_harm): |
Given snippet: <|code_start|># Copyright 2014 Rustici Software
#
# 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 require... | class SerializableBase(Base): |
Given the following code snippet before the placeholder: <|code_start|> for uscore, camel in self._props_corrected.items():
if camel in new_kwargs:
new_kwargs[uscore[1:]] = new_kwargs[camel]
new_kwargs.pop(camel)
super(SerializableBase, self).__init__(**new_kw... | def to_json(self, version=Version.latest): |
Predict the next line for this snippet: <|code_start|> def as_version(self, version=Version.latest):
"""Returns a dict that has been modified based on versioning
in order to be represented in JSON properly
A class should overload as_version(self, version)
implementation in order to t... | result[k] = jsonify_datetime(v) |
Based on the snippet: <|code_start|> return json.dumps(self.as_version(version))
def as_version(self, version=Version.latest):
"""Returns a dict that has been modified based on versioning
in order to be represented in JSON properly
A class should overload as_version(self, version)
... | result[k] = jsonify_timedelta(v) |
Predict the next line after this snippet: <|code_start|> def timestamp(self):
"""The Document timestamp.
:setter: Tries to convert to :class:`datetime.datetime`. If
no timezone is given, makes a naive `datetime.datetime`.
Strings will be parsed as ISO 8601 timestamps.
If a ... | self._timestamp = make_datetime(value) |
Next line prediction: <|code_start|># 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... | doc = Document() |
Using the snippet: <|code_start|># Copyright 2014 Rustici Software
#
# 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 req... | class StatementsResult(SerializableBase): |
Predict the next line after this snippet: <|code_start|>
class StatementsResult(SerializableBase):
_props_req = [
'statements',
'more',
]
_props = []
_props.extend(_props_req)
def __init__(self, *args, **kwargs):
self._statements = None
self._more = None
su... | self._statements = StatementList() |
Given snippet: <|code_start|># Copyright 2014 Rustici Software
#
# 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 require... | _cls = InteractionComponent |
Here is a snippet: <|code_start|>
class Rectangle(object):
def __init__(self, matrix):
self.value = 0.0
self.hue = random()
self.x = randrange(0, matrix.width)
self.y = randrange(0, matrix.height)
self.w = randrange(int(matrix.width/8), int(matrix.width/2))
self.... | hsvToRgb(h=self.hue, v=self.value), |
Using the snippet: <|code_start|>
# implementation of a linear feedback shift register generator that gives us
# n-bits of pseudo-random values, completing the entire sequence before
# repeating.
# polynomials required to calculate a n-bit lsfr. Higher bits are
# available, just not included here yet.
poly = {
2: ... | @timefunc |
Based on the snippet: <|code_start|> def __init__(self, x, y, radius):
self.x = x
self.y = y
self.phase = 0
self.radius = radius
def transform(self, angle):
x = self.x + self.radius * sin(angle)
y = self.y + self.radius * cos(angle)
return x, y
class Ra... | self.hue = getColorGen(0.001) |
Predict the next line for this snippet: <|code_start|> self.y = y
self.dx = dx
self.dy = dy
self.hue = hue
self.age = 0
def update(self, matrix, expires):
decay = 1-(float(self.age)/expires)
self.age += 1
color = hsvToRgb(self.hue, 1, decay)
ma... | self.hue = getHueGen(step=0.05, hue=randint(0, 100)/100.0) |
Given the code snippet: <|code_start|>
class Point(object):
def __init__(self, x, y, dx, dy, hue):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
self.hue = hue
self.age = 0
def update(self, matrix, expires):
decay = 1-(float(self.age)/expires)
... | color = hsvToRgb(self.hue, 1, decay) |
Given snippet: <|code_start|>
class Art(ArtBaseClass):
description = "Downsample a high-res image to improve perceived clarity"
def __init__(self, matrix, config):
self.width = sqrt(matrix.numpix)/3
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ._baseclas... | self.hue = getColorGen(0.001) |
Based on the snippet: <|code_start|>
SEGMENTS=4
HUEDELTA=1/(SEGMENTS*1.5)
class Barber(ArtBaseClass):
def __init__(self, matrix, config):
self.width = int(matrix.width/SEGMENTS)
<|code_end|>
, predict the immediate next line with the help of imports:
from .. _baseclass import ArtBaseClass
from opc.hue... | self.hue = getHueGen(step=0.01) |
Here is a snippet: <|code_start|>
class Art(ArtBaseClass):
description = "Bubbling pixels"
def __init__(self, matrix, config):
self.pieces = int(sqrt(matrix.numpix))
cycles = int(sqrt(matrix.numpix)*2)
<|code_end|>
. Write the next line using the current file imports:
from ._baseclass impo... | self.shrapnel = [Shrapnel(matrix, cycles, saturation=0.2) |
Predict the next line for this snippet: <|code_start|> self.color = color
self.mid = matrix.height/2
self.x = x
self.y = 0
def vote(self, value):
if self.x == value:
return True
if self.y > self.mid:
return False
if self.x-1 <= value ... | self.color = getColorGen(step=0.015, hue=random()) |
Given the code snippet: <|code_start|>
REPEATS = 4
class BarSet(object):
def __init__(self, matrix, horizontal):
# increments are split into primary and secondary. primary items(p)
# increase on subsequent calls, secondary increments happen within
# a call to draw a row.
if hori... | self.color = hsvToRgb(random(), self._stepped(), self._stepped()) |
Predict the next line after this snippet: <|code_start|>
SCALE = 4
class Art(ArtBaseClass):
description = "Demo image rotation"
def __init__(self, matrix, config):
<|code_end|>
using the current file's imports:
from ._baseclass import ArtBaseClass
from math import sqrt
from random import random
from opc... | self.hue = getColorGen(0.006) |
Next line prediction: <|code_start|>
class Art(ArtBaseClass):
description = "Slow transition of hues across the display"
def __init__(self, matrix, config):
self.base = 0
def start(self, matrix):
pass
def refresh(self, matrix):
self.base += 4
h = matrix.height - 1
... | matrix.drawPixel(x, y, hsvToRgb(hue, sat, val)) |
Given snippet: <|code_start|> self.mandel = Mandelbrot(matrix.width, matrix.height, ITERSTEPS)
# this gives a pretty good view of the artifact at max zoom
self.origin = Region(-2.0, -1.5, 1.0, 1.5)
self._begin(matrix)
self.i = 0
def start(self, matrix):
... | matrix.drawPixel(x, y, hsvToRgb(hue)) |
Predict the next line after this snippet: <|code_start|>
ZOOMSTEPS = 24
ITERSTEPS = 30
DEBUG = False
class Art(ArtBaseClass):
description = "Auto-zooming mandelbrot"
def __init__(self, matrix, config):
<|code_end|>
using the current file's imports:
from ._baseclass import ArtBaseClass
from opc.hue impor... | with HQ(matrix): |
Given the following code snippet before the placeholder: <|code_start|> colormap cells
"""
steps = float(index1) - index0
delta = [(color1[gun] - color0[gun]) / steps for gun in range(3)]
for index in range(index0, index1):
c = [color0[gun] + delta[gun] * (index-index... | self.cmap = idw.soften_2d(self.cmap, neighbors) |
Continue the code snippet: <|code_start|>
class Art(ArtBaseClass):
description = "Rolling sine wave marks border between contrasting colors"
def __init__(self, matrix, config):
<|code_end|>
. Use current file imports:
from ._baseclass import ArtBaseClass
from opc.hue import getColorGen
import math
and co... | self.hue1 = getColorGen(step=0.00001, hue=0.0) |
Predict the next line after this snippet: <|code_start|> field = np.empty((matrix.width, matrix.height))
# linearize x and y coordinates for regions
xs = np.array([region["x"] for region in self.regions])
ys = np.array([region["y"] for region in self.regions])
# find closest reg... | matrix.drawPixel(x, y, hsvToRgb(self.field[x,y], 1, 1)) |
Using the snippet: <|code_start|>
DTYPE = np.uint8
class Filter(object):
@timefunc
def maskbelow(self, thresh, color):
"""
Set (r, g, b) values below an average value of thresh
to value
"""
keys = np.mean(self.buf.buf,2)<thresh
self.buf.buf[keys] = color
@... | hsv = rgb_to_hsv(self.buf.buf) |
Here is a snippet: <|code_start|>
class Filter(object):
@timefunc
def maskbelow(self, thresh, color):
"""
Set (r, g, b) values below an average value of thresh
to value
"""
keys = np.mean(self.buf.buf,2)<thresh
self.buf.buf[keys] = color
@timefunc
def m... | rgb = hsv_to_rgb(mod) |
Here is a snippet: <|code_start|>
class Art(ArtBaseClass):
description = "And then it exploded..."
PAUSE_CYCLES = 10
def __init__(self, matrix, config):
self.pause = 0
self.pieces = int(sqrt(matrix.numpix))
cycles = int(sqrt(matrix.numpix)*2)
<|code_end|>
. Write the next line ... | self.shrapnel = [Shrapnel(matrix, cycles, decelerate=True) |
Based on the snippet: <|code_start|>
class Art(ArtBaseClass):
description = "Rain falling down the display"
def __init__(self, matrix, config):
<|code_end|>
, predict the immediate next line with the help of imports:
from ._baseclass import ArtBaseClass
from random import random, randrange
from math impor... | with HQ(matrix): |
Given the code snippet: <|code_start|>
class Flow(ArtBaseClass):
huecount = (8+1) # the addition covers offscreen for recoloring
def __init__(self, matrix, config):
self.base = 0
self.offset = 0
self.usecount = []
self.blocksize = int(matrix.numpix/(self.huecount-1))
... | return hsvToRgb(hue/255) |
Predict the next line after this snippet: <|code_start|>
class Art(Barber):
description = "Barber-pole-esque (clean)"
def _line(self, matrix, x1, x2, hue):
<|code_end|>
using the current file's imports:
from .baseclasses.barber import Barber
from opc.hue import hsvToRgb
and any relevant context from othe... | color = hsvToRgb(hue, 1, 1) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
class Pixel(object):
@timefunc
def setStripPixel(self, z, color):
"""
Exposed helper method that sets a given pixel in the unrolled strip
of LEDs.
"""
x = int(z / self.height)
... | @wrapexception(logger) |
Based on the snippet: <|code_start|>
DELTA_Z = 0.02
class Art(ArtBaseClass):
description = "Lissajous figures"
def __init__(self, matrix, config):
<|code_end|>
, predict the immediate next line with the help of imports:
from ._baseclass import ArtBaseClass
from opc.hue import getColorGen
from math impor... | self.color = getColorGen(0.01) |
Predict the next line for this snippet: <|code_start|>
HSCALE = 0.01
RESET_INTERVAL = 20
class Art(object):
description = "Conway's Game of Life"
def __init__(self, matrix, config):
self._interval = 300 if math.sqrt(matrix.numpix) < 20 else 75
self.hue = random.random()
self._init(... | return hsvToRgb(self.hue+HSCALE*offset) |
Continue the code snippet: <|code_start|> self._sampleDiamond(x, y + halfstep, stepsize,
self._rand() * scale)
def generate(self):
samplesize = self.featureSize
scale = 1.0
# seed initial values
for y in range(0, self.height, sampl... | color = hsvToRgb(hue+values[x, y]/5, 1, values[x, y]) |
Predict the next line after this snippet: <|code_start|> stepsize = int(stepsize)
halfstep = int(stepsize/2)
for y in range(0, self.height+halfstep, stepsize):
for x in range(0, self.width+halfstep, stepsize):
self._sampleSquare(halfstep+x, halfstep+y,
... | @timefunc |
Next line prediction: <|code_start|>
class Art(ArtBaseClass):
description = "Sparse Balistics"
def __init__(self, matrix, config):
<|code_end|>
. Use current file imports:
(from ._baseclass import ArtBaseClass
from .utils.fire import Gun)
and context including class names, function names, or small code sn... | self.gun = Gun(matrix) |
Given the code snippet: <|code_start|>
class Channel(object):
def __init__(self, matrix):
ones = np.ones(matrix.numpix).reshape((matrix.height, matrix.width))
self.x = ones*np.arange(matrix.width)
self.y = np.flipud(np.rot90(np.rot90(ones)*np.arange(matrix.height)))
self.delta = ... | with HQ(matrix): |
Based on the snippet: <|code_start|> """
default = sample[base]
total = None
for distance in range(maxdist, -1, -1):
samples = (
_relative(sample, base, distance, default),
_relative(sample, base, -distance, default)
)
if total is None:
t... | gr = GunRoller(sample) |
Using the snippet: <|code_start|>
class ScrollText(ArtBaseClass):
description = "Scroll text across the display"
fg = None
bg = None
def __init__(self, matrix, config):
self.config = config
self._initText()
self.thisMessage = self._getText()
self.nextMessage = self._... | self.typeface = OPCText(typeface_bbc) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.