Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
##################################################################
# Imports
from __future__ import absolute_import
##################################################################
# Constants
#####################... | xgb = XGBoostSenser() |
Predict the next line for this snippet: <|code_start|>
def _register_standard_tasks(self):
self.registry.register_module_tasks(bolt_conttest)
self.registry.register_module_tasks(bolt_coverage)
self.registry.register_module_tasks(bolt_delete_files)
self.registry.register_module_tasks... | return load_script(self.filename) |
Given the following code snippet before the placeholder: <|code_start|>"""
This module defines exception classes used in the implementation of Bolt to
report errors or as base classes to define other error conditions.
"""
print('WARNING!!! bolt.errors is deprecated. Use bolt.api for exceptions')
<|code_end|>
, predi... | class InvalidConfigurationError(BoltError): |
Given the code snippet: <|code_start|>
class DatabaseUserSource(UserSource):
def __init__(self):
db = get_db()
db.create_table(DatabaseUser, safe=True)
self._db = db
<|code_end|>
, generate the next line using the imports in this file:
from booking.utils.database import get_db
from ..Use... | def add_user(self, user: User): |
Using the snippet: <|code_start|>
class DatabaseUserSource(UserSource):
def __init__(self):
db = get_db()
<|code_end|>
, determine the next line of code. You have imports:
from booking.utils.database import get_db
from ..UserSource import UserSource
from ..User import User
from .DatabaseUser import Datab... | db.create_table(DatabaseUser, safe=True) |
Given the following code snippet before the placeholder: <|code_start|>
class ClassroomSource(ABC):
"""
Class that have the responsibility to save the classroom and to provide access to them.
"""
@abstractmethod
<|code_end|>
, predict the next line using imports from the current file:
from abc impor... | def get_classroom(self, identifier: str) -> Classroom: |
Given the following code snippet before the placeholder: <|code_start|> :param identifier: building identifier.
:return: Returns the classrooms that are in the building.
"""
pass
def is_classroom_present(self, identifier: str):
"""
Tels if a classroom is present insid... | def get_all_buildings(self) -> List[Building]: |
Next line prediction: <|code_start|>
class DatabaseEventsSource(EventsSource):
def __init__(self):
db = get_db()
db.create_table(DatabaseEvent, safe=True)
self._db = db
<|code_end|>
. Use current file imports:
(from datetime import datetime
from datetime import timedelta
from typing impor... | def add_event(self, event: Event): |
Here is a snippet: <|code_start|> event = None
if len(events) > 0:
event = query_result_to_event(events[0])
return event
def get_all_classroom_events(self, classroom_identifier: str):
return query_result_to_events(DatabaseEvent.select()
... | return EventImpl(str(event.name), |
Given snippet: <|code_start|>
class DatabaseEventsSource(EventsSource):
def __init__(self):
db = get_db()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import datetime
from datetime import timedelta
from typing import List
from booking.source.event impor... | db.create_table(DatabaseEvent, safe=True) |
Given the following code snippet before the placeholder: <|code_start|>
class EventsSource(metaclass=ABCMeta):
"""
Class that have the responsibility to save the events and to provide access to them.
"""
@abstractmethod
<|code_end|>
, predict the next line using imports from the current file:
from ... | def add_event(self, event: Event): |
Next line prediction: <|code_start|>
class DatabaseClassroom(BaseModel):
class Meta:
db_table = 'classroom'
"""
Mysql representation of a classroom.
"""
<|code_end|>
. Use current file imports:
(from peewee import *
from booking.utils.database.models.BaseModel import BaseModel
from . import D... | build = ForeignKeyField(DatabaseBuild) |
Given the following code snippet before the placeholder: <|code_start|>
class UserSource(ABC):
"""
Class that represents a source used to store and get the user that use the bot.
"""
@abstractmethod
<|code_end|>
, predict the next line using imports from the current file:
from abc import ABC
from abc... | def get_user_by_identifier(self, identifier: int) -> User: |
Given the code snippet: <|code_start|>
class BaseModel(Model):
"""
Base mysql model class.
"""
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from peewee import *
from ..DatabaseProvider import get_db
and context (functions, classes, or occasionally code) from other... | database = get_db() |
Given snippet: <|code_start|>
class BaseSpider(metaclass=ABCMeta):
"""
Abstract class that represents a spider that collects events from internet.
"""
def __init__(self, url: str):
"""
Default constructor
:param url: The url of the page that contains the events data.
... | def get_buildings_provider(self) -> BuildingsProvider: |
Given the code snippet: <|code_start|> if avatar:
avatar = "https://2017.djangocon.eu{}".format(
avatar
)
return {
"active": True,
"avatar": avatar,
"bio": getattr(submission, "author_bio", ""),
"description": slot.a... | qs = Slot.objects.all() |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
class Slot(ModelMeta, models.Model):
"""
Model for conference time slots. It can be for a talk, a workshop, or a custom time slot (i. e. coffee break)
"""
talk = models.Fore... | Submission, related_name='talks', limit_choices_to={'selected': True}, null=True, blank=True |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
class Slot(ModelMeta, models.Model):
"""
Model for conference time slots. It can be for a talk, a workshop, or a custom time slot (i. e. coffee break)
"""
talk = mode... | WorkshopSubmission, related_name='workshops', limit_choices_to={'selected': True}, null=True, blank=True |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
class Command(NoArgsCommand):
def handle_noargs(self, **options):
<|code_end|>
. Use current file imports:
(from django.core.management.base import NoArgsCommand
from conference.... | for slot in Slot.objects.all(): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
class SlotResource(resources.ModelResource):
class Meta:
<|code_end|>
. Use current file imports:
from django.contrib import admin
from import_export import resources
from ... | model = Slot |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
urlpatterns = [
url(r'^', SubmissionView.as_view(
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from .forms import TalkSubmissionForm
from .models imp... | form_class=TalkSubmissionForm, model=Submission |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
urlpatterns = [
url(r'^', SubmissionView.as_view(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
from .forms import ... | form_class=TalkSubmissionForm, model=Submission |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
def set_submission_as_selected(modeladmin, request, queryset):
queryset.update(selected=True)
set_submission_as_selected.short_description = _("... | @admin.register(Submission) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
def set_submission_as_selected(modeladmin, request, queryset):
queryset.update(selected=True)
set_submission_as_selected.short_description = _("... | @admin.register(WorkshopSubmission) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
urlpatterns = [
url(r'^(?P<slug>[\w.@+-]+)/$', SlotDetail.as_view(), name='talk-detail'),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf... | url(r'^', SlotList.as_view(), name='talk-list'), |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
class TalkSubmissionForm(forms.ModelForm):
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.utils.transl... | model = Submission |
Given the code snippet: <|code_start|>
class Meta:
model = Submission
fields = (
'author', 'email', 'author_bio', 'proposal_title',
'proposal_abstract', 'proposal_why', 'proposal_requirements', 'proposal_audience',
'mentor_wanted', 'mentor_offer', 'notes', 'pycon'... | model = WorkshopSubmission |
Given snippet: <|code_start|>
class CFP_TestCases(TestCase):
def test_closing_date_tomorrow(self):
test_date = datetime.date.today() + datetime.timedelta(days=1)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
from django.test import TestCase
from .vie... | self.assertFalse(is_cfp_closed(test_date.strftime("%Y-%m-%d"))) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
urlpatterns = [
url(r'^', SubmissionView.as_view(
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.conf.urls i... | form_class=WorkshopSubmissionForm, model=WorkshopSubmission, |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
urlpatterns = [
url(r'^', SubmissionView.as_view(
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.conf.urls imp... | form_class=WorkshopSubmissionForm, model=WorkshopSubmission, |
Given the code snippet: <|code_start|>
Returns:
Canonicalized SMILES string, None if the molecule is invalid.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is not None:
return Chem.MolToSmiles(mol, isomericSmiles=include_stereocenters)
else:
return None
def canonicalize_lis... | return remove_duplicates(canonicalized_smiles) |
Based on the snippet: <|code_start|>
def test_num_atoms():
smiles = 'CCOC(CCC)'
mol = Chem.MolFromSmiles(smiles)
<|code_end|>
, predict the immediate next line with the help of imports:
from rdkit import Chem
from guacamol.utils.descriptors import num_atoms, AtomCounter
and context (classes, functions, some... | assert num_atoms(mol) == 21 |
Given snippet: <|code_start|>
def test_num_atoms():
smiles = 'CCOC(CCC)'
mol = Chem.MolFromSmiles(smiles)
assert num_atoms(mol) == 21
def test_num_atoms_does_not_change_mol_instance():
smiles = 'CCOC(CCC)'
mol = Chem.MolFromSmiles(smiles)
assert mol.GetNumAtoms() == 7
num_atoms(mol)
... | assert AtomCounter('C')(mol) == 6 |
Given the code snippet: <|code_start|>
def test_validity_empty_molecule():
smiles = ''
assert not is_valid(smiles)
def test_validity_incorrect_syntax():
smiles = 'CCCincorrectsyntaxCCC'
assert not is_valid(smiles)
def test_validity_incorrect_valence():
smiles = 'CCC(CC)(CC)(=O)CCC'
assert n... | with_stereocenters = canonicalize(endiandric_acid, include_stereocenters=True) |
Next line prediction: <|code_start|> m4 = 'CC(OCON=N)CC'
molecules = [m1, m2, m3, m4]
canonicalized_molecules = canonicalize_list(molecules)
valid_molecules = [m1, m3, m4]
expected = [canonicalize(smiles) for smiles in valid_molecules]
assert canonicalized_molecules == expected
def test_inte... | sim = calculate_pairwise_similarities(molz1, molz2) |
Continue the code snippet: <|code_start|> molz = ['OCCCF', 'c1cc(F)ccc1', 'c1cnc(CO)cc1', 'FOOF']
sim = calculate_internal_pairwise_similarities(molz)
assert sim.shape[0] == 4
assert sim.shape[1] == 4
# check elements
for i in range(sim.shape[0]):
for j in range(sim.shape[1]):
... | parsed = parse_molecular_formula(formula) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class FrechetBenchmark(DistributionLearningBenchmark):
"""
Calculates the Fréchet ChemNet Distance.
See http://dx.doi.org/10.1021/acs.jcim.8b00234 for the publication.
... | def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult: |
Continue the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class FrechetBenchmark(DistributionLearningBenchmark):
"""
Calculates the Fréchet ChemNet Distance.
See http://dx.doi.org/10.1021/acs.jcim.8b00234 for the publication.
"""
de... | def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult: |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class FrechetBenchmark(DistributionLearningBenchmark):
"""
Calculates the Fréchet ChemNet Distance.
See http://dx.doi.org/10.1021/acs.jcim.8b00234 for the publication.
"""
def __i... | self.reference_molecules = get_random_subset(training_set, self.sample_size, seed=42) |
Given the following code snippet before the placeholder: <|code_start|>logger.addHandler(logging.NullHandler())
class FrechetBenchmark(DistributionLearningBenchmark):
"""
Calculates the Fréchet ChemNet Distance.
See http://dx.doi.org/10.1021/acs.jcim.8b00234 for the publication.
"""
def __init__... | generated_molecules = sample_valid_molecules(model=model, number_molecules=self.number_samples) |
Given the code snippet: <|code_start|>
def sample_valid_molecules(model: DistributionMatchingGenerator, number_molecules: int, max_tries=10) -> List[str]:
"""
Sample from the given generator until the desired number of valid molecules
has been sampled (i.e., ignore invalid molecules).
Args:
m... | valid_molecules += [m for m in samples if is_valid(m)] |
Predict the next line for this snippet: <|code_start|>
def sample_unique_molecules(model: DistributionMatchingGenerator, number_molecules: int, max_tries=10) -> List[str]:
"""
Sample from the given generator until the desired number of unique (distinct) molecules
has been sampled (i.e., ignore duplicate mol... | canonical_smiles = canonicalize(smiles) |
Based on the snippet: <|code_start|>
scores = [self.corrupt_score if raw_score is None
else self.modify_score(raw_score)
for raw_score in raw_scores]
return scores
@abstractmethod
def raw_score_list(self, smiles_list: List[str]) -> List[float]:
"""
... | mol = smiles_to_rdkit_mol(smiles) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class InvalidMolecule(Exception):
pass
class ScoringFunction:
"""
Base class for an objective function.
In general, do not inherit directly from this class. Prefer ... | def __init__(self, score_modifier: ScoreModifier = None) -> None: |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class InvalidMolecule(Exception):
pass
class ScoringFunction:
"""
Base class for an objective function.
In general, do not inherit directly from this class. Prefer `MoleculewiseScoring... | self._score_modifier = LinearModifier() if modifier is None else modifier |
Based on the snippet: <|code_start|> scores = []
for function, weight in zip(self.scoring_functions, self.weights):
res = function.score_list(smiles_list)
scores.append(weight * np.array(res))
scores = np.array(scores).sum(axis=0) / np.sum(self.weights)
return l... | return geometric_mean(partial_scores) |
Based on the snippet: <|code_start|>
class GoalDirectedGenerator(metaclass=ABCMeta):
"""
Interface for goal-directed molecule generators.
"""
@abstractmethod
<|code_end|>
, predict the immediate next line with the help of imports:
from abc import ABCMeta, abstractmethod
from typing import List, Opti... | def generate_optimized_molecules(self, scoring_function: ScoringFunction, number_molecules: int, |
Next line prediction: <|code_start|>
scalar_value = 8.343
value_array = np.array([[-3.3, 0, 5.5],
[0.011, 2.0, -33]])
def test_linear_function_default():
<|code_end|>
. Use current file imports:
(from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifi... | f = LinearModifier() |
Next line prediction: <|code_start|>
scalar_value = 8.343
value_array = np.array([[-3.3, 0, 5.5],
[0.011, 2.0, -33]])
def test_linear_function_default():
f = LinearModifier()
assert f(scalar_value) == scalar_value
assert np.array_equal(f(value_array), value_array)
def test_lin... | f = SquaredModifier(target_value=target_value, coefficient=coefficient) |
Based on the snippet: <|code_start|>
def test_linear_function_default():
f = LinearModifier()
assert f(scalar_value) == scalar_value
assert np.array_equal(f(value_array), value_array)
def test_linear_function_with_slope():
slope = 3.3
f = LinearModifier(slope=slope)
assert f(scalar_value) ==... | f = AbsoluteScoreModifier(target_value=target_value) |
Using the snippet: <|code_start|> target_value = 5.555
coefficient = 0.123
f = SquaredModifier(target_value=target_value, coefficient=coefficient)
expected_scalar = 1.0 - coefficient * (target_value - scalar_value) ** 2
expected_array = 1.0 - coefficient * np.square(target_value - value_array)
... | f = GaussianModifier(mu=mu, sigma=sigma) |
Based on the snippet: <|code_start|>def test_absolute_function():
target_value = 5.555
f = AbsoluteScoreModifier(target_value=target_value)
expected_scalar = 1.0 - abs(target_value - scalar_value)
expected_array = 1.0 - np.abs(target_value - value_array)
assert f(scalar_value) == expected_scalar
... | f = MinGaussianModifier(mu=mu, sigma=sigma) |
Given the following code snippet before the placeholder: <|code_start|> assert f(scalar_value) == gaussian(scalar_value, mu, sigma)
assert np.allclose(f(value_array), gaussian(value_array, mu, sigma))
def test_min_gaussian_function():
mu = -1.223
sigma = 0.334
f = MinGaussianModifier(mu=mu, sigma=... | f = MaxGaussianModifier(mu=mu, sigma=sigma) |
Next line prediction: <|code_start|> min_gaussian = np.vectorize(min_gaussian_lambda)
assert f(scalar_value) == min_gaussian(scalar_value)
assert np.allclose(f(value_array), min_gaussian(value_array))
def test_max_gaussian_function():
mu = -1.223
sigma = 0.334
f = MaxGaussianModifier(mu=mu, s... | f = ThresholdedLinearModifier(threshold=threshold) |
Given snippet: <|code_start|> assert f(low_value) == 0.0
assert f(large_value) == 1.0
full_gaussian = partial(gaussian, mu=mu, sig=sigma)
max_gaussian_lambda = lambda x: 1.0 if x > mu else full_gaussian(x)
max_gaussian = np.vectorize(max_gaussian_lambda)
assert f(scalar_value) == max_gaussian(s... | modifier = ClippedScoreModifier(upper_x=max_x, lower_x=min_x, high_score=max_score, low_score=min_score) |
Predict the next line after this snippet: <|code_start|> assert modifier(x) == max_score
# values larger than min_x should be assigned min_score
for x in [8.8, 9.0, 1000]:
assert modifier(x) == min_score
# values in between are interpolated
slope = (max_score - min_score) / (max_x - min... | modifier = SmoothClippedScoreModifier(upper_x=max_x, lower_x=min_x, high_score=max_score, low_score=min_score) |
Using the snippet: <|code_start|> # The smooth clipped function also works for decreasing scores
max_x = 4.4
min_x = 8.8
min_score = -3.3
max_score = 9.2
modifier = SmoothClippedScoreModifier(upper_x=max_x, lower_x=min_x, high_score=max_score, low_score=min_score)
# assert that the slope in... | chained_1 = ChainedModifier([linear, squared]) |
Given snippet: <|code_start|>
def _assess_distribution_learning(model: DistributionMatchingGenerator,
chembl_training_file: str,
json_output_file: str,
benchmark_version: str,
number_s... | benchmarks: List[DistributionLearningBenchmark] |
Continue the code snippet: <|code_start|>def _assess_distribution_learning(model: DistributionMatchingGenerator,
chembl_training_file: str,
json_output_file: str,
benchmark_version: str,
... | ) -> List[DistributionLearningBenchmarkResult]: |
Given the following code snippet before the placeholder: <|code_start|>def assess_distribution_learning(model: DistributionMatchingGenerator,
chembl_training_file: str,
json_output_file='output_distribution_learning.json',
... | benchmarks = distribution_learning_benchmark_suite(chembl_file_path=chembl_training_file, |
Given the code snippet: <|code_start|> chembl_training_file: path to ChEMBL training set, necessary for some benchmarks
json_output_file: Name of the file where to save the results in JSON format
benchmark_version: which benchmark suite to execute
"""
_assess_distribution_learning(model=m... | benchmark_results['timestamp'] = get_time_string() |
Given snippet: <|code_start|>
def test_sample_valid_molecules_with_invalid_molecules():
generator = MockGenerator(['invalid', 'invalid', 'invalid', 'CCCC', 'invalid', 'CC'])
mols = sample_valid_molecules(generator, 2)
assert mols == ['CCCC', 'CC']
def test_sample_valid_molecules_if_not_enough_valid_gen... | mols = sample_unique_molecules(generator, 2) |
Based on the snippet: <|code_start|>
def send_message(self, chat_id, text: str, **kwargs):
if len(text) <= constants.MAX_MESSAGE_LENGTH:
return self.bot.sendMessage(chat_id, text, **self._set_defaults(kwargs))
parts = []
while len(text) > 0:
if len(text) > constants.... | success(text), |
Predict the next line after this snippet: <|code_start|> parts.append(part[:first_lnbr])
text = text[first_lnbr:]
else:
parts.append(text)
break
msg = None
for part in parts:
msg = self.bot.sendMessage(chat_id, part,... | failure(text), |
Given the code snippet: <|code_start|> msg = self.bot.sendMessage(chat_id, part, **self._set_defaults(kwargs))
return msg
def send_success(self, chat_id, text: str, add_punctuation=True, reply_markup=None, **kwargs):
if add_punctuation:
if text[-1] != '.':
tex... | action_hint(text), |
Given the following code snippet before the placeholder: <|code_start|>
def manage_subscription(bot, update):
chat_id = update.effective_chat.id
user_id = update.effective_user.id
<|code_end|>
, predict the next line using imports from the current file:
from telegram import InlineKeyboardButton, InlineKeybo... | if util.is_group_message(update): |
Next line prediction: <|code_start|>
download_session("josxa", appglobals.ACCOUNTS_DIR)
bot_checker = BotChecker(
event_loop=asyncio.get_event_loop(),
<|code_end|>
. Use current file imports:
(import asyncio
import os
import threading
from pathlib import Path
from pyrogram import Client
from botlistbot import ... | session_name=settings.USERBOT_SESSION, |
Next line prediction: <|code_start|>
BUCKET_NAME = "useraccounts"
client = Minio(
config('MINIO_URL'),
access_key=config('MINIO_ACCESS_KEY'),
secret_key=config('MINIO_SECRET_KEY'),
secure=True)
if not client.bucket_exists(BUCKET_NAME):
raise RuntimeError(f"Bucket {BUCKET_NAME} does not exist.")
... | accounts_path = Path(appglobals.ROOT_DIR) / "accounts" |
Predict the next line after this snippet: <|code_start|>{new_bots}
Share your bots in @BotListChat"""
SEARCH_MESSAGE = mdformat.action_hint("What would you like to search for?")
SEARCH_RESULTS = """I found *{num_results} bot{plural}* in the @BotList for "{query}":\n
{bots}
"""
KEYWORD_BEST_PRACTICES = """The following... | FAVORITES_HEADLINE = "*{}* 🔽\n_┌ from_ @BotList".format(captions.FAVORITES) |
Using the snippet: <|code_start|>• /offline @unresponsive\_bot
• "Aaaargh, @spambot's #spam is too crazy!"
• /spam @spambot
"""
REJECTION_WITH_REASON = """Sorry, but your bot submission {} was rejected.
Reason: {reason}
Please adhere to the quality standards we impose for inclusion to the @BotList.
For further infor... | SEARCH_MESSAGE = mdformat.action_hint("What would you like to search for?") |
Here is a snippet: <|code_start|>▫️Use singular where applicable (#̶v̶i̶d̶e̶o̶s̶ video)
▫️Try to tag every supported platform (e.g. #vimeo, #youtube, #twitch, ...)
▫Try to tag every supported action (#search, #upload, #download, ...)
▫Try to tag every supported format (#mp3, #webm, #mp4, ...)
▫Keep it specific (only ta... | {emojis.RECOMMEND_MODERATOR} Recommend another moderator for this submission |
Given the following code snippet before the placeholder: <|code_start|>
db_path = config('DATABASE_URL', default=os.path.expanduser('~/botlistbot.sqlite3'))
db = SqliteExtDatabase(db_path)
migrator = SqliteMigrator(db)
revision = IntegerField(default=100)
with db.transaction():
migrate(
migrator.add_co... | Revision.create_table(fail_silently=True) |
Continue the code snippet: <|code_start|>
@pytest.fixture(scope="session")
def client():
# setup
print('Initializing integration test client')
c = BotIntegrationClient(
<|code_end|>
. Use current file imports:
import pytest
from botlistbot import settings
from tgintegration import BotIntegrationClient
... | bot_under_test=settings.BOT_UNDER_TEST, |
Given the code snippet: <|code_start|>
base = '..\\assets'
class TestTrainer(TestCase):
def test_get_matches(self):
location = os.path.join(base, "ok_box.png")
base_location = os.path.join(base, "nox", "vagabond.png")
black_screen = os.path.join(base, "nox", "black_screen.png")
... | trainer = tm.Trainer(base_img, 480, 50) |
Next line prediction: <|code_start|>
base = '..\\assets'
class TestTrainer(TestCase):
def test_get_matches(self):
location = os.path.join(base, "ok_box.png")
base_location = os.path.join(base, "nox", "vagabond.png")
black_screen = os.path.join(base, "nox", "black_screen.png")
as... | self.assertTrue(trainer.get_matches(location, LOW_CORR) is False) |
Given the code snippet: <|code_start|> continue
self.circlePoints.append((i[0], i[1]))
if self._debug:
self.draw_circles(circles, cimg)
def capture_white_circles(self, x_limit=480, y_limit=670):
self.prep_for_white_circles()
img = cv2.cvtColor(self.whi... | self.white_query = mask_image(lower, upper, self.query, apply_mask=True) |
Predict the next line after this snippet: <|code_start|>
QApplication.setQuitOnLastWindowClosed(False)
uconfig = default_config()
uconfig.read(config_file)
dlRuntime = setup_runtime(uconfig)
dlRuntime.main()
window = DuelLinksGui(dlRuntime, uconfig.get('locations', 'asse... | set_pip_test(True) |
Based on the snippet: <|code_start|> QApplication.setQuitOnLastWindowClosed(False)
uconfig = default_config()
uconfig.read(config_file)
dlRuntime = setup_runtime(uconfig)
dlRuntime.main()
window = DuelLinksGui(dlRuntime, uconfig.get('locations', 'assets'))
window.... | main_install() |
Here is a snippet: <|code_start|>
class TestDuelLinkRunTimeOptions(TestCase):
def setUp(self):
file = r'D:\Sync\OneDrive\Yu-gi-oh_bot\run_at_test.json'
<|code_end|>
. Write the next line using the current file imports:
from unittest import TestCase
from bot.duel_links_runtime import DuelLinkRunTimeOption... | self.runtimeoptions = DuelLinkRunTimeOptions(file) |
Predict the next line for this snippet: <|code_start|>
class TestDuelLinkRunTimeOptions(TestCase):
def setUp(self):
file = r'D:\Sync\OneDrive\Yu-gi-oh_bot\run_at_test.json'
self.runtimeoptions = DuelLinkRunTimeOptions(file)
def test_update(self):
self.runtimeoptions.update()
... | tmp_data = read_json_file(self.runtimeoptions._file) |
Next line prediction: <|code_start|>
class TestDuelLinkRunTimeOptions(TestCase):
def setUp(self):
file = r'D:\Sync\OneDrive\Yu-gi-oh_bot\run_at_test.json'
self.runtimeoptions = DuelLinkRunTimeOptions(file)
def test_update(self):
self.runtimeoptions.update()
self.runtimeoption... | write_data_file(tmp_data, self.runtimeoptions._file) |
Predict the next line after this snippet: <|code_start|>
duel_variant_v = {
'v1' : (800, 800),
'v2-duel' : (640, 800),
'v2-autoduel': (970, 800)
}
class SteamAreas(Enum):
MAINAREA = 1
CARDINFO = 2
LOG = 3
<|code_end|>
using the current file's imports:
import os as os
import cv... | class SteamPredefined(Predefined): |
Continue the code snippet: <|code_start|> CARDINFO = 2
LOG = 3
class SteamPredefined(Predefined):
files_need = [
os.path.join("steam", "auto_duel_on.png"),
os.path.join("steam", "auto_duel_off.png"),
os.path.join("steam", "new_duel_variant.png")
]
files_needed_for_comparisio... | save['version'] = nox_current_version |
Given the following code snippet before the placeholder: <|code_start|> 'auto_duel_on' : b
}
return save
def generate_duel_button_stats(self):
location = self.assets
new_duel_variant = os.path.join(location, "steam", "new_duel_variant.png")
im = cv2.imread(new_due... | return tupletodict(x + xrel, y + yrel, height, width) |
Using the snippet: <|code_start|>
# from bot.providers.predefined import Predefined
# from bot.providers.provider import Provider
class AbstractIgnoreEvent(object):
"""
Class implemented checks to avoid ui elements that should not be access
as well as doing the task required to avoid specified ui
"""
... | def event_condition(self, dl_info: DuelLinksInfo, img=None): |
Predict the next line for this snippet: <|code_start|> root = logging.getLogger("bot.modes.event_checker")
def __init__(self, provider):
self.provider = provider # type: Provider
@abstractmethod
def is_occurrence(self, img=None):
raise NotImplementedError("is_occurrence not implemented... | img = crop_image(img, **street_replay) |
Next line prediction: <|code_start|>
# from bot.providers.duellinks import DuelLinksInfo
# from bot.providers import Provider
class CheckPoints(Enum):
beforeStarting = 1
afterStarting = 2
beforeEnding = 3
afterEnding = 4
checkingBattle = 5
class AbstractBattle(object):
sort_value = -1
d... | signalers[cp] = Signal() |
Continue the code snippet: <|code_start|> self.provider.__check_battle_is_running__()
self.signalers[CheckPoints.afterStarting].emit(info)
self.provider.wait_for('OK')
self.signalers[CheckPoints.beforeEnding].emit(info)
if info:
info.status = "Battle Ended"
... | img = crop_image(img, **self.provider.predefined.duelist_name_area) |
Given snippet: <|code_start|> self.name_mode = 'NPC Battle'
def battle(self, info, check_battle: bool = False):
self.signalers[CheckPoints.beforeStarting].emit(info)
self.provider.root.info("Battling with {}".format(info.name))
if check_battle:
self.provider.wait_for_auto... | self.provider.scan_for_ok(LOW_CORR) |
Next line prediction: <|code_start|> self.signalers[CheckPoints.afterStarting].emit(info)
self.provider.wait_for('OK')
self.signalers[CheckPoints.beforeEnding].emit(info)
if info:
info.status = "Battle Ended"
self.log(info)
self.provider.wait_for_ui(.5)
... | name = self.provider.img_to_string(img, alpha_numeric).lower() |
Given the following code snippet before the placeholder: <|code_start|>
data_object = {
'next_run_at': None,
'last_run_at': None,
'runnow': False,
'stop': False
}
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import json
import h5py
import numpy as np
from ... | data_object = DotDict(data_object) |
Here is a snippet: <|code_start|>def logged(f):
def _inner(*args, **kwargs):
if not UserSession().isLogged():
raise BaseException('You are not authorized')
return f(*args, **kwargs)
return _inner
#decorator
def guest_only(f):
def _inner(*args, **kwargs):
if UserSession(... | Registry().set('request', self.request) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2010 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wik... | class TemplateNotFound(TemplateError): |
Continue the code snippet: <|code_start|> (the default), "lenient", or a custom lookup
class
:param allow_exec: whether to allow Python code blocks in templates
:param callback: (optional) a callback function that is invoked after a
... | self._cache = LRUCache(max_cache_size) |
Given the following code snippet before the placeholder: <|code_start|>
class AbstractSession(dict):
namespace = 'undefined'
def __init__(self):
if self.namespace == 'undefined':
raise AttributeError('namespace attribute is not defined in subclass')
<|code_end|>
, predict the next line u... | session = Registry().get('session') |
Using the snippet: <|code_start|> return cls()
if type(text) is cls:
return text
if hasattr(text, '__html__'):
return cls(text.__html__())
text = text.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>')
... | def stripentities(self, keepxmlentities=False): |
Given the following code snippet before the placeholder: <|code_start|> """Reverse-escapes &, <, >, and \" and returns a `unicode` object.
>>> Markup('1 < 2').unescape()
u'1 < 2'
:return: the unescaped string
:rtype: `unicode`
:see: `genshi.core.unesca... | def striptags(self): |
Given snippet: <|code_start|> return (self.uri,)
def __getstate__(self):
return self.uri
def __setstate__(self, uri):
self.uri = uri
def __init__(self, uri):
self.uri = unicode(uri)
def __contains__(self, qname):
return qname.namespace == self.uri
def __ne... | return '%s(%s)' % (type(self).__name__, stringrepr(self.uri)) |
Based on the snippet: <|code_start|>
class UserSession(AbstractSession):
namespace = 'user'
def isLogged(self):
if 'user_key' in self:
return True
else:
return False
def getUser(self):
if 'user_key' in self:
<|code_end|>
, predict the immediate next line wit... | user = User.get(self['user_key']) |
Next line prediction: <|code_start|>
def render_template(template_name, template_vals={}):
loader = TemplateLoader('theme/frontend')
template = loader.load(template_name)
template_vals['render']=render_template
<|code_end|>
. Use current file imports:
(import os
import genshi
from google.appengine.ext.w... | template_vals['Registry']=Registry |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.