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
##################################################################
# Test Classes
class TestXGBoostSenser(TestCase):
def test_init(self):
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from dsenser.xgboost import XGBoostSenser
and context (functions, classes, or occasionally code) from other files:
# Path: dsenser/xgboost/xgboost.py
# class XGBoostSenser(WangSenser):
# """Class for XGBoost classification of discourse relations.
#
# Attributes:
# explicit (:class:`dsenser.xgboost.explicit.XGBoostExplicitSenser`):
# classifier for explicit discourse relations
# implicit (:class:`dsenser.xgboost.implicit.XGBoostImplicitSenser`):
# classifier for implicit discourse relations
# n_y (int): number of distinct classes
#
# """
#
# def __init__(self, **kwargs):
# """Class constructor.
#
# Args:
# kwargs (dict): keyword arguments to be forwarded
#
# """
# self.explicit = XGBoostExplicitSenser(**kwargs)
# self.implicit = XGBoostImplicitSenser(**kwargs)
. Output only the next line. | 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(bolt_mkdir)
self.registry.register_module_tasks(bolt_nose)
self.registry.register_module_tasks(bolt_pip)
self.registry.register_module_tasks(bolt_set_vars)
self.registry.register_module_tasks(bolt_setup)
self.registry.register_module_tasks(bolt_shell)
self.registry.register_module_tasks(bolt_sleep)
def _register_module(self, module):
module.register_tasks(self.registry)
class BoltFile(object):
"""
"""
def __init__(self, bolt_file_name):
self.filename = os.path.abspath(bolt_file_name)
self._bolt_file_module = self._load()
def _load(self):
<|code_end|>
with the help of current file imports:
import os.path
import bolt._btconfig as btconfig
import bolt._btoptions as btoptions
import bolt._btregistry as btregistry
import bolt._btrunner as btrunner
import bolt.tasks.bolt_conttest as bolt_conttest
import bolt.tasks.bolt_coverage as bolt_coverage
import bolt.tasks.bolt_delete_files as bolt_delete_files
import bolt.tasks.bolt_mkdir as bolt_mkdir
import bolt.tasks.bolt_nose as bolt_nose
import bolt.tasks.bolt_pip as bolt_pip
import bolt.tasks.bolt_set_vars as bolt_set_vars
import bolt.tasks.bolt_setup as bolt_setup
import bolt.tasks.bolt_shell as bolt_shell
import bolt.tasks.bolt_sleep as bolt_sleep
from bolt._btutils import load_script
and context from other files:
# Path: bolt/_btutils.py
# def load_script(filename):
# """
# Loads a python script as a module.
#
# This function is provided to allow applications to load a Python module by its file name.
#
# :param string filename:
# Name of the python file to be loaded as a module.
#
# :return:
# A |Python|_ module loaded from the specified file.
# """
# path, module_name, ext = _extract_script_components(filename)
# add_search_path(path)
# return _load_module(module_name)
, which may contain function names, class names, or code. Output only the next line. | 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|>
, predict the next line using imports from the current file:
from bolt.api import BoltError
and context including class names, function names, and sometimes code from other files:
# Path: bolt/api.py
# class BoltError(Exception):
# """
# Base class for all exceptions in Bolt. The class is provided for inheritance
# and it should not be used by itself.
#
# Errors for the Bolt application itself should be derived from this class.
# """
# def __init__(self, code=1):
# self.code = code
#
#
# def __repr__(self):
# return 'BoltError({code})'.format(code=self.code)
#
#
# def __str__(self):
# return repr(self)
. Output only the next line. | 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 ..UserSource import UserSource
from ..User import User
from .DatabaseUser import DatabaseUser
from typing import List
and context (functions, classes, or occasionally code) from other files:
# Path: src/booking/source/user/UserSource.py
# class UserSource(ABC):
# """
# Class that represents a source used to store and get the user that use the bot.
# """
#
# @abstractmethod
# def get_user_by_identifier(self, identifier: int) -> User:
# """
# Gets the user that have the identifier equal to the provided identifier.
# :param identifier: Identifier used to get the user.
# :return: Return the user that have the requested identifier, if the user is not present will return None.
# """
# pass
#
# def get_all_users(self) -> List[User]:
# """
# Gets all the users.
# :return: Return a list of all the users.
# """
# pass
#
# def add_user(self, user: User):
# """
# Adds a user.
# :param user: User that will be added.
# :return:
# """
# pass
#
# Path: src/booking/source/user/User.py
# class User:
#
# class Role(Enum):
# USER = 0
# ADMIN = 1
#
# def __new__(cls, value):
# member = object.__new__(cls)
# member._value = value
# return member
#
# def __int__(self):
# return self._value
#
# def __init__(self, username: str, name: str, surname: str, identifier: int, role: Role = Role.USER):
# self._username = escape_none(username)
# self._name = escape_none(name)
# self._surname = escape_none(surname)
# self._identifier = identifier
# self._role = role
#
# def get_username(self) -> str:
# return self._username
#
# def get_name(self) -> str:
# return self._name
#
# def get_surname(self) -> str:
# return self._surname
#
# def get_identifier(self) -> int:
# return self._identifier
#
# def get_role(self) -> Role:
# return self._role
#
# def set_role(self, role: Role):
# self._role = role
#
# Path: src/booking/source/user/database/DatabaseUser.py
# class DatabaseUser(BaseModel):
# class Meta:
# db_table = 'user'
#
# """
# Database representation of a User
# """
# username = CharField(64, default='')
# name = CharField(64, default='')
# surname = CharField(64, default='')
# identifier = IntegerField()
# role = IntegerField()
. Output only the next line. | 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 DatabaseUser
from typing import List
and context (class names, function names, or code) available:
# Path: src/booking/source/user/UserSource.py
# class UserSource(ABC):
# """
# Class that represents a source used to store and get the user that use the bot.
# """
#
# @abstractmethod
# def get_user_by_identifier(self, identifier: int) -> User:
# """
# Gets the user that have the identifier equal to the provided identifier.
# :param identifier: Identifier used to get the user.
# :return: Return the user that have the requested identifier, if the user is not present will return None.
# """
# pass
#
# def get_all_users(self) -> List[User]:
# """
# Gets all the users.
# :return: Return a list of all the users.
# """
# pass
#
# def add_user(self, user: User):
# """
# Adds a user.
# :param user: User that will be added.
# :return:
# """
# pass
#
# Path: src/booking/source/user/User.py
# class User:
#
# class Role(Enum):
# USER = 0
# ADMIN = 1
#
# def __new__(cls, value):
# member = object.__new__(cls)
# member._value = value
# return member
#
# def __int__(self):
# return self._value
#
# def __init__(self, username: str, name: str, surname: str, identifier: int, role: Role = Role.USER):
# self._username = escape_none(username)
# self._name = escape_none(name)
# self._surname = escape_none(surname)
# self._identifier = identifier
# self._role = role
#
# def get_username(self) -> str:
# return self._username
#
# def get_name(self) -> str:
# return self._name
#
# def get_surname(self) -> str:
# return self._surname
#
# def get_identifier(self) -> int:
# return self._identifier
#
# def get_role(self) -> Role:
# return self._role
#
# def set_role(self, role: Role):
# self._role = role
#
# Path: src/booking/source/user/database/DatabaseUser.py
# class DatabaseUser(BaseModel):
# class Meta:
# db_table = 'user'
#
# """
# Database representation of a User
# """
# username = CharField(64, default='')
# name = CharField(64, default='')
# surname = CharField(64, default='')
# identifier = IntegerField()
# role = IntegerField()
. Output only the next line. | 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 import abstractmethod, ABC
from typing import List
from .model import Classroom, Building
and context including class names, function names, and sometimes code from other files:
# Path: src/booking/source/classroom/model/Classroom.py
# class Classroom:
# """
# Class that represents a single classroom.
# """
#
# def __init__(self, identifier: str, name: str, building: Building, floor: str):
# self._identifier = identifier
# self._name = name
# self._building = building
# self._floor = floor
#
# def get_identifier(self) -> str:
# return self._identifier
#
# def get_name(self) -> str:
# return self._name
#
# def get_building(self) -> Building:
# return self._building
#
# def get_floor(self) -> str:
# return self._floor
#
# Path: src/booking/source/classroom/model/Building.py
# class Building:
#
# """
# Class that represents a building.
# """
#
# def __init__(self, identifier: str, name: str):
# self._identifier = identifier
# self._name = name
#
# def get_identifier(self):
# return self._identifier
#
# def get_name(self) -> str:
# return self._name
. Output only the next line. | 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 inside the source.
:param identifier: Name of the class that will be checked.
:return: Returns True if the classroom is present False otherwise.
"""
return self.get_classroom(identifier) is not None
@abstractmethod
def add_classroom(self, classroom: Classroom):
"""
Adds a classroom to the source.
:param classroom: Classroom that will be added.
"""
pass
@abstractmethod
def get_all_classrooms(self) -> List[Classroom]:
"""
Gets all the classroom inside the source.
:return: Returns a List of all the classrooms inside the source.
"""
pass
@abstractmethod
<|code_end|>
, predict the next line using imports from the current file:
from abc import abstractmethod, ABC
from typing import List
from .model import Classroom, Building
and context including class names, function names, and sometimes code from other files:
# Path: src/booking/source/classroom/model/Classroom.py
# class Classroom:
# """
# Class that represents a single classroom.
# """
#
# def __init__(self, identifier: str, name: str, building: Building, floor: str):
# self._identifier = identifier
# self._name = name
# self._building = building
# self._floor = floor
#
# def get_identifier(self) -> str:
# return self._identifier
#
# def get_name(self) -> str:
# return self._name
#
# def get_building(self) -> Building:
# return self._building
#
# def get_floor(self) -> str:
# return self._floor
#
# Path: src/booking/source/classroom/model/Building.py
# class Building:
#
# """
# Class that represents a building.
# """
#
# def __init__(self, identifier: str, name: str):
# self._identifier = identifier
# self._name = name
#
# def get_identifier(self):
# return self._identifier
#
# def get_name(self) -> str:
# return self._name
. Output only the next line. | 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 import List
from booking.source.event import EventsSource
from ..model import Event, EventImpl
from .model import DatabaseEvent
from booking.utils.database import get_db)
and context including class names, function names, or small code snippets from other files:
# Path: src/booking/source/event/model/Event.py
# class Event(metaclass=ABCMeta):
#
# """
# Interface that represents a generic event
# """
#
# @abstractmethod
# def get_classroom_identifier(self) -> str:
# """Returns the classroom identifier where will be the event."""
# pass
#
# @abstractmethod
# def get_name(self) -> str:
# """
# Returns the name of the event
# :rtype: str representing the name of the event
# """
# pass
#
# @abstractmethod
# def get_description(self) -> str:
# """Return a short description of the event"""
# pass
#
# @abstractmethod
# def get_begin(self) -> datetime:
# """Returns the date time representing when the event start"""
# pass
#
# @abstractmethod
# def get_end(self) -> datetime:
# """Returns the date time representing when is the event end"""
# pass
#
# def __str__(self):
# return self.get_name() + "\n" + \
# self.get_classroom_identifier() + "\n" + \
# str(self.get_begin()) + "\n" + \
# str(self.get_end()) + "\n" + \
# self.get_description()
#
# Path: src/booking/source/event/model/EventImpl.py
# class EventImpl(Event):
#
# """
# Class that implements the Event interface.
# """
#
# def __init__(self, name: str, description: str, classroom_identifier: str, begin_at: datetime, end_at: datetime):
# self._name = name
# self._description = description
# self._classroom_identifier = classroom_identifier
# self._beginAt = begin_at
# self._endAt = end_at
#
# def get_description(self) -> str:
# return self._description
#
# def get_name(self) -> str:
# return self._name
#
# def get_classroom_identifier(self) -> str:
# return self._classroom_identifier
#
# def get_begin(self) -> datetime:
# return self._beginAt
#
# def get_end(self) -> datetime:
# return self._endAt
#
# Path: src/booking/source/event/database/model/DatabaseEvent.py
# class DatabaseEvent(BaseModel):
# class Meta:
# db_table = 'event'
#
# """
# Mysql representation of a Event
# """
# name = CharField(256)
# start = DateTimeField()
# end = DateTimeField()
# desc = CharField(256)
# classroom_identifier = CharField(32)
. Output only the next line. | 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()
.where(DatabaseEvent.classroom_identifier == classroom_identifier))
def get_today_classroom_events(self, classroom_identifier: str) -> List[Event]:
start = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
end = datetime.today().replace(hour=23, minute=59, second=59, microsecond=0)
return query_result_to_events(DatabaseEvent.select()
.where(DatabaseEvent.classroom_identifier == classroom_identifier,
DatabaseEvent.start >= start, DatabaseEvent.end <= end))
def delete_old_events(self):
old_time_value = datetime.now().replace(hour=23, minute=59, second=59, microsecond=0) - timedelta(days=1)
DatabaseEvent.delete() \
.where(DatabaseEvent.start <= old_time_value) \
.execute()
def delete_all_events(self):
DatabaseEvent.delete().execute()
def is_classroom_free(self, classroom_identifier: str, date_time: datetime) -> bool:
return self.get_current_event(classroom_identifier, date_time) is None
def query_result_to_event(event: DatabaseEvent) -> Event:
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from datetime import timedelta
from typing import List
from booking.source.event import EventsSource
from ..model import Event, EventImpl
from .model import DatabaseEvent
from booking.utils.database import get_db
and context from other files:
# Path: src/booking/source/event/model/Event.py
# class Event(metaclass=ABCMeta):
#
# """
# Interface that represents a generic event
# """
#
# @abstractmethod
# def get_classroom_identifier(self) -> str:
# """Returns the classroom identifier where will be the event."""
# pass
#
# @abstractmethod
# def get_name(self) -> str:
# """
# Returns the name of the event
# :rtype: str representing the name of the event
# """
# pass
#
# @abstractmethod
# def get_description(self) -> str:
# """Return a short description of the event"""
# pass
#
# @abstractmethod
# def get_begin(self) -> datetime:
# """Returns the date time representing when the event start"""
# pass
#
# @abstractmethod
# def get_end(self) -> datetime:
# """Returns the date time representing when is the event end"""
# pass
#
# def __str__(self):
# return self.get_name() + "\n" + \
# self.get_classroom_identifier() + "\n" + \
# str(self.get_begin()) + "\n" + \
# str(self.get_end()) + "\n" + \
# self.get_description()
#
# Path: src/booking/source/event/model/EventImpl.py
# class EventImpl(Event):
#
# """
# Class that implements the Event interface.
# """
#
# def __init__(self, name: str, description: str, classroom_identifier: str, begin_at: datetime, end_at: datetime):
# self._name = name
# self._description = description
# self._classroom_identifier = classroom_identifier
# self._beginAt = begin_at
# self._endAt = end_at
#
# def get_description(self) -> str:
# return self._description
#
# def get_name(self) -> str:
# return self._name
#
# def get_classroom_identifier(self) -> str:
# return self._classroom_identifier
#
# def get_begin(self) -> datetime:
# return self._beginAt
#
# def get_end(self) -> datetime:
# return self._endAt
#
# Path: src/booking/source/event/database/model/DatabaseEvent.py
# class DatabaseEvent(BaseModel):
# class Meta:
# db_table = 'event'
#
# """
# Mysql representation of a Event
# """
# name = CharField(256)
# start = DateTimeField()
# end = DateTimeField()
# desc = CharField(256)
# classroom_identifier = CharField(32)
, which may include functions, classes, or code. Output only the next line. | 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 import EventsSource
from ..model import Event, EventImpl
from .model import DatabaseEvent
from booking.utils.database import get_db
and context:
# Path: src/booking/source/event/model/Event.py
# class Event(metaclass=ABCMeta):
#
# """
# Interface that represents a generic event
# """
#
# @abstractmethod
# def get_classroom_identifier(self) -> str:
# """Returns the classroom identifier where will be the event."""
# pass
#
# @abstractmethod
# def get_name(self) -> str:
# """
# Returns the name of the event
# :rtype: str representing the name of the event
# """
# pass
#
# @abstractmethod
# def get_description(self) -> str:
# """Return a short description of the event"""
# pass
#
# @abstractmethod
# def get_begin(self) -> datetime:
# """Returns the date time representing when the event start"""
# pass
#
# @abstractmethod
# def get_end(self) -> datetime:
# """Returns the date time representing when is the event end"""
# pass
#
# def __str__(self):
# return self.get_name() + "\n" + \
# self.get_classroom_identifier() + "\n" + \
# str(self.get_begin()) + "\n" + \
# str(self.get_end()) + "\n" + \
# self.get_description()
#
# Path: src/booking/source/event/model/EventImpl.py
# class EventImpl(Event):
#
# """
# Class that implements the Event interface.
# """
#
# def __init__(self, name: str, description: str, classroom_identifier: str, begin_at: datetime, end_at: datetime):
# self._name = name
# self._description = description
# self._classroom_identifier = classroom_identifier
# self._beginAt = begin_at
# self._endAt = end_at
#
# def get_description(self) -> str:
# return self._description
#
# def get_name(self) -> str:
# return self._name
#
# def get_classroom_identifier(self) -> str:
# return self._classroom_identifier
#
# def get_begin(self) -> datetime:
# return self._beginAt
#
# def get_end(self) -> datetime:
# return self._endAt
#
# Path: src/booking/source/event/database/model/DatabaseEvent.py
# class DatabaseEvent(BaseModel):
# class Meta:
# db_table = 'event'
#
# """
# Mysql representation of a Event
# """
# name = CharField(256)
# start = DateTimeField()
# end = DateTimeField()
# desc = CharField(256)
# classroom_identifier = CharField(32)
which might include code, classes, or functions. Output only the next line. | 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 abc import ABCMeta, abstractmethod
from datetime import datetime
from typing import List
from .model import Event
and context including class names, function names, and sometimes code from other files:
# Path: src/booking/source/event/model/Event.py
# class Event(metaclass=ABCMeta):
#
# """
# Interface that represents a generic event
# """
#
# @abstractmethod
# def get_classroom_identifier(self) -> str:
# """Returns the classroom identifier where will be the event."""
# pass
#
# @abstractmethod
# def get_name(self) -> str:
# """
# Returns the name of the event
# :rtype: str representing the name of the event
# """
# pass
#
# @abstractmethod
# def get_description(self) -> str:
# """Return a short description of the event"""
# pass
#
# @abstractmethod
# def get_begin(self) -> datetime:
# """Returns the date time representing when the event start"""
# pass
#
# @abstractmethod
# def get_end(self) -> datetime:
# """Returns the date time representing when is the event end"""
# pass
#
# def __str__(self):
# return self.get_name() + "\n" + \
# self.get_classroom_identifier() + "\n" + \
# str(self.get_begin()) + "\n" + \
# str(self.get_end()) + "\n" + \
# self.get_description()
. Output only the next line. | 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 DatabaseBuild)
and context including class names, function names, or small code snippets from other files:
# Path: src/booking/source/classroom/database/model/DatabaseBuild.py
# class DatabaseBuild(BaseModel):
# class Meta:
# db_table = 'building'
# """
# Mysql representation of a build.
# """
# identifier = CharField()
# name = CharField()
. Output only the next line. | 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 import abstractmethod
from .User import User
from typing import List
and context including class names, function names, and sometimes code from other files:
# Path: src/booking/source/user/User.py
# class User:
#
# class Role(Enum):
# USER = 0
# ADMIN = 1
#
# def __new__(cls, value):
# member = object.__new__(cls)
# member._value = value
# return member
#
# def __int__(self):
# return self._value
#
# def __init__(self, username: str, name: str, surname: str, identifier: int, role: Role = Role.USER):
# self._username = escape_none(username)
# self._name = escape_none(name)
# self._surname = escape_none(surname)
# self._identifier = identifier
# self._role = role
#
# def get_username(self) -> str:
# return self._username
#
# def get_name(self) -> str:
# return self._name
#
# def get_surname(self) -> str:
# return self._surname
#
# def get_identifier(self) -> int:
# return self._identifier
#
# def get_role(self) -> Role:
# return self._role
#
# def set_role(self, role: Role):
# self._role = role
. Output only the next line. | 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 files:
# Path: src/booking/utils/database/DatabaseProvider.py
# def get_db() -> Database:
# database = DB_INJECTOR.get(Database)
# if database.is_closed():
# database.connect()
# return database
. Output only the next line. | 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.
"""
self._url = url
@abc.abstractclassmethod
def get_events(self, request_date: datetime = datetime.now()) -> List[SpiderEvent]:
"""
Gets the events scheduled in the provided date.
@:param request_date: The date of interest.
:return: Returns a List[SpiderEvent] that contains the events obtained from the spider.
"""
pass
@abc.abstractclassmethod
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import abc
import requests
from abc import ABCMeta
from typing import List
from lxml import html
from .BuildingsProvider import BuildingsProvider
from datetime import datetime
from booking.spider.SpiderEvent import SpiderEvent
and context:
# Path: src/booking/spider/BuildingsProvider.py
# class BuildingsProvider:
#
# """
# Class that expose the classrooms and buildings handled from a spider.
# """
#
# class Building:
#
# """
# Class that represents a building.
# """
#
# def __init__(self, identifier: str, name: str):
# self.identifier = identifier
# self.name = name
#
# def get_name(self) -> str:
# return self.name
#
# def get_identifier(self) -> str:
# return self.identifier
#
# class Classroom:
#
# """
# Class that represents a classroom.
# """
#
# def __init__(self, building, name: str, floor: int):
# self.building = building
# self.name = name
# self.floor = floor
# self.identifier = building.get_identifier() + "_" + name.lower()
#
# def get_building(self):
# return self.building
#
# def get_name(self) -> str:
# return self.name
#
# def get_floor(self) -> int:
# return self.floor
#
# def get_identifier(self) -> str:
# return self.identifier
#
# class Builder:
#
# """
# Builder class to create instances of BuildingsProvider.
# """
#
# def __init__(self):
# self.building_provider = BuildingsProvider()
#
# def add_building(self, identifier: str, name: str):
# """
# Adds a building
# :param identifier: Unique key that identify a building, this can be equal to the key of a building
# handled from an another spider in case this spider provides events associated to that building.
# :param name: Name of the building.
# :return: Returns self in order to provide a fluent api.
# """
# self.building_provider._buildings.append(BuildingsProvider.Building(identifier, name))
# return self
#
# def add_classroom(self, name: str, floor: int):
# """
# Adds a classroom to the last created building
# :param name: Name of the classroom.
# :param floor: Floor of the classroom.
# :return: Returns self in order to provide a fluent api.
# """
# current_building = self.building_provider._buildings[-1]
# classroom = BuildingsProvider.Classroom(current_building, name, floor)
# self.building_provider._classrooms.append(classroom)
# return self
#
# def build(self):
# """
# Creates the BuildingsProvider instance.
# :return: Returns the initialized BuildingsProvider instance.
# """
# return self.building_provider
#
# def __init__(self):
# self._buildings = []
# self._classrooms = []
#
# def get_classrooms(self):
# """
# Gets all the classrooms.
# :return: Return a list of Classroom.
# """
# return self._classrooms
#
# def get_buildings(self):
# """
# Gets all the building
# :return: Return a list of Building.
# """
# return self._buildings
which might include code, classes, or functions. Output only the next line. | 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.abstract,
"end_date": slot.day.strftime("%d.%m."),
"end_time": endtime.strftime("%H:%M"),
"id": str(slot.pk),
"speaker": slot.author,
"start_date": slot.day.strftime("%d.%m."),
"start_time": slot.start.strftime("%H:%M"),
"title": slot.title,
"twitter": twitter,
"type": cls.get_slot_type(slot),
"votes": ["", ]
}
def serialize(self):
data = [self.to_pycon_app(slot) for slot in self.queryset]
return {"Odeon": data}
class Command(BaseCommand):
def handle(self, *args, **options):
<|code_end|>
, generate the next line using the imports in this file:
import requests
from django.core.management.base import BaseCommand
from conference.schedule.models import Slot
and context (functions, classes, or occasionally code) from other files:
# Path: conference/schedule/models.py
# 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.ForeignKey(
# Submission, related_name='talks', limit_choices_to={'selected': True}, null=True, blank=True
# )
# slug = AutoSlugField(
# _('Slug'), max_length=400, blank=True, populate_from='generated_slug', always_update=True
# )
# workshop = models.ForeignKey(
# WorkshopSubmission, related_name='workshops', limit_choices_to={'selected': True}, null=True, blank=True
# )
# name = models.CharField(
# _('Name'), max_length=250, null=True, blank=True,
# help_text=_('Field for time slots that does not relate to a Talk or a Workshop.')
# )
# mugshot = FilerImageField(verbose_name=_('Speaker mughshot'), null=True, blank=True)
# twitter = models.CharField(_('Twitter'), max_length=200, default='', blank=True)
# schedule_abstract = models.TextField(_('Schedule abstract'), blank=True, null=True)
# day = models.DateField(_('Date'))
# start = models.TimeField(_('Start'))
# duration = models.DurationField(_('Duration'))
# sprint_days = models.BooleanField(_('Part of sprint days'), default=False)
# show_end_time = models.BooleanField(_('Show end time in schedule'), default=False)
# slides = models.URLField(_('Speaker slides'), blank=True, null=True)
# video = models.URLField(_('Talk video'), blank=True, null=True)
#
# _metadata = {
# 'title': 'title',
# 'description': 'get_meta_abstract',
# 'image': 'get_image',
# }
#
# class Meta:
# verbose_name = _('Time slot')
# verbose_name_plural = _('Time slots')
# ordering = ('day', 'start')
#
# def clean(self):
# # ensure talk and workshop are NOT filled at the same time
# if self.talk and self.workshop:
# message = _('Please, select either a Talk or a Workshop, not both.')
# raise ValidationError({
# 'talk': ValidationError(message=message, code='invalid'),
# 'workshop': ValidationError(message=message, code='invalid'),
# })
#
# def get_image(self):
# if self.mugshot:
# return self.mugshot.url
# else:
# return None
#
# def get_meta_abstract(self):
# return truncatechars_html(self.abstract, 180)
#
# @property
# def title(self):
# if self.talk_id:
# return self.talk.proposal_title
# elif self.workshop_id:
# return self.workshop.proposal_title
# elif self.name:
# return self.name
# return ''
#
# @property
# def author(self):
# if self.talk:
# return self.talk.author
# elif self.workshop:
# return self.workshop.author
# return ''
#
# @property
# def generated_slug(self):
# return slugify(self.title)
#
# @property
# def twitter_split(self):
# if self.twitter:
# return self.twitter.split(',')
# return ''
#
# @property
# def abstract(self):
# if self.schedule_abstract:
# return self.schedule_abstract
# if self.talk:
# return self.talk.proposal_abstract
# elif self.workshop:
# return self.workshop.proposal_abstract
# return ''
#
# @property
# def bio(self):
# if self.is_talk() and self.talk.author_bio and len(self.talk.author_bio) > 3:
# return self.talk.author_bio
# if self.is_workshop() and self.workshop.author_bio and len(self.workshop.author_bio) > 3:
# return self.workshop.author_bio
# return ''
#
# @property
# def parsed_duration(self):
# minutes = self.duration.seconds//60
# hours = minutes//60
# if hours:
# minutes -= hours * 60
# if minutes:
# return '{}h {}min'.format(hours, minutes)
# return '{}h'.format(hours)
# return '{}min'.format(minutes)
#
# @property
# def end_time(self):
# combined = dt.datetime.combine(dt.date.today(), self.start)
# end_time = combined + self.duration
# return end_time.time()
#
# @property
# def height(self):
# return self.duration.total_seconds() / 100 * 6
#
# @property
# def thumbnail_option(self):
# return ThumbnailOption.objects.get(name__icontains='speaker').as_dict
#
# def is_talk(self):
# return True if self.talk else False
# is_talk.short_description = _('Talk')
# is_talk.boolean = True
#
# def is_workshop(self):
# return True if self.workshop else False
# is_workshop.short_description = _('Workshop')
# is_workshop.boolean = True
#
# def is_custom(self):
# return True if self.name else False
# is_custom.short_description = _('Custom')
# is_custom.boolean = True
. Output only the next line. | 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.ForeignKey(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime as dt
from autoslug import AutoSlugField
from autoslug.utils import slugify
from django.core.exceptions import ValidationError
from django.db import models
from django.template.defaultfilters import truncatechars_html
from django.utils.translation import gettext_lazy as _
from filer.fields.image import FilerImageField
from filer.models import ThumbnailOption
from meta.models import ModelMeta
from conference.cfp.models import Submission, WorkshopSubmission
and context:
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
which might include code, classes, or functions. Output only the next line. | 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 = models.ForeignKey(
Submission, related_name='talks', limit_choices_to={'selected': True}, null=True, blank=True
)
slug = AutoSlugField(
_('Slug'), max_length=400, blank=True, populate_from='generated_slug', always_update=True
)
workshop = models.ForeignKey(
<|code_end|>
. Use current file imports:
(import datetime as dt
from autoslug import AutoSlugField
from autoslug.utils import slugify
from django.core.exceptions import ValidationError
from django.db import models
from django.template.defaultfilters import truncatechars_html
from django.utils.translation import gettext_lazy as _
from filer.fields.image import FilerImageField
from filer.models import ThumbnailOption
from meta.models import ModelMeta
from conference.cfp.models import Submission, WorkshopSubmission)
and context including class names, function names, or small code snippets from other files:
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
. Output only the next line. | 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.schedule.models import Slot)
and context including class names, function names, or small code snippets from other files:
# Path: conference/schedule/models.py
# 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.ForeignKey(
# Submission, related_name='talks', limit_choices_to={'selected': True}, null=True, blank=True
# )
# slug = AutoSlugField(
# _('Slug'), max_length=400, blank=True, populate_from='generated_slug', always_update=True
# )
# workshop = models.ForeignKey(
# WorkshopSubmission, related_name='workshops', limit_choices_to={'selected': True}, null=True, blank=True
# )
# name = models.CharField(
# _('Name'), max_length=250, null=True, blank=True,
# help_text=_('Field for time slots that does not relate to a Talk or a Workshop.')
# )
# mugshot = FilerImageField(verbose_name=_('Speaker mughshot'), null=True, blank=True)
# twitter = models.CharField(_('Twitter'), max_length=200, default='', blank=True)
# schedule_abstract = models.TextField(_('Schedule abstract'), blank=True, null=True)
# day = models.DateField(_('Date'))
# start = models.TimeField(_('Start'))
# duration = models.DurationField(_('Duration'))
# sprint_days = models.BooleanField(_('Part of sprint days'), default=False)
# show_end_time = models.BooleanField(_('Show end time in schedule'), default=False)
# slides = models.URLField(_('Speaker slides'), blank=True, null=True)
# video = models.URLField(_('Talk video'), blank=True, null=True)
#
# _metadata = {
# 'title': 'title',
# 'description': 'get_meta_abstract',
# 'image': 'get_image',
# }
#
# class Meta:
# verbose_name = _('Time slot')
# verbose_name_plural = _('Time slots')
# ordering = ('day', 'start')
#
# def clean(self):
# # ensure talk and workshop are NOT filled at the same time
# if self.talk and self.workshop:
# message = _('Please, select either a Talk or a Workshop, not both.')
# raise ValidationError({
# 'talk': ValidationError(message=message, code='invalid'),
# 'workshop': ValidationError(message=message, code='invalid'),
# })
#
# def get_image(self):
# if self.mugshot:
# return self.mugshot.url
# else:
# return None
#
# def get_meta_abstract(self):
# return truncatechars_html(self.abstract, 180)
#
# @property
# def title(self):
# if self.talk_id:
# return self.talk.proposal_title
# elif self.workshop_id:
# return self.workshop.proposal_title
# elif self.name:
# return self.name
# return ''
#
# @property
# def author(self):
# if self.talk:
# return self.talk.author
# elif self.workshop:
# return self.workshop.author
# return ''
#
# @property
# def generated_slug(self):
# return slugify(self.title)
#
# @property
# def twitter_split(self):
# if self.twitter:
# return self.twitter.split(',')
# return ''
#
# @property
# def abstract(self):
# if self.schedule_abstract:
# return self.schedule_abstract
# if self.talk:
# return self.talk.proposal_abstract
# elif self.workshop:
# return self.workshop.proposal_abstract
# return ''
#
# @property
# def bio(self):
# if self.is_talk() and self.talk.author_bio and len(self.talk.author_bio) > 3:
# return self.talk.author_bio
# if self.is_workshop() and self.workshop.author_bio and len(self.workshop.author_bio) > 3:
# return self.workshop.author_bio
# return ''
#
# @property
# def parsed_duration(self):
# minutes = self.duration.seconds//60
# hours = minutes//60
# if hours:
# minutes -= hours * 60
# if minutes:
# return '{}h {}min'.format(hours, minutes)
# return '{}h'.format(hours)
# return '{}min'.format(minutes)
#
# @property
# def end_time(self):
# combined = dt.datetime.combine(dt.date.today(), self.start)
# end_time = combined + self.duration
# return end_time.time()
#
# @property
# def height(self):
# return self.duration.total_seconds() / 100 * 6
#
# @property
# def thumbnail_option(self):
# return ThumbnailOption.objects.get(name__icontains='speaker').as_dict
#
# def is_talk(self):
# return True if self.talk else False
# is_talk.short_description = _('Talk')
# is_talk.boolean = True
#
# def is_workshop(self):
# return True if self.workshop else False
# is_workshop.short_description = _('Workshop')
# is_workshop.boolean = True
#
# def is_custom(self):
# return True if self.name else False
# is_custom.short_description = _('Custom')
# is_custom.boolean = True
. Output only the next line. | 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 import_export.admin import ExportActionModelAdmin
from .models import Slot
and context (classes, functions, or code) from other files:
# Path: conference/schedule/models.py
# 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.ForeignKey(
# Submission, related_name='talks', limit_choices_to={'selected': True}, null=True, blank=True
# )
# slug = AutoSlugField(
# _('Slug'), max_length=400, blank=True, populate_from='generated_slug', always_update=True
# )
# workshop = models.ForeignKey(
# WorkshopSubmission, related_name='workshops', limit_choices_to={'selected': True}, null=True, blank=True
# )
# name = models.CharField(
# _('Name'), max_length=250, null=True, blank=True,
# help_text=_('Field for time slots that does not relate to a Talk or a Workshop.')
# )
# mugshot = FilerImageField(verbose_name=_('Speaker mughshot'), null=True, blank=True)
# twitter = models.CharField(_('Twitter'), max_length=200, default='', blank=True)
# schedule_abstract = models.TextField(_('Schedule abstract'), blank=True, null=True)
# day = models.DateField(_('Date'))
# start = models.TimeField(_('Start'))
# duration = models.DurationField(_('Duration'))
# sprint_days = models.BooleanField(_('Part of sprint days'), default=False)
# show_end_time = models.BooleanField(_('Show end time in schedule'), default=False)
# slides = models.URLField(_('Speaker slides'), blank=True, null=True)
# video = models.URLField(_('Talk video'), blank=True, null=True)
#
# _metadata = {
# 'title': 'title',
# 'description': 'get_meta_abstract',
# 'image': 'get_image',
# }
#
# class Meta:
# verbose_name = _('Time slot')
# verbose_name_plural = _('Time slots')
# ordering = ('day', 'start')
#
# def clean(self):
# # ensure talk and workshop are NOT filled at the same time
# if self.talk and self.workshop:
# message = _('Please, select either a Talk or a Workshop, not both.')
# raise ValidationError({
# 'talk': ValidationError(message=message, code='invalid'),
# 'workshop': ValidationError(message=message, code='invalid'),
# })
#
# def get_image(self):
# if self.mugshot:
# return self.mugshot.url
# else:
# return None
#
# def get_meta_abstract(self):
# return truncatechars_html(self.abstract, 180)
#
# @property
# def title(self):
# if self.talk_id:
# return self.talk.proposal_title
# elif self.workshop_id:
# return self.workshop.proposal_title
# elif self.name:
# return self.name
# return ''
#
# @property
# def author(self):
# if self.talk:
# return self.talk.author
# elif self.workshop:
# return self.workshop.author
# return ''
#
# @property
# def generated_slug(self):
# return slugify(self.title)
#
# @property
# def twitter_split(self):
# if self.twitter:
# return self.twitter.split(',')
# return ''
#
# @property
# def abstract(self):
# if self.schedule_abstract:
# return self.schedule_abstract
# if self.talk:
# return self.talk.proposal_abstract
# elif self.workshop:
# return self.workshop.proposal_abstract
# return ''
#
# @property
# def bio(self):
# if self.is_talk() and self.talk.author_bio and len(self.talk.author_bio) > 3:
# return self.talk.author_bio
# if self.is_workshop() and self.workshop.author_bio and len(self.workshop.author_bio) > 3:
# return self.workshop.author_bio
# return ''
#
# @property
# def parsed_duration(self):
# minutes = self.duration.seconds//60
# hours = minutes//60
# if hours:
# minutes -= hours * 60
# if minutes:
# return '{}h {}min'.format(hours, minutes)
# return '{}h'.format(hours)
# return '{}min'.format(minutes)
#
# @property
# def end_time(self):
# combined = dt.datetime.combine(dt.date.today(), self.start)
# end_time = combined + self.duration
# return end_time.time()
#
# @property
# def height(self):
# return self.duration.total_seconds() / 100 * 6
#
# @property
# def thumbnail_option(self):
# return ThumbnailOption.objects.get(name__icontains='speaker').as_dict
#
# def is_talk(self):
# return True if self.talk else False
# is_talk.short_description = _('Talk')
# is_talk.boolean = True
#
# def is_workshop(self):
# return True if self.workshop else False
# is_workshop.short_description = _('Workshop')
# is_workshop.boolean = True
#
# def is_custom(self):
# return True if self.name else False
# is_custom.short_description = _('Custom')
# is_custom.boolean = True
. Output only the next line. | 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 import Submission
from .views import SubmissionView)
and context including class names, function names, or small code snippets from other files:
# Path: conference/cfp/forms.py
# class TalkSubmissionForm(forms.ModelForm):
#
# 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'
# )
#
# def __init__(self, *args, **kwargs):
# super(TalkSubmissionForm, self).__init__(*args, **kwargs)
# self.fields['author'].label = _('Your name')
# self.fields['email'].label = _('Your email')
# self.fields['author_bio'].label = _('Tell us about yourself')
# self.fields['proposal_title'].label = _('Your proposal\'s title')
# self.fields['proposal_abstract'].label = _('Abstract of your proposal')
# self.fields['proposal_why'].label = _('What the audience will get from your proposal?')
# self.fields['proposal_requirements'].label = _(
# 'Do you have any special requirement for your talk?'
# )
# self.fields['proposal_audience'].label = _(
# 'What\'s the intended audience of your proposal?')
# self.fields['mentor_wanted'].label = _('I\'d like a mentor')
# self.fields['mentor_offer'].label = _('I\'m volunteering as mentor')
# self.fields['pycon'].label = _('Do you want to submit your proposal to PyCon Italia 2017?')
#
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# Path: conference/cfp/views.py
# class SubmissionView(CreateView):
# thanks_page = 'thanks_cfp'
# closed_page = 'closed_cfp'
# closing_date = settings.CFP_CLOSING_DATE
#
# def _send_notification(self):
# if self.object:
# with open(os.path.join(settings.STATIC_ROOT, 'css', 'style.css'), 'r') as css_file:
# css = css_file.read()
# context = {
# 'css': css,
# 'instance': self.object
# }
# email = MagicMailBuilder()
# notification = email.submission_notification(self.object.email, context)
# notification.send()
#
# def get_success_url(self):
# self._send_notification()
# try:
# return Page.objects.public().get(reverse_id=self.thanks_page).get_absolute_url()
# except Page.DoesNotExist:
# return Page.objects.public().get_home().get_absolute_url()
#
# def get(self, request, *args, **kwargs):
# if is_cfp_closed(self.closing_date):
# redirect_url = Page.objects.public().get(reverse_id=self.closed_page).get_absolute_url()
# return HttpResponseRedirect(redirect_url)
# return super(SubmissionView, self).get(request, *args, **kwargs)
. Output only the next line. | 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 TalkSubmissionForm
from .models import Submission
from .views import SubmissionView
and context:
# Path: conference/cfp/forms.py
# class TalkSubmissionForm(forms.ModelForm):
#
# 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'
# )
#
# def __init__(self, *args, **kwargs):
# super(TalkSubmissionForm, self).__init__(*args, **kwargs)
# self.fields['author'].label = _('Your name')
# self.fields['email'].label = _('Your email')
# self.fields['author_bio'].label = _('Tell us about yourself')
# self.fields['proposal_title'].label = _('Your proposal\'s title')
# self.fields['proposal_abstract'].label = _('Abstract of your proposal')
# self.fields['proposal_why'].label = _('What the audience will get from your proposal?')
# self.fields['proposal_requirements'].label = _(
# 'Do you have any special requirement for your talk?'
# )
# self.fields['proposal_audience'].label = _(
# 'What\'s the intended audience of your proposal?')
# self.fields['mentor_wanted'].label = _('I\'d like a mentor')
# self.fields['mentor_offer'].label = _('I\'m volunteering as mentor')
# self.fields['pycon'].label = _('Do you want to submit your proposal to PyCon Italia 2017?')
#
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# Path: conference/cfp/views.py
# class SubmissionView(CreateView):
# thanks_page = 'thanks_cfp'
# closed_page = 'closed_cfp'
# closing_date = settings.CFP_CLOSING_DATE
#
# def _send_notification(self):
# if self.object:
# with open(os.path.join(settings.STATIC_ROOT, 'css', 'style.css'), 'r') as css_file:
# css = css_file.read()
# context = {
# 'css': css,
# 'instance': self.object
# }
# email = MagicMailBuilder()
# notification = email.submission_notification(self.object.email, context)
# notification.send()
#
# def get_success_url(self):
# self._send_notification()
# try:
# return Page.objects.public().get(reverse_id=self.thanks_page).get_absolute_url()
# except Page.DoesNotExist:
# return Page.objects.public().get_home().get_absolute_url()
#
# def get(self, request, *args, **kwargs):
# if is_cfp_closed(self.closing_date):
# redirect_url = Page.objects.public().get(reverse_id=self.closed_page).get_absolute_url()
# return HttpResponseRedirect(redirect_url)
# return super(SubmissionView, self).get(request, *args, **kwargs)
which might include code, classes, or functions. Output only the next line. | 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 = _("Set submission as 'Selected'") # NOQA
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from import_export import resources
from import_export.admin import ExportActionModelAdmin
from .models import Submission, WorkshopSubmission
and context including class names, function names, and sometimes code from other files:
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
. Output only the next line. | @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 = _("Set submission as 'Selected'") # NOQA
@admin.register(Submission)
class TalkSubmissionAdmin(ExportActionModelAdmin):
list_display = (
'author', 'proposal_title', 'selected', 'pycon', 'created_at',
'mentor_wanted', 'mentor_offer'
)
list_filter = ('selected', 'pycon')
search_fields = ('author', 'proposal_title')
actions = [set_submission_as_selected]
class TalkSubmissionData(resources.ModelResource):
class Meta:
model = Submission
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from import_export import resources
from import_export.admin import ExportActionModelAdmin
from .models import Submission, WorkshopSubmission
and context including class names, function names, and sometimes code from other files:
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
. Output only the next line. | @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.urls import url
from conference.schedule.views import SlotDetail, SlotList
and context (classes, functions, sometimes code) from other files:
# Path: conference/schedule/views.py
# class SlotDetail(DetailView):
# model = Slot
# context_object_name = 'talk'
#
# def get_context_data(self, **kwargs):
# context = super(SlotDetail, self).get_context_data(**kwargs)
# context['meta'] = self.get_object().as_meta(self.request)
# return context
#
# class SlotList(ListView):
# model = Slot
# context_object_name = 'talks'
#
# def get_context_data(self, **kwargs):
# context = super(SlotList, self).get_context_data(**kwargs)
# context['talks'] = super(SlotList, self).get_queryset().filter(sprint_days=False)
# context['workshops'] = super(SlotList, self).get_queryset().filter(sprint_days=True)
# return context
. Output only the next line. | 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.translation import gettext_lazy as _
from conference.cfp.models import Submission, WorkshopSubmission
and context (classes, functions, sometimes code) from other files:
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
. Output only the next line. | 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'
)
def __init__(self, *args, **kwargs):
super(TalkSubmissionForm, self).__init__(*args, **kwargs)
self.fields['author'].label = _('Your name')
self.fields['email'].label = _('Your email')
self.fields['author_bio'].label = _('Tell us about yourself')
self.fields['proposal_title'].label = _('Your proposal\'s title')
self.fields['proposal_abstract'].label = _('Abstract of your proposal')
self.fields['proposal_why'].label = _('What the audience will get from your proposal?')
self.fields['proposal_requirements'].label = _(
'Do you have any special requirement for your talk?'
)
self.fields['proposal_audience'].label = _(
'What\'s the intended audience of your proposal?')
self.fields['mentor_wanted'].label = _('I\'d like a mentor')
self.fields['mentor_offer'].label = _('I\'m volunteering as mentor')
self.fields['pycon'].label = _('Do you want to submit your proposal to PyCon Italia 2017?')
class WorkshopSubmissionForm(forms.ModelForm):
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from django import forms
from django.utils.translation import gettext_lazy as _
from conference.cfp.models import Submission, WorkshopSubmission
and context (functions, classes, or occasionally code) from other files:
# Path: conference/cfp/models.py
# class Submission(AbstractSubmission):
# proposal_why = models.TextField(
# _('Motivation'),
# help_text=_('Explain here why your proposal is important for the attendees and what they will get from it.')
# )
# proposal_requirements = models.TextField(
# _('Requirements'), blank=False, default='',
# )
# mentor_wanted = models.BooleanField(
# _('Mentor'), default=False,
# help_text=_('More experienced speakers can help you reviewing your talk, '
# 'practicing, and getting ready for the presentation')
# )
# mentor_offer = models.BooleanField(
# _('Mentor - Offer'), default=False,
# help_text=_('Are you an experienced speaker and are you willing to help other speakers? '
# 'Select this and we will get in contact with you!')
# )
# pycon = models.BooleanField(
# _('PyCon'), default=False,
# help_text=_('We will share your proposal with the PyCon Italia Team and they will '
# 'evaluate independently your proposal.')
# )
#
# class Meta:
# verbose_name = _('talk submission')
# verbose_name_plural = _('talk submissions')
#
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
. Output only the next line. | 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 .views import is_cfp_closed
and context:
# Path: conference/cfp/views.py
# def is_cfp_closed(closing_date):
# cfp_closing_date = datetime.datetime.strptime(closing_date, '%Y-%m-%d')
# return cfp_closing_date.date() <= datetime.date.today()
which might include code, classes, or functions. Output only the next line. | 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 import url
from .forms import WorkshopSubmissionForm
from .models import WorkshopSubmission
from .views import SubmissionView
and context (classes, functions, sometimes code) from other files:
# Path: conference/cfp/forms.py
# class WorkshopSubmissionForm(forms.ModelForm):
#
# class Meta:
# model = WorkshopSubmission
# fields = (
# 'author', 'email', 'author_bio', 'proposal_title',
# 'proposal_abstract', 'proposal_audience', 'workshop_duration',
# 'notes'
# )
#
# def __init__(self, *args, **kwargs):
# super(WorkshopSubmissionForm, self).__init__(*args, **kwargs)
# self.fields['author'].label = _('Your name')
# self.fields['email'].label = _('Your email')
# self.fields['author_bio'].label = _('Tell us about yourself')
# self.fields['proposal_title'].label = _('Your proposal\'s title')
# self.fields['proposal_abstract'].label = _('Abstract of your proposal')
# self.fields['proposal_audience'].label = _(
# 'What\'s the intended audience of your proposal?')
# self.fields['workshop_duration'].lable = _('How long is the workshop?')
#
# Path: conference/cfp/models.py
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
#
# Path: conference/cfp/views.py
# class SubmissionView(CreateView):
# thanks_page = 'thanks_cfp'
# closed_page = 'closed_cfp'
# closing_date = settings.CFP_CLOSING_DATE
#
# def _send_notification(self):
# if self.object:
# with open(os.path.join(settings.STATIC_ROOT, 'css', 'style.css'), 'r') as css_file:
# css = css_file.read()
# context = {
# 'css': css,
# 'instance': self.object
# }
# email = MagicMailBuilder()
# notification = email.submission_notification(self.object.email, context)
# notification.send()
#
# def get_success_url(self):
# self._send_notification()
# try:
# return Page.objects.public().get(reverse_id=self.thanks_page).get_absolute_url()
# except Page.DoesNotExist:
# return Page.objects.public().get_home().get_absolute_url()
#
# def get(self, request, *args, **kwargs):
# if is_cfp_closed(self.closing_date):
# redirect_url = Page.objects.public().get(reverse_id=self.closed_page).get_absolute_url()
# return HttpResponseRedirect(redirect_url)
# return super(SubmissionView, self).get(request, *args, **kwargs)
. Output only the next line. | 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 import url
from .forms import WorkshopSubmissionForm
from .models import WorkshopSubmission
from .views import SubmissionView
and context from other files:
# Path: conference/cfp/forms.py
# class WorkshopSubmissionForm(forms.ModelForm):
#
# class Meta:
# model = WorkshopSubmission
# fields = (
# 'author', 'email', 'author_bio', 'proposal_title',
# 'proposal_abstract', 'proposal_audience', 'workshop_duration',
# 'notes'
# )
#
# def __init__(self, *args, **kwargs):
# super(WorkshopSubmissionForm, self).__init__(*args, **kwargs)
# self.fields['author'].label = _('Your name')
# self.fields['email'].label = _('Your email')
# self.fields['author_bio'].label = _('Tell us about yourself')
# self.fields['proposal_title'].label = _('Your proposal\'s title')
# self.fields['proposal_abstract'].label = _('Abstract of your proposal')
# self.fields['proposal_audience'].label = _(
# 'What\'s the intended audience of your proposal?')
# self.fields['workshop_duration'].lable = _('How long is the workshop?')
#
# Path: conference/cfp/models.py
# class WorkshopSubmission(AbstractSubmission):
# TWO_HOURS = '2'
# DURATIONS = (
# (TWO_HOURS, _('2 Hours')),
# )
# workshop_duration = models.CharField(
# _('Duration'), choices=DURATIONS, max_length=10,
# )
#
# class Meta:
# verbose_name = _('workshop submission')
# verbose_name_plural = _('workshop submissions')
#
# Path: conference/cfp/views.py
# class SubmissionView(CreateView):
# thanks_page = 'thanks_cfp'
# closed_page = 'closed_cfp'
# closing_date = settings.CFP_CLOSING_DATE
#
# def _send_notification(self):
# if self.object:
# with open(os.path.join(settings.STATIC_ROOT, 'css', 'style.css'), 'r') as css_file:
# css = css_file.read()
# context = {
# 'css': css,
# 'instance': self.object
# }
# email = MagicMailBuilder()
# notification = email.submission_notification(self.object.email, context)
# notification.send()
#
# def get_success_url(self):
# self._send_notification()
# try:
# return Page.objects.public().get(reverse_id=self.thanks_page).get_absolute_url()
# except Page.DoesNotExist:
# return Page.objects.public().get_home().get_absolute_url()
#
# def get(self, request, *args, **kwargs):
# if is_cfp_closed(self.closing_date):
# redirect_url = Page.objects.public().get(reverse_id=self.closed_page).get_absolute_url()
# return HttpResponseRedirect(redirect_url)
# return super(SubmissionView, self).get(request, *args, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | 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_list(smiles_list: Iterable[str], include_stereocenters=True) -> List[str]:
"""
Canonicalize a list of smiles. Filters out repetitions and removes corrupted molecules.
Args:
smiles_list: molecules as SMILES strings
include_stereocenters: whether to keep the stereochemical information in the canonical SMILES strings
Returns:
The canonicalized and filtered input smiles.
"""
canonicalized_smiles = [canonicalize(smiles, include_stereocenters) for smiles in smiles_list]
# Remove None elements
canonicalized_smiles = [s for s in canonicalized_smiles if s is not None]
<|code_end|>
, generate the next line using the imports in this file:
import logging
import re
import numpy as np
from typing import Optional, List, Iterable, Collection, Tuple
from rdkit import Chem
from rdkit import RDLogger, DataStructs
from rdkit.Chem import AllChem
from rdkit.ML.Descriptors import MoleculeDescriptors
from scipy import histogram
from scipy.stats import entropy, gaussian_kde
from guacamol.utils.data import remove_duplicates
and context (functions, classes, or occasionally code) from other files:
# Path: guacamol/utils/data.py
# def remove_duplicates(list_with_duplicates):
# """
# Removes the duplicates and keeps the ordering of the original list.
# For duplicates, the first occurrence is kept and the later occurrences are ignored.
#
# Args:
# list_with_duplicates: list that possibly contains duplicates
#
# Returns:
# A list with no duplicates.
# """
#
# unique_set: Set[Any] = set()
# unique_list = []
# for element in list_with_duplicates:
# if element not in unique_set:
# unique_set.add(element)
# unique_list.append(element)
#
# return unique_list
. Output only the next line. | 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, sometimes code) from other files:
# Path: guacamol/utils/descriptors.py
# def num_atoms(mol: Mol) -> int:
# """
# Returns the total number of atoms, H included
# """
# mol = Chem.AddHs(mol)
# return mol.GetNumAtoms()
#
# class AtomCounter:
#
# def __init__(self, element: str) -> None:
# """
# Args:
# element: element to count within a molecule
# """
# self.element = element
#
# def __call__(self, mol: Mol) -> int:
# """
# Count the number of atoms of a given type.
#
# Args:
# mol: molecule
#
# Returns:
# The number of atoms of the given type.
# """
# # if the molecule contains H atoms, they may be implicit, so add them
# if self.element == 'H':
# mol = Chem.AddHs(mol)
#
# return sum(1 for a in mol.GetAtoms() if a.GetSymbol() == self.element)
. Output only the next line. | 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 mol.GetNumAtoms() == 7
def test_count_c_atoms():
smiles = 'CCOC(CCC)'
mol = Chem.MolFromSmiles(smiles)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rdkit import Chem
from guacamol.utils.descriptors import num_atoms, AtomCounter
and context:
# Path: guacamol/utils/descriptors.py
# def num_atoms(mol: Mol) -> int:
# """
# Returns the total number of atoms, H included
# """
# mol = Chem.AddHs(mol)
# return mol.GetNumAtoms()
#
# class AtomCounter:
#
# def __init__(self, element: str) -> None:
# """
# Args:
# element: element to count within a molecule
# """
# self.element = element
#
# def __call__(self, mol: Mol) -> int:
# """
# Count the number of atoms of a given type.
#
# Args:
# mol: molecule
#
# Returns:
# The number of atoms of the given type.
# """
# # if the molecule contains H atoms, they may be implicit, so add them
# if self.element == 'H':
# mol = Chem.AddHs(mol)
#
# return sum(1 for a in mol.GetAtoms() if a.GetSymbol() == self.element)
which might include code, classes, or functions. Output only the next line. | 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 not is_valid(smiles)
def test_validity_correct_molecules():
smiles_1 = 'O'
smiles_2 = 'C'
smiles_3 = 'CC(ONONOC)CCCc1ccccc1'
assert is_valid(smiles_1)
assert is_valid(smiles_2)
assert is_valid(smiles_3)
def test_isomeric_canonicalisation():
endiandric_acid = r'OC(=O)[C@H]5C2\C=C/C3[C@@H]5CC4[C@H](C\C=C\C=C\c1ccccc1)[C@@H]2[C@@H]34'
<|code_end|>
, generate the next line using the imports in this file:
from guacamol.utils.chemistry import canonicalize, canonicalize_list, is_valid, \
calculate_internal_pairwise_similarities, calculate_pairwise_similarities, parse_molecular_formula
and context (functions, classes, or occasionally code) from other files:
# Path: guacamol/utils/chemistry.py
# def canonicalize(smiles: str, include_stereocenters=True) -> Optional[str]:
# """
# Canonicalize the SMILES strings with RDKit.
#
# The algorithm is detailed under https://pubs.acs.org/doi/full/10.1021/acs.jcim.5b00543
#
# Args:
# smiles: SMILES string to canonicalize
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES string
#
# 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_list(smiles_list: Iterable[str], include_stereocenters=True) -> List[str]:
# """
# Canonicalize a list of smiles. Filters out repetitions and removes corrupted molecules.
#
# Args:
# smiles_list: molecules as SMILES strings
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES strings
#
# Returns:
# The canonicalized and filtered input smiles.
# """
#
# canonicalized_smiles = [canonicalize(smiles, include_stereocenters) for smiles in smiles_list]
#
# # Remove None elements
# canonicalized_smiles = [s for s in canonicalized_smiles if s is not None]
#
# return remove_duplicates(canonicalized_smiles)
#
# def is_valid(smiles: str):
# """
# Verifies whether a SMILES string corresponds to a valid molecule.
#
# Args:
# smiles: SMILES string
#
# Returns:
# True if the SMILES strings corresponds to a valid, non-empty molecule.
# """
#
# mol = Chem.MolFromSmiles(smiles)
#
# return smiles != '' and mol is not None and mol.GetNumAtoms() > 0
#
# def calculate_internal_pairwise_similarities(smiles_list: Collection[str]) -> np.ndarray:
# """
# Computes the pairwise similarities of the provided list of smiles against itself.
#
# Returns:
# Symmetric matrix of pairwise similarities. Diagonal is set to zero.
# """
# if len(smiles_list) > 10000:
# logger.warning(f'Calculating internal similarity on large set of '
# f'SMILES strings ({len(smiles_list)})')
#
# mols = get_mols(smiles_list)
# fps = get_fingerprints(mols)
# nfps = len(fps)
#
# similarities = np.zeros((nfps, nfps))
#
# for i in range(1, nfps):
# sims = DataStructs.BulkTanimotoSimilarity(fps[i], fps[:i])
# similarities[i, :i] = sims
# similarities[:i, i] = sims
#
# return similarities
#
# def calculate_pairwise_similarities(smiles_list1: List[str], smiles_list2: List[str]) -> np.ndarray:
# """
# Computes the pairwise ECFP4 tanimoto similarity of the two smiles containers.
#
# Returns:
# Pairwise similarity matrix as np.ndarray
# """
# if len(smiles_list1) > 10000 or len(smiles_list2) > 10000:
# logger.warning(f'Calculating similarity between large sets of '
# f'SMILES strings ({len(smiles_list1)} x {len(smiles_list2)})')
#
# mols1 = get_mols(smiles_list1)
# fps1 = get_fingerprints(mols1)
#
# mols2 = get_mols(smiles_list2)
# fps2 = get_fingerprints(mols2)
#
# similarities = []
#
# for fp1 in fps1:
# sims = DataStructs.BulkTanimotoSimilarity(fp1, fps2)
#
# similarities.append(sims)
#
# return np.array(similarities)
#
# def parse_molecular_formula(formula: str) -> List[Tuple[str, int]]:
# """
# Parse a molecular formulat to get the element types and counts.
#
# Args:
# formula: molecular formula, f.i. "C8H3F3Br"
#
# Returns:
# A list of tuples containing element types and number of occurrences.
# """
# matches = re.findall(r'([A-Z][a-z]*)(\d*)', formula)
#
# # Convert matches to the required format
# results = []
# for match in matches:
# # convert count to an integer, and set it to 1 if the count is not visible in the molecular formula
# count = 1 if not match[1] else int(match[1])
# results.append((match[0], count))
#
# return results
. Output only the next line. | 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_internal_sim():
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]):
assert sim[i, j] == sim[j, i]
if i != j:
assert sim[i, j] < 1.0
else:
assert sim[i, j] == 0
def test_external_sim():
molz1 = ['OCCCF', 'c1cc(F)ccc1', 'c1cnc(CO)cc1', 'FOOF']
molz2 = ['c1cc(Cl)ccc1', '[Cr][Ac][K]', '[Ca](F)[Fe]']
<|code_end|>
. Use current file imports:
(from guacamol.utils.chemistry import canonicalize, canonicalize_list, is_valid, \
calculate_internal_pairwise_similarities, calculate_pairwise_similarities, parse_molecular_formula)
and context including class names, function names, or small code snippets from other files:
# Path: guacamol/utils/chemistry.py
# def canonicalize(smiles: str, include_stereocenters=True) -> Optional[str]:
# """
# Canonicalize the SMILES strings with RDKit.
#
# The algorithm is detailed under https://pubs.acs.org/doi/full/10.1021/acs.jcim.5b00543
#
# Args:
# smiles: SMILES string to canonicalize
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES string
#
# 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_list(smiles_list: Iterable[str], include_stereocenters=True) -> List[str]:
# """
# Canonicalize a list of smiles. Filters out repetitions and removes corrupted molecules.
#
# Args:
# smiles_list: molecules as SMILES strings
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES strings
#
# Returns:
# The canonicalized and filtered input smiles.
# """
#
# canonicalized_smiles = [canonicalize(smiles, include_stereocenters) for smiles in smiles_list]
#
# # Remove None elements
# canonicalized_smiles = [s for s in canonicalized_smiles if s is not None]
#
# return remove_duplicates(canonicalized_smiles)
#
# def is_valid(smiles: str):
# """
# Verifies whether a SMILES string corresponds to a valid molecule.
#
# Args:
# smiles: SMILES string
#
# Returns:
# True if the SMILES strings corresponds to a valid, non-empty molecule.
# """
#
# mol = Chem.MolFromSmiles(smiles)
#
# return smiles != '' and mol is not None and mol.GetNumAtoms() > 0
#
# def calculate_internal_pairwise_similarities(smiles_list: Collection[str]) -> np.ndarray:
# """
# Computes the pairwise similarities of the provided list of smiles against itself.
#
# Returns:
# Symmetric matrix of pairwise similarities. Diagonal is set to zero.
# """
# if len(smiles_list) > 10000:
# logger.warning(f'Calculating internal similarity on large set of '
# f'SMILES strings ({len(smiles_list)})')
#
# mols = get_mols(smiles_list)
# fps = get_fingerprints(mols)
# nfps = len(fps)
#
# similarities = np.zeros((nfps, nfps))
#
# for i in range(1, nfps):
# sims = DataStructs.BulkTanimotoSimilarity(fps[i], fps[:i])
# similarities[i, :i] = sims
# similarities[:i, i] = sims
#
# return similarities
#
# def calculate_pairwise_similarities(smiles_list1: List[str], smiles_list2: List[str]) -> np.ndarray:
# """
# Computes the pairwise ECFP4 tanimoto similarity of the two smiles containers.
#
# Returns:
# Pairwise similarity matrix as np.ndarray
# """
# if len(smiles_list1) > 10000 or len(smiles_list2) > 10000:
# logger.warning(f'Calculating similarity between large sets of '
# f'SMILES strings ({len(smiles_list1)} x {len(smiles_list2)})')
#
# mols1 = get_mols(smiles_list1)
# fps1 = get_fingerprints(mols1)
#
# mols2 = get_mols(smiles_list2)
# fps2 = get_fingerprints(mols2)
#
# similarities = []
#
# for fp1 in fps1:
# sims = DataStructs.BulkTanimotoSimilarity(fp1, fps2)
#
# similarities.append(sims)
#
# return np.array(similarities)
#
# def parse_molecular_formula(formula: str) -> List[Tuple[str, int]]:
# """
# Parse a molecular formulat to get the element types and counts.
#
# Args:
# formula: molecular formula, f.i. "C8H3F3Br"
#
# Returns:
# A list of tuples containing element types and number of occurrences.
# """
# matches = re.findall(r'([A-Z][a-z]*)(\d*)', formula)
#
# # Convert matches to the required format
# results = []
# for match in matches:
# # convert count to an integer, and set it to 1 if the count is not visible in the molecular formula
# count = 1 if not match[1] else int(match[1])
# results.append((match[0], count))
#
# return results
. Output only the next line. | 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]):
assert sim[i, j] == sim[j, i]
if i != j:
assert sim[i, j] < 1.0
else:
assert sim[i, j] == 0
def test_external_sim():
molz1 = ['OCCCF', 'c1cc(F)ccc1', 'c1cnc(CO)cc1', 'FOOF']
molz2 = ['c1cc(Cl)ccc1', '[Cr][Ac][K]', '[Ca](F)[Fe]']
sim = calculate_pairwise_similarities(molz1, molz2)
assert sim.shape[0] == 4
assert sim.shape[1] == 3
# check elements
for i in range(sim.shape[0]):
for j in range(sim.shape[1]):
assert sim[i, j] < 1.0
def test_parse_molecular_formula():
formula = 'C6H9NOF2Cl2Br'
<|code_end|>
. Use current file imports:
from guacamol.utils.chemistry import canonicalize, canonicalize_list, is_valid, \
calculate_internal_pairwise_similarities, calculate_pairwise_similarities, parse_molecular_formula
and context (classes, functions, or code) from other files:
# Path: guacamol/utils/chemistry.py
# def canonicalize(smiles: str, include_stereocenters=True) -> Optional[str]:
# """
# Canonicalize the SMILES strings with RDKit.
#
# The algorithm is detailed under https://pubs.acs.org/doi/full/10.1021/acs.jcim.5b00543
#
# Args:
# smiles: SMILES string to canonicalize
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES string
#
# 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_list(smiles_list: Iterable[str], include_stereocenters=True) -> List[str]:
# """
# Canonicalize a list of smiles. Filters out repetitions and removes corrupted molecules.
#
# Args:
# smiles_list: molecules as SMILES strings
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES strings
#
# Returns:
# The canonicalized and filtered input smiles.
# """
#
# canonicalized_smiles = [canonicalize(smiles, include_stereocenters) for smiles in smiles_list]
#
# # Remove None elements
# canonicalized_smiles = [s for s in canonicalized_smiles if s is not None]
#
# return remove_duplicates(canonicalized_smiles)
#
# def is_valid(smiles: str):
# """
# Verifies whether a SMILES string corresponds to a valid molecule.
#
# Args:
# smiles: SMILES string
#
# Returns:
# True if the SMILES strings corresponds to a valid, non-empty molecule.
# """
#
# mol = Chem.MolFromSmiles(smiles)
#
# return smiles != '' and mol is not None and mol.GetNumAtoms() > 0
#
# def calculate_internal_pairwise_similarities(smiles_list: Collection[str]) -> np.ndarray:
# """
# Computes the pairwise similarities of the provided list of smiles against itself.
#
# Returns:
# Symmetric matrix of pairwise similarities. Diagonal is set to zero.
# """
# if len(smiles_list) > 10000:
# logger.warning(f'Calculating internal similarity on large set of '
# f'SMILES strings ({len(smiles_list)})')
#
# mols = get_mols(smiles_list)
# fps = get_fingerprints(mols)
# nfps = len(fps)
#
# similarities = np.zeros((nfps, nfps))
#
# for i in range(1, nfps):
# sims = DataStructs.BulkTanimotoSimilarity(fps[i], fps[:i])
# similarities[i, :i] = sims
# similarities[:i, i] = sims
#
# return similarities
#
# def calculate_pairwise_similarities(smiles_list1: List[str], smiles_list2: List[str]) -> np.ndarray:
# """
# Computes the pairwise ECFP4 tanimoto similarity of the two smiles containers.
#
# Returns:
# Pairwise similarity matrix as np.ndarray
# """
# if len(smiles_list1) > 10000 or len(smiles_list2) > 10000:
# logger.warning(f'Calculating similarity between large sets of '
# f'SMILES strings ({len(smiles_list1)} x {len(smiles_list2)})')
#
# mols1 = get_mols(smiles_list1)
# fps1 = get_fingerprints(mols1)
#
# mols2 = get_mols(smiles_list2)
# fps2 = get_fingerprints(mols2)
#
# similarities = []
#
# for fp1 in fps1:
# sims = DataStructs.BulkTanimotoSimilarity(fp1, fps2)
#
# similarities.append(sims)
#
# return np.array(similarities)
#
# def parse_molecular_formula(formula: str) -> List[Tuple[str, int]]:
# """
# Parse a molecular formulat to get the element types and counts.
#
# Args:
# formula: molecular formula, f.i. "C8H3F3Br"
#
# Returns:
# A list of tuples containing element types and number of occurrences.
# """
# matches = re.findall(r'([A-Z][a-z]*)(\d*)', formula)
#
# # Convert matches to the required format
# results = []
# for match in matches:
# # convert count to an integer, and set it to 1 if the count is not visible in the molecular formula
# count = 1 if not match[1] else int(match[1])
# results.append((match[0], count))
#
# return results
. Output only the next line. | 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 __init__(self, training_set: List[str],
chemnet_model_filename='ChemNet_v0.13_pretrained.h5',
sample_size=10000) -> None:
"""
Args:
training_set: molecules from the training set
chemnet_model_filename: name of the file for trained ChemNet model.
Must be present in the 'fcd' package, since it will be loaded directly from there.
sample_size: how many molecules to generate the distribution statistics from (both reference data and model)
"""
self.chemnet_model_filename = chemnet_model_filename
self.sample_size = sample_size
super().__init__(name='Frechet ChemNet Distance', number_samples=self.sample_size)
self.reference_molecules = get_random_subset(training_set, self.sample_size, seed=42)
<|code_end|>
with the help of current file imports:
import logging
import os
import pkgutil
import tempfile
import time
import fcd
import numpy as np
from typing import List
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.utils.data import get_random_subset
from guacamol.utils.sampling_helpers import sample_valid_molecules
and context from other files:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/utils/data.py
# def get_random_subset(dataset: List[Any], subset_size: int, seed: Optional[int] = None) -> List[Any]:
# """
# Get a random subset of some dataset.
#
# For reproducibility, the random number generator seed can be specified.
# Nevertheless, the state of the random number generator is restored to avoid side effects.
#
# Args:
# dataset: full set to select a subset from
# subset_size: target size of the subset
# seed: random number generator seed. Defaults to not setting the seed.
#
# Returns:
# subset of the original dataset as a list
# """
# if len(dataset) < subset_size:
# raise Exception(f'The dataset to extract a subset from is too small: '
# f'{len(dataset)} < {subset_size}')
#
# # save random number generator state
# rng_state = np.random.get_state()
#
# if seed is not None:
# # extract a subset (for a given training set, the subset will always be identical).
# np.random.seed(seed)
#
# subset = np.random.choice(dataset, subset_size, replace=False)
#
# if seed is not None:
# # reset random number generator state, only if needed
# np.random.set_state(rng_state)
#
# return list(subset)
#
# Path: guacamol/utils/sampling_helpers.py
# 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:
# model: model to sample from
# number_molecules: number of valid molecules to generate
# max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
#
# Returns:
# A list of number_molecules valid molecules. If this was not possible with the given max_tries, the list may be shorter.
# """
#
# max_samples = max_tries * number_molecules
# number_already_sampled = 0
#
# valid_molecules: List[str] = []
#
# while len(valid_molecules) < number_molecules and number_already_sampled < max_samples:
# remaining_to_sample = number_molecules - len(valid_molecules)
#
# samples = model.generate(remaining_to_sample)
# number_already_sampled += remaining_to_sample
#
# valid_molecules += [m for m in samples if is_valid(m)]
#
# return valid_molecules
, which may contain function names, class names, or code. Output only the next line. | 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.
"""
def __init__(self, training_set: List[str],
chemnet_model_filename='ChemNet_v0.13_pretrained.h5',
sample_size=10000) -> None:
"""
Args:
training_set: molecules from the training set
chemnet_model_filename: name of the file for trained ChemNet model.
Must be present in the 'fcd' package, since it will be loaded directly from there.
sample_size: how many molecules to generate the distribution statistics from (both reference data and model)
"""
self.chemnet_model_filename = chemnet_model_filename
self.sample_size = sample_size
super().__init__(name='Frechet ChemNet Distance', number_samples=self.sample_size)
self.reference_molecules = get_random_subset(training_set, self.sample_size, seed=42)
<|code_end|>
. Use current file imports:
import logging
import os
import pkgutil
import tempfile
import time
import fcd
import numpy as np
from typing import List
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.utils.data import get_random_subset
from guacamol.utils.sampling_helpers import sample_valid_molecules
and context (classes, functions, or code) from other files:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/utils/data.py
# def get_random_subset(dataset: List[Any], subset_size: int, seed: Optional[int] = None) -> List[Any]:
# """
# Get a random subset of some dataset.
#
# For reproducibility, the random number generator seed can be specified.
# Nevertheless, the state of the random number generator is restored to avoid side effects.
#
# Args:
# dataset: full set to select a subset from
# subset_size: target size of the subset
# seed: random number generator seed. Defaults to not setting the seed.
#
# Returns:
# subset of the original dataset as a list
# """
# if len(dataset) < subset_size:
# raise Exception(f'The dataset to extract a subset from is too small: '
# f'{len(dataset)} < {subset_size}')
#
# # save random number generator state
# rng_state = np.random.get_state()
#
# if seed is not None:
# # extract a subset (for a given training set, the subset will always be identical).
# np.random.seed(seed)
#
# subset = np.random.choice(dataset, subset_size, replace=False)
#
# if seed is not None:
# # reset random number generator state, only if needed
# np.random.set_state(rng_state)
#
# return list(subset)
#
# Path: guacamol/utils/sampling_helpers.py
# 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:
# model: model to sample from
# number_molecules: number of valid molecules to generate
# max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
#
# Returns:
# A list of number_molecules valid molecules. If this was not possible with the given max_tries, the list may be shorter.
# """
#
# max_samples = max_tries * number_molecules
# number_already_sampled = 0
#
# valid_molecules: List[str] = []
#
# while len(valid_molecules) < number_molecules and number_already_sampled < max_samples:
# remaining_to_sample = number_molecules - len(valid_molecules)
#
# samples = model.generate(remaining_to_sample)
# number_already_sampled += remaining_to_sample
#
# valid_molecules += [m for m in samples if is_valid(m)]
#
# return valid_molecules
. Output only the next line. | 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 __init__(self, training_set: List[str],
chemnet_model_filename='ChemNet_v0.13_pretrained.h5',
sample_size=10000) -> None:
"""
Args:
training_set: molecules from the training set
chemnet_model_filename: name of the file for trained ChemNet model.
Must be present in the 'fcd' package, since it will be loaded directly from there.
sample_size: how many molecules to generate the distribution statistics from (both reference data and model)
"""
self.chemnet_model_filename = chemnet_model_filename
self.sample_size = sample_size
super().__init__(name='Frechet ChemNet Distance', number_samples=self.sample_size)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os
import pkgutil
import tempfile
import time
import fcd
import numpy as np
from typing import List
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.utils.data import get_random_subset
from guacamol.utils.sampling_helpers import sample_valid_molecules
and context (classes, functions, sometimes code) from other files:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/utils/data.py
# def get_random_subset(dataset: List[Any], subset_size: int, seed: Optional[int] = None) -> List[Any]:
# """
# Get a random subset of some dataset.
#
# For reproducibility, the random number generator seed can be specified.
# Nevertheless, the state of the random number generator is restored to avoid side effects.
#
# Args:
# dataset: full set to select a subset from
# subset_size: target size of the subset
# seed: random number generator seed. Defaults to not setting the seed.
#
# Returns:
# subset of the original dataset as a list
# """
# if len(dataset) < subset_size:
# raise Exception(f'The dataset to extract a subset from is too small: '
# f'{len(dataset)} < {subset_size}')
#
# # save random number generator state
# rng_state = np.random.get_state()
#
# if seed is not None:
# # extract a subset (for a given training set, the subset will always be identical).
# np.random.seed(seed)
#
# subset = np.random.choice(dataset, subset_size, replace=False)
#
# if seed is not None:
# # reset random number generator state, only if needed
# np.random.set_state(rng_state)
#
# return list(subset)
#
# Path: guacamol/utils/sampling_helpers.py
# 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:
# model: model to sample from
# number_molecules: number of valid molecules to generate
# max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
#
# Returns:
# A list of number_molecules valid molecules. If this was not possible with the given max_tries, the list may be shorter.
# """
#
# max_samples = max_tries * number_molecules
# number_already_sampled = 0
#
# valid_molecules: List[str] = []
#
# while len(valid_molecules) < number_molecules and number_already_sampled < max_samples:
# remaining_to_sample = number_molecules - len(valid_molecules)
#
# samples = model.generate(remaining_to_sample)
# number_already_sampled += remaining_to_sample
#
# valid_molecules += [m for m in samples if is_valid(m)]
#
# return valid_molecules
. Output only the next line. | 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__(self, training_set: List[str],
chemnet_model_filename='ChemNet_v0.13_pretrained.h5',
sample_size=10000) -> None:
"""
Args:
training_set: molecules from the training set
chemnet_model_filename: name of the file for trained ChemNet model.
Must be present in the 'fcd' package, since it will be loaded directly from there.
sample_size: how many molecules to generate the distribution statistics from (both reference data and model)
"""
self.chemnet_model_filename = chemnet_model_filename
self.sample_size = sample_size
super().__init__(name='Frechet ChemNet Distance', number_samples=self.sample_size)
self.reference_molecules = get_random_subset(training_set, self.sample_size, seed=42)
def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
chemnet = self._load_chemnet()
start_time = time.time()
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
import pkgutil
import tempfile
import time
import fcd
import numpy as np
from typing import List
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.utils.data import get_random_subset
from guacamol.utils.sampling_helpers import sample_valid_molecules
and context including class names, function names, and sometimes code from other files:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/utils/data.py
# def get_random_subset(dataset: List[Any], subset_size: int, seed: Optional[int] = None) -> List[Any]:
# """
# Get a random subset of some dataset.
#
# For reproducibility, the random number generator seed can be specified.
# Nevertheless, the state of the random number generator is restored to avoid side effects.
#
# Args:
# dataset: full set to select a subset from
# subset_size: target size of the subset
# seed: random number generator seed. Defaults to not setting the seed.
#
# Returns:
# subset of the original dataset as a list
# """
# if len(dataset) < subset_size:
# raise Exception(f'The dataset to extract a subset from is too small: '
# f'{len(dataset)} < {subset_size}')
#
# # save random number generator state
# rng_state = np.random.get_state()
#
# if seed is not None:
# # extract a subset (for a given training set, the subset will always be identical).
# np.random.seed(seed)
#
# subset = np.random.choice(dataset, subset_size, replace=False)
#
# if seed is not None:
# # reset random number generator state, only if needed
# np.random.set_state(rng_state)
#
# return list(subset)
#
# Path: guacamol/utils/sampling_helpers.py
# 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:
# model: model to sample from
# number_molecules: number of valid molecules to generate
# max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
#
# Returns:
# A list of number_molecules valid molecules. If this was not possible with the given max_tries, the list may be shorter.
# """
#
# max_samples = max_tries * number_molecules
# number_already_sampled = 0
#
# valid_molecules: List[str] = []
#
# while len(valid_molecules) < number_molecules and number_already_sampled < max_samples:
# remaining_to_sample = number_molecules - len(valid_molecules)
#
# samples = model.generate(remaining_to_sample)
# number_already_sampled += remaining_to_sample
#
# valid_molecules += [m for m in samples if is_valid(m)]
#
# return valid_molecules
. Output only the next line. | 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:
model: model to sample from
number_molecules: number of valid molecules to generate
max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
Returns:
A list of number_molecules valid molecules. If this was not possible with the given max_tries, the list may be shorter.
"""
max_samples = max_tries * number_molecules
number_already_sampled = 0
valid_molecules: List[str] = []
while len(valid_molecules) < number_molecules and number_already_sampled < max_samples:
remaining_to_sample = number_molecules - len(valid_molecules)
samples = model.generate(remaining_to_sample)
number_already_sampled += remaining_to_sample
<|code_end|>
, generate the next line using the imports in this file:
from typing import List, Set
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.utils.chemistry import is_valid, canonicalize
and context (functions, classes, or occasionally code) from other files:
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/utils/chemistry.py
# def is_valid(smiles: str):
# """
# Verifies whether a SMILES string corresponds to a valid molecule.
#
# Args:
# smiles: SMILES string
#
# Returns:
# True if the SMILES strings corresponds to a valid, non-empty molecule.
# """
#
# mol = Chem.MolFromSmiles(smiles)
#
# return smiles != '' and mol is not None and mol.GetNumAtoms() > 0
#
# def canonicalize(smiles: str, include_stereocenters=True) -> Optional[str]:
# """
# Canonicalize the SMILES strings with RDKit.
#
# The algorithm is detailed under https://pubs.acs.org/doi/full/10.1021/acs.jcim.5b00543
#
# Args:
# smiles: SMILES string to canonicalize
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES string
#
# 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
. Output only the next line. | 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 molecules).
Args:
model: model to sample from
number_molecules: number of unique (distinct) molecules to generate
max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
Returns:
A list of number_molecules unique molecules, in canonalized form.
If this was not possible with the given max_tries, the list may be shorter.
The generation order is kept.
"""
max_samples = max_tries * number_molecules
number_already_sampled = 0
unique_list: List[str] = []
unique_set: Set[str] = set()
while len(unique_list) < number_molecules and number_already_sampled < max_samples:
remaining_to_sample = number_molecules - len(unique_list)
samples = model.generate(remaining_to_sample)
number_already_sampled += remaining_to_sample
for smiles in samples:
<|code_end|>
with the help of current file imports:
from typing import List, Set
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.utils.chemistry import is_valid, canonicalize
and context from other files:
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/utils/chemistry.py
# def is_valid(smiles: str):
# """
# Verifies whether a SMILES string corresponds to a valid molecule.
#
# Args:
# smiles: SMILES string
#
# Returns:
# True if the SMILES strings corresponds to a valid, non-empty molecule.
# """
#
# mol = Chem.MolFromSmiles(smiles)
#
# return smiles != '' and mol is not None and mol.GetNumAtoms() > 0
#
# def canonicalize(smiles: str, include_stereocenters=True) -> Optional[str]:
# """
# Canonicalize the SMILES strings with RDKit.
#
# The algorithm is detailed under https://pubs.acs.org/doi/full/10.1021/acs.jcim.5b00543
#
# Args:
# smiles: SMILES string to canonicalize
# include_stereocenters: whether to keep the stereochemical information in the canonical SMILES string
#
# 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
, which may contain function names, class names, or code. Output only the next line. | 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]:
"""
Calculate the objective score before application of the modifier for a batch of molecules.
Args:
smiles_list: list of SMILES strings to process
Returns:
A list of scores. For unsuccessful calculations or invalid molecules, `None` should be given as a value for
the corresponding molecule.
"""
raise NotImplementedError
class ScoringFunctionBasedOnRdkitMol(MoleculewiseScoringFunction):
"""
Base class for scoring functions that calculate scores based on rdkit.Chem.Mol instances.
Derived classes must implement the `score_mol` function.
"""
def raw_score(self, smiles: str) -> float:
<|code_end|>
, predict the immediate next line with the help of imports:
from abc import abstractmethod
from typing import List, Optional
from rdkit import Chem
from guacamol.utils.chemistry import smiles_to_rdkit_mol
from guacamol.score_modifier import ScoreModifier, LinearModifier
from guacamol.utils.math import geometric_mean
import logging
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: guacamol/utils/chemistry.py
# def smiles_to_rdkit_mol(smiles: str) -> Optional[Chem.Mol]:
# """
# Converts a SMILES string to a RDKit molecule.
#
# Args:
# smiles: SMILES string of the molecule
#
# Returns:
# RDKit Mol, None if the SMILES string is invalid
# """
# mol = Chem.MolFromSmiles(smiles)
#
# # Sanitization check (detects invalid valence)
# if mol is not None:
# try:
# Chem.SanitizeMol(mol)
# except ValueError:
# return None
#
# return mol
#
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# """
# Interface for score modifiers.
# """
#
# @abstractmethod
# def __call__(self, x):
# """
# Apply the modifier on x.
#
# Args:
# x: float or np.array to modify
#
# Returns:
# float or np.array (depending on the type of x) after application of the distance function.
# """
#
# class LinearModifier(ScoreModifier):
# """
# Score modifier that multiplies the score by a scalar (default: 1, i.e. do nothing).
# """
#
# def __init__(self, slope=1.0):
# self.slope = slope
#
# def __call__(self, x):
# return self.slope * x
#
# Path: guacamol/utils/math.py
# def geometric_mean(values: List[float]) -> float:
# """
# Computes the geometric mean of a list of values.
# """
# a = np.array(values)
# return a.prod() ** (1.0 / len(a))
. Output only the next line. | 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 `MoleculewiseScoringFunction` or `BatchScoringFunction`.
"""
<|code_end|>
with the help of current file imports:
from abc import abstractmethod
from typing import List, Optional
from rdkit import Chem
from guacamol.utils.chemistry import smiles_to_rdkit_mol
from guacamol.score_modifier import ScoreModifier, LinearModifier
from guacamol.utils.math import geometric_mean
import logging
import numpy as np
and context from other files:
# Path: guacamol/utils/chemistry.py
# def smiles_to_rdkit_mol(smiles: str) -> Optional[Chem.Mol]:
# """
# Converts a SMILES string to a RDKit molecule.
#
# Args:
# smiles: SMILES string of the molecule
#
# Returns:
# RDKit Mol, None if the SMILES string is invalid
# """
# mol = Chem.MolFromSmiles(smiles)
#
# # Sanitization check (detects invalid valence)
# if mol is not None:
# try:
# Chem.SanitizeMol(mol)
# except ValueError:
# return None
#
# return mol
#
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# """
# Interface for score modifiers.
# """
#
# @abstractmethod
# def __call__(self, x):
# """
# Apply the modifier on x.
#
# Args:
# x: float or np.array to modify
#
# Returns:
# float or np.array (depending on the type of x) after application of the distance function.
# """
#
# class LinearModifier(ScoreModifier):
# """
# Score modifier that multiplies the score by a scalar (default: 1, i.e. do nothing).
# """
#
# def __init__(self, slope=1.0):
# self.slope = slope
#
# def __call__(self, x):
# return self.slope * x
#
# Path: guacamol/utils/math.py
# def geometric_mean(values: List[float]) -> float:
# """
# Computes the geometric mean of a list of values.
# """
# a = np.array(values)
# return a.prod() ** (1.0 / len(a))
, which may contain function names, class names, or code. Output only the next line. | 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 `MoleculewiseScoringFunction` or `BatchScoringFunction`.
"""
def __init__(self, score_modifier: ScoreModifier = None) -> None:
"""
Args:
score_modifier: Modifier to apply to the score. If None, will be LinearModifier()
"""
self.score_modifier = score_modifier
self.corrupt_score = -1.0
@property
def score_modifier(self):
return self._score_modifier
@score_modifier.setter
def score_modifier(self, modifier: Optional[ScoreModifier]):
<|code_end|>
, predict the immediate next line with the help of imports:
from abc import abstractmethod
from typing import List, Optional
from rdkit import Chem
from guacamol.utils.chemistry import smiles_to_rdkit_mol
from guacamol.score_modifier import ScoreModifier, LinearModifier
from guacamol.utils.math import geometric_mean
import logging
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: guacamol/utils/chemistry.py
# def smiles_to_rdkit_mol(smiles: str) -> Optional[Chem.Mol]:
# """
# Converts a SMILES string to a RDKit molecule.
#
# Args:
# smiles: SMILES string of the molecule
#
# Returns:
# RDKit Mol, None if the SMILES string is invalid
# """
# mol = Chem.MolFromSmiles(smiles)
#
# # Sanitization check (detects invalid valence)
# if mol is not None:
# try:
# Chem.SanitizeMol(mol)
# except ValueError:
# return None
#
# return mol
#
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# """
# Interface for score modifiers.
# """
#
# @abstractmethod
# def __call__(self, x):
# """
# Apply the modifier on x.
#
# Args:
# x: float or np.array to modify
#
# Returns:
# float or np.array (depending on the type of x) after application of the distance function.
# """
#
# class LinearModifier(ScoreModifier):
# """
# Score modifier that multiplies the score by a scalar (default: 1, i.e. do nothing).
# """
#
# def __init__(self, slope=1.0):
# self.slope = slope
#
# def __call__(self, x):
# return self.slope * x
#
# Path: guacamol/utils/math.py
# def geometric_mean(values: List[float]) -> float:
# """
# Computes the geometric mean of a list of values.
# """
# a = np.array(values)
# return a.prod() ** (1.0 / len(a))
. Output only the next line. | 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 list(scores)
class GeometricMeanScoringFunction(MoleculewiseScoringFunction):
"""
Scoring function that combines multiple scoring functions multiplicatively.
"""
def __init__(self, scoring_functions: List[ScoringFunction]) -> None:
"""
Args:
scoring_functions: scoring functions to combine
"""
super().__init__()
self.scoring_functions = scoring_functions
def raw_score(self, smiles: str) -> float:
partial_scores = [f.score(smiles) for f in self.scoring_functions]
if self.corrupt_score in partial_scores:
return self.corrupt_score
<|code_end|>
, predict the immediate next line with the help of imports:
from abc import abstractmethod
from typing import List, Optional
from rdkit import Chem
from guacamol.utils.chemistry import smiles_to_rdkit_mol
from guacamol.score_modifier import ScoreModifier, LinearModifier
from guacamol.utils.math import geometric_mean
import logging
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: guacamol/utils/chemistry.py
# def smiles_to_rdkit_mol(smiles: str) -> Optional[Chem.Mol]:
# """
# Converts a SMILES string to a RDKit molecule.
#
# Args:
# smiles: SMILES string of the molecule
#
# Returns:
# RDKit Mol, None if the SMILES string is invalid
# """
# mol = Chem.MolFromSmiles(smiles)
#
# # Sanitization check (detects invalid valence)
# if mol is not None:
# try:
# Chem.SanitizeMol(mol)
# except ValueError:
# return None
#
# return mol
#
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# """
# Interface for score modifiers.
# """
#
# @abstractmethod
# def __call__(self, x):
# """
# Apply the modifier on x.
#
# Args:
# x: float or np.array to modify
#
# Returns:
# float or np.array (depending on the type of x) after application of the distance function.
# """
#
# class LinearModifier(ScoreModifier):
# """
# Score modifier that multiplies the score by a scalar (default: 1, i.e. do nothing).
# """
#
# def __init__(self, slope=1.0):
# self.slope = slope
#
# def __call__(self, x):
# return self.slope * x
#
# Path: guacamol/utils/math.py
# def geometric_mean(values: List[float]) -> float:
# """
# Computes the geometric mean of a list of values.
# """
# a = np.array(values)
# return a.prod() ** (1.0 / len(a))
. Output only the next line. | 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, Optional
from guacamol.scoring_function import ScoringFunction
and context (classes, functions, sometimes code) from other files:
# Path: guacamol/scoring_function.py
# class ScoringFunction:
# """
# Base class for an objective function.
#
# In general, do not inherit directly from this class. Prefer `MoleculewiseScoringFunction` or `BatchScoringFunction`.
# """
#
# def __init__(self, score_modifier: ScoreModifier = None) -> None:
# """
# Args:
# score_modifier: Modifier to apply to the score. If None, will be LinearModifier()
# """
# self.score_modifier = score_modifier
# self.corrupt_score = -1.0
#
# @property
# def score_modifier(self):
# return self._score_modifier
#
# @score_modifier.setter
# def score_modifier(self, modifier: Optional[ScoreModifier]):
# self._score_modifier = LinearModifier() if modifier is None else modifier
#
# def modify_score(self, raw_score: float) -> float:
# return self._score_modifier(raw_score)
#
# @abstractmethod
# def score(self, smiles: str) -> float:
# """
# Score a single molecule as smiles
# """
# raise NotImplementedError
#
# @abstractmethod
# def score_list(self, smiles_list: List[str]) -> List[float]:
# """
# Score a list of smiles.
#
# Args:
# smiles_list: list of smiles [smiles1, smiles2,...]
#
# Returns: a list of scores
#
# the order of the input smiles is matched in the output.
#
# """
# raise NotImplementedError
. Output only the next line. | 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, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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_linear_function_with_slope():
slope = 3.3
f = LinearModifier(slope=slope)
assert f(scalar_value) == slope * scalar_value
assert np.array_equal(f(value_array), slope * value_array)
def test_squared_function():
target_value = 5.555
coefficient = 0.123
<|code_end|>
. Use current file imports:
(from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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) == slope * scalar_value
assert np.array_equal(f(value_array), slope * value_array)
def test_squared_function():
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)
assert f(scalar_value) == expected_scalar
assert np.array_equal(f(value_array), expected_array)
def test_absolute_function():
target_value = 5.555
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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)
assert f(scalar_value) == expected_scalar
assert np.array_equal(f(value_array), expected_array)
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
assert np.array_equal(f(value_array), expected_array)
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def test_gaussian_function():
mu = -1.223
sigma = 0.334
<|code_end|>
, determine the next line of code. You have imports:
from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest
and context (class names, function names, or code) available:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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
assert np.array_equal(f(value_array), expected_array)
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def test_gaussian_function():
mu = -1.223
sigma = 0.334
f = GaussianModifier(mu=mu, sigma=sigma)
assert f(mu) == 1.0
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
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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=sigma)
assert f(mu) == 1.0
low_value = -np.inf
large_value = np.inf
assert f(low_value) == 1.0
assert f(large_value) == 0.0
full_gaussian = partial(gaussian, mu=mu, sig=sigma)
min_gaussian_lambda = lambda x: 1.0 if x < mu else full_gaussian(x)
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
<|code_end|>
, predict the next line using imports from the current file:
from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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, sigma=sigma)
assert f(mu) == 1.0
low_value = -np.inf
large_value = np.inf
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(scalar_value)
assert np.allclose(f(value_array), max_gaussian(value_array))
def test_tanimoto_threshold_function():
threshold = 5.555
<|code_end|>
. Use current file imports:
(from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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(scalar_value)
assert np.allclose(f(value_array), max_gaussian(value_array))
def test_tanimoto_threshold_function():
threshold = 5.555
f = ThresholdedLinearModifier(threshold=threshold)
large_value = np.inf
assert f(large_value) == 1.0
assert f(threshold) == 1.0
expected_array = np.minimum(value_array, threshold) / threshold
assert np.array_equal(f(value_array), expected_array)
def test_clipped_function():
min_x = 4.4
max_x = 8.8
min_score = -3.3
max_score = 9.2
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest
and context:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
which might include code, classes, or functions. Output only the next line. | 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_x)
for x in [4.4, 4.8, 5.353, 8.034, 8.8]:
dx = x - min_x
dy = dx * slope
assert modifier(x) == pytest.approx(min_score + dy)
def test_thresholded_is_special_case_of_clipped_for_positive_input():
threshold = 4.584
thresholded_modifier = ThresholdedLinearModifier(threshold=threshold)
clipped_modifier = ClippedScoreModifier(upper_x=threshold)
values = np.array([0, 2.3, 8.545, 3.23, 0.12, 55.555])
assert np.allclose(thresholded_modifier(values), clipped_modifier(values))
def test_smooth_clipped():
min_x = 4.4
max_x = 8.8
min_score = -3.3
max_score = 9.2
<|code_end|>
using the current file's imports:
from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest
and any relevant context from other files:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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 the middle is correct
middle_x = (min_x + max_x) / 2
delta = 1e-5
vp = modifier(middle_x + delta)
vm = modifier(middle_x - delta)
slope = (vp - vm) / (2 * delta)
expected_slope = (max_score - min_score) / (max_x - min_x)
assert slope == pytest.approx(expected_slope)
# assert behavior at +- infinity
assert modifier(1e5) == pytest.approx(min_score)
assert modifier(-1e5) == pytest.approx(max_score)
def test_chained_modifier():
linear = LinearModifier(slope=2)
squared = SquaredModifier(10.0)
<|code_end|>
, determine the next line of code. You have imports:
from functools import partial
from guacamol.score_modifier import LinearModifier, SquaredModifier, AbsoluteScoreModifier, GaussianModifier, \
MinGaussianModifier, MaxGaussianModifier, ThresholdedLinearModifier, ClippedScoreModifier, \
SmoothClippedScoreModifier, ChainedModifier
import numpy as np
import pytest
and context (class names, function names, or code) available:
# Path: guacamol/score_modifier.py
# class ScoreModifier:
# class ChainedModifier(ScoreModifier):
# class LinearModifier(ScoreModifier):
# class SquaredModifier(ScoreModifier):
# class AbsoluteScoreModifier(ScoreModifier):
# class GaussianModifier(ScoreModifier):
# class MinMaxGaussianModifier(ScoreModifier):
# class ClippedScoreModifier(ScoreModifier):
# class SmoothClippedScoreModifier(ScoreModifier):
# class ThresholdedLinearModifier(ScoreModifier):
# def __call__(self, x):
# def __init__(self, modifiers: List[ScoreModifier]) -> None:
# def __call__(self, x):
# def __init__(self, slope=1.0):
# def __call__(self, x):
# def __init__(self, target_value: float, coefficient=1.0) -> None:
# def __call__(self, x):
# def __init__(self, target_value: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float) -> None:
# def __call__(self, x):
# def __init__(self, mu: float, sigma: float, minimize=False) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, upper_x: float, lower_x=0.0, high_score=1.0, low_score=0.0) -> None:
# def __call__(self, x):
# def __init__(self, threshold: float) -> None:
# def __call__(self, x):
. Output only the next line. | 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_samples: int) -> None:
"""
Internal equivalent to assess_distribution_learning, but allows for a flexible number of samples.
To call directly only for testing.
"""
logger.info(f'Benchmarking distribution learning, version {benchmark_version}')
benchmarks = distribution_learning_benchmark_suite(chembl_file_path=chembl_training_file,
version_name=benchmark_version,
number_samples=number_samples)
results = _evaluate_distribution_learning_benchmarks(model=model, benchmarks=benchmarks)
benchmark_results: Dict[str, Any] = OrderedDict()
benchmark_results['guacamol_version'] = guacamol.__version__
benchmark_results['benchmark_suite_version'] = benchmark_version
benchmark_results['timestamp'] = get_time_string()
benchmark_results['samples'] = model.generate(100)
benchmark_results['results'] = [vars(result) for result in results]
logger.info(f'Save results to file {json_output_file}')
with open(json_output_file, 'wt') as f:
f.write(json.dumps(benchmark_results, indent=4))
def _evaluate_distribution_learning_benchmarks(model: DistributionMatchingGenerator,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import json
import logging
import guacamol
from collections import OrderedDict
from typing import List, Dict, Any
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.benchmark_suites import distribution_learning_benchmark_suite
from guacamol.utils.data import get_time_string
and context:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/benchmark_suites.py
# def distribution_learning_benchmark_suite(chembl_file_path: str,
# version_name: str,
# number_samples: int) -> List[DistributionLearningBenchmark]:
# """
# Returns a suite of benchmarks for a specified benchmark version
#
# Args:
# chembl_file_path: path to ChEMBL training set, necessary for some benchmarks
# version_name: benchmark version
#
# Returns:
# List of benchmaks
# """
#
# # For distribution-learning, v1 and v2 are identical
# if version_name == 'v1' or version_name == 'v2':
# return distribution_learning_suite_v1(chembl_file_path=chembl_file_path, number_samples=number_samples)
#
# raise Exception(f'Distribution-learning benchmark suite "{version_name}" does not exist.')
#
# Path: guacamol/utils/data.py
# def get_time_string():
# lt = time.localtime()
# return "%04d%02d%02d-%02d%02d" % (lt.tm_year, lt.tm_mon, lt.tm_mday, lt.tm_hour, lt.tm_min)
which might include code, classes, or functions. Output only the next line. | 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,
number_samples: int) -> None:
"""
Internal equivalent to assess_distribution_learning, but allows for a flexible number of samples.
To call directly only for testing.
"""
logger.info(f'Benchmarking distribution learning, version {benchmark_version}')
benchmarks = distribution_learning_benchmark_suite(chembl_file_path=chembl_training_file,
version_name=benchmark_version,
number_samples=number_samples)
results = _evaluate_distribution_learning_benchmarks(model=model, benchmarks=benchmarks)
benchmark_results: Dict[str, Any] = OrderedDict()
benchmark_results['guacamol_version'] = guacamol.__version__
benchmark_results['benchmark_suite_version'] = benchmark_version
benchmark_results['timestamp'] = get_time_string()
benchmark_results['samples'] = model.generate(100)
benchmark_results['results'] = [vars(result) for result in results]
logger.info(f'Save results to file {json_output_file}')
with open(json_output_file, 'wt') as f:
f.write(json.dumps(benchmark_results, indent=4))
def _evaluate_distribution_learning_benchmarks(model: DistributionMatchingGenerator,
benchmarks: List[DistributionLearningBenchmark]
<|code_end|>
. Use current file imports:
import datetime
import json
import logging
import guacamol
from collections import OrderedDict
from typing import List, Dict, Any
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.benchmark_suites import distribution_learning_benchmark_suite
from guacamol.utils.data import get_time_string
and context (classes, functions, or code) from other files:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/benchmark_suites.py
# def distribution_learning_benchmark_suite(chembl_file_path: str,
# version_name: str,
# number_samples: int) -> List[DistributionLearningBenchmark]:
# """
# Returns a suite of benchmarks for a specified benchmark version
#
# Args:
# chembl_file_path: path to ChEMBL training set, necessary for some benchmarks
# version_name: benchmark version
#
# Returns:
# List of benchmaks
# """
#
# # For distribution-learning, v1 and v2 are identical
# if version_name == 'v1' or version_name == 'v2':
# return distribution_learning_suite_v1(chembl_file_path=chembl_file_path, number_samples=number_samples)
#
# raise Exception(f'Distribution-learning benchmark suite "{version_name}" does not exist.')
#
# Path: guacamol/utils/data.py
# def get_time_string():
# lt = time.localtime()
# return "%04d%02d%02d-%02d%02d" % (lt.tm_year, lt.tm_mon, lt.tm_mday, lt.tm_hour, lt.tm_min)
. Output only the next line. | ) -> 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',
benchmark_version='v1') -> None:
"""
Assesses a distribution-matching model for de novo molecule design.
Args:
model: Model to evaluate
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=model,
chembl_training_file=chembl_training_file,
json_output_file=json_output_file,
benchmark_version=benchmark_version,
number_samples=10000)
def _assess_distribution_learning(model: DistributionMatchingGenerator,
chembl_training_file: str,
json_output_file: str,
benchmark_version: str,
number_samples: int) -> None:
"""
Internal equivalent to assess_distribution_learning, but allows for a flexible number of samples.
To call directly only for testing.
"""
logger.info(f'Benchmarking distribution learning, version {benchmark_version}')
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import json
import logging
import guacamol
from collections import OrderedDict
from typing import List, Dict, Any
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.benchmark_suites import distribution_learning_benchmark_suite
from guacamol.utils.data import get_time_string
and context including class names, function names, and sometimes code from other files:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/benchmark_suites.py
# def distribution_learning_benchmark_suite(chembl_file_path: str,
# version_name: str,
# number_samples: int) -> List[DistributionLearningBenchmark]:
# """
# Returns a suite of benchmarks for a specified benchmark version
#
# Args:
# chembl_file_path: path to ChEMBL training set, necessary for some benchmarks
# version_name: benchmark version
#
# Returns:
# List of benchmaks
# """
#
# # For distribution-learning, v1 and v2 are identical
# if version_name == 'v1' or version_name == 'v2':
# return distribution_learning_suite_v1(chembl_file_path=chembl_file_path, number_samples=number_samples)
#
# raise Exception(f'Distribution-learning benchmark suite "{version_name}" does not exist.')
#
# Path: guacamol/utils/data.py
# def get_time_string():
# lt = time.localtime()
# return "%04d%02d%02d-%02d%02d" % (lt.tm_year, lt.tm_mon, lt.tm_mday, lt.tm_hour, lt.tm_min)
. Output only the next line. | 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=model,
chembl_training_file=chembl_training_file,
json_output_file=json_output_file,
benchmark_version=benchmark_version,
number_samples=10000)
def _assess_distribution_learning(model: DistributionMatchingGenerator,
chembl_training_file: str,
json_output_file: str,
benchmark_version: str,
number_samples: int) -> None:
"""
Internal equivalent to assess_distribution_learning, but allows for a flexible number of samples.
To call directly only for testing.
"""
logger.info(f'Benchmarking distribution learning, version {benchmark_version}')
benchmarks = distribution_learning_benchmark_suite(chembl_file_path=chembl_training_file,
version_name=benchmark_version,
number_samples=number_samples)
results = _evaluate_distribution_learning_benchmarks(model=model, benchmarks=benchmarks)
benchmark_results: Dict[str, Any] = OrderedDict()
benchmark_results['guacamol_version'] = guacamol.__version__
benchmark_results['benchmark_suite_version'] = benchmark_version
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import json
import logging
import guacamol
from collections import OrderedDict
from typing import List, Dict, Any
from guacamol.distribution_learning_benchmark import DistributionLearningBenchmark, DistributionLearningBenchmarkResult
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from guacamol.benchmark_suites import distribution_learning_benchmark_suite
from guacamol.utils.data import get_time_string
and context (functions, classes, or occasionally code) from other files:
# Path: guacamol/distribution_learning_benchmark.py
# class DistributionLearningBenchmark:
# """
# Base class for assessing how well a model is able to generate molecules matching a molecule distribution.
#
# Derived class should implement the assess_molecules function
# """
#
# def __init__(self, name: str, number_samples: int) -> None:
# self.name = name
# self.number_samples = number_samples
#
# @abstractmethod
# def assess_model(self, model: DistributionMatchingGenerator) -> DistributionLearningBenchmarkResult:
# """
# Assess a distribution-matching generator model.
#
# Args:
# model: model to assess
# """
#
# class DistributionLearningBenchmarkResult:
# """
# Contains the results of a distribution learning benchmark.
#
# NB: timing does not make sense since training happens outside of DistributionLearningBenchmark.
# """
#
# def __init__(self, benchmark_name: str, score: float, sampling_time: float, metadata: Dict[str, Any]) -> None:
# """
# Args:
# benchmark_name: name of the distribution-learning benchmark
# score: benchmark score
# sampling_time: time for sampling the molecules in seconds
# metadata: benchmark-specific information
# """
# self.benchmark_name = benchmark_name
# self.score = score
# self.sampling_time = sampling_time
# self.metadata = metadata
#
# Path: guacamol/distribution_matching_generator.py
# class DistributionMatchingGenerator(metaclass=ABCMeta):
# """
# Interface for molecule generators.
# """
#
# @abstractmethod
# def generate(self, number_samples: int) -> List[str]:
# """
# Samples SMILES strings from a molecule generator.
#
# Args:
# number_samples: number of molecules to generate
#
# Returns:
# A list of SMILES strings.
# """
#
# Path: guacamol/benchmark_suites.py
# def distribution_learning_benchmark_suite(chembl_file_path: str,
# version_name: str,
# number_samples: int) -> List[DistributionLearningBenchmark]:
# """
# Returns a suite of benchmarks for a specified benchmark version
#
# Args:
# chembl_file_path: path to ChEMBL training set, necessary for some benchmarks
# version_name: benchmark version
#
# Returns:
# List of benchmaks
# """
#
# # For distribution-learning, v1 and v2 are identical
# if version_name == 'v1' or version_name == 'v2':
# return distribution_learning_suite_v1(chembl_file_path=chembl_file_path, number_samples=number_samples)
#
# raise Exception(f'Distribution-learning benchmark suite "{version_name}" does not exist.')
#
# Path: guacamol/utils/data.py
# def get_time_string():
# lt = time.localtime()
# return "%04d%02d%02d-%02d%02d" % (lt.tm_year, lt.tm_mon, lt.tm_mday, lt.tm_hour, lt.tm_min)
. Output only the next line. | 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_generated():
# does not raise an exception if
molecules = ['invalid' for _ in range(20)]
molecules[-1] = 'CC'
molecules[-2] = 'CN'
generator = MockGenerator(molecules)
# samples a max of 9*2 molecules and just does not sample the good ones
# in this case the list of generated molecules is empty
assert not sample_valid_molecules(generator, 2, max_tries=9)
# with a max of 10*2 molecules two valid molecules can be sampled
generator = MockGenerator(molecules)
mols = sample_valid_molecules(generator, 2)
assert mols == ['CN', 'CC']
def test_sample_unique_molecules_for_valid_only():
generator = MockGenerator(['CCCC', 'CC'])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from guacamol.utils.sampling_helpers import sample_valid_molecules, sample_unique_molecules
from .mock_generator import MockGenerator
and context:
# Path: guacamol/utils/sampling_helpers.py
# 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:
# model: model to sample from
# number_molecules: number of valid molecules to generate
# max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
#
# Returns:
# A list of number_molecules valid molecules. If this was not possible with the given max_tries, the list may be shorter.
# """
#
# max_samples = max_tries * number_molecules
# number_already_sampled = 0
#
# valid_molecules: List[str] = []
#
# while len(valid_molecules) < number_molecules and number_already_sampled < max_samples:
# remaining_to_sample = number_molecules - len(valid_molecules)
#
# samples = model.generate(remaining_to_sample)
# number_already_sampled += remaining_to_sample
#
# valid_molecules += [m for m in samples if is_valid(m)]
#
# return valid_molecules
#
# 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 molecules).
#
# Args:
# model: model to sample from
# number_molecules: number of unique (distinct) molecules to generate
# max_tries: determines the maximum number N of samples to draw, N = number_molecules * max_tries
#
# Returns:
# A list of number_molecules unique molecules, in canonalized form.
# If this was not possible with the given max_tries, the list may be shorter.
# The generation order is kept.
# """
#
# max_samples = max_tries * number_molecules
# number_already_sampled = 0
#
# unique_list: List[str] = []
# unique_set: Set[str] = set()
#
# while len(unique_list) < number_molecules and number_already_sampled < max_samples:
# remaining_to_sample = number_molecules - len(unique_list)
#
# samples = model.generate(remaining_to_sample)
# number_already_sampled += remaining_to_sample
#
# for smiles in samples:
# canonical_smiles = canonicalize(smiles)
# if canonical_smiles is not None and canonical_smiles not in unique_set:
# unique_set.add(canonical_smiles)
# unique_list.append(canonical_smiles)
#
# # this should always be True
# assert len(unique_set) == len(unique_list)
#
# return unique_list
#
# Path: tests/mock_generator.py
# class MockGenerator(DistributionMatchingGenerator):
# """
# Mock generator that returns pre-defined molecules,
# possibly split in several calls
# """
#
# def __init__(self, molecules: List[str]) -> None:
# self.molecules = molecules
# self.cursor = 0
#
# def generate(self, number_samples: int) -> List[str]:
# end = self.cursor + number_samples
#
# sampled_molecules = self.molecules[self.cursor:end]
# self.cursor = end
# return sampled_molecules
which might include code, classes, or functions. Output only the next line. | 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.MAX_MESSAGE_LENGTH:
part = text[:constants.MAX_MESSAGE_LENGTH]
first_lnbr = part.rfind('\n')
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, **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] != '.':
text += '.'
if not reply_markup:
reply_markup = ReplyKeyboardRemove()
return self.bot.sendMessage(
chat_id,
<|code_end|>
, predict the immediate next line with the help of imports:
from botlistbot.mdformat import success, failure, action_hint
from telegram import Message, constants
from telegram import ParseMode
from telegram import ReplyKeyboardRemove
from telegram.error import BadRequest
and context (classes, functions, sometimes code) from other files:
# Path: botlistbot/mdformat.py
# def success(text):
# return '{} {}'.format(Emoji.WHITE_HEAVY_CHECK_MARK, text, hide_keyboard=True)
#
# def failure(text):
# return '{} {}'.format(Emoji.CROSS_MARK, text)
#
# def action_hint(text):
# return '💬 {}'.format(text)
. Output only the next line. | 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, **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] != '.':
text += '.'
if not reply_markup:
reply_markup = ReplyKeyboardRemove()
return self.bot.sendMessage(
chat_id,
success(text),
reply_markup=reply_markup,
**self._set_defaults(kwargs))
def send_failure(self, chat_id, text: str, **kwargs):
text = str.strip(text)
if text[-1] != '.':
text += '.'
return self.bot.sendMessage(
chat_id,
<|code_end|>
using the current file's imports:
from botlistbot.mdformat import success, failure, action_hint
from telegram import Message, constants
from telegram import ParseMode
from telegram import ReplyKeyboardRemove
from telegram.error import BadRequest
and any relevant context from other files:
# Path: botlistbot/mdformat.py
# def success(text):
# return '{} {}'.format(Emoji.WHITE_HEAVY_CHECK_MARK, text, hide_keyboard=True)
#
# def failure(text):
# return '{} {}'.format(Emoji.CROSS_MARK, text)
#
# def action_hint(text):
# return '💬 {}'.format(text)
. Output only the next line. | 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] != '.':
text += '.'
if not reply_markup:
reply_markup = ReplyKeyboardRemove()
return self.bot.sendMessage(
chat_id,
success(text),
reply_markup=reply_markup,
**self._set_defaults(kwargs))
def send_failure(self, chat_id, text: str, **kwargs):
text = str.strip(text)
if text[-1] != '.':
text += '.'
return self.bot.sendMessage(
chat_id,
failure(text),
**self._set_defaults(kwargs))
def send_action_hint(self, chat_id, text: str, **kwargs):
if text[-1] == '.':
text = text[0:-1]
return self.bot.sendMessage(
chat_id,
<|code_end|>
, generate the next line using the imports in this file:
from botlistbot.mdformat import success, failure, action_hint
from telegram import Message, constants
from telegram import ParseMode
from telegram import ReplyKeyboardRemove
from telegram.error import BadRequest
and context (functions, classes, or occasionally code) from other files:
# Path: botlistbot/mdformat.py
# def success(text):
# return '{} {}'.format(Emoji.WHITE_HEAVY_CHECK_MARK, text, hide_keyboard=True)
#
# def failure(text):
# return '{} {}'.format(Emoji.CROSS_MARK, text)
#
# def action_hint(text):
# return '💬 {}'.format(text)
. Output only the next line. | 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, InlineKeyboardMarkup
from telegram.ext import ConversationHandler
from botlistbot import util
from botlistbot.const import CallbackActions
and context including class names, function names, and sometimes code from other files:
# Path: botlistbot/util.py
# def stop_banned(update, user):
# def track_groups(func):
# def wrapped(bot, update, *args, **kwargs):
# def restricted(func=None, strict=False, silent=False):
# def wrapped(bot, update, *args, **kwargs):
# def private_chat_only(func):
# def wrapped(bot, update, *args, **kwargs):
# def timeit(method):
# def timed(*args, **kw):
# def build_menu(buttons: List,
# n_cols,
# header_buttons: List = None,
# footer_buttons: List = None):
# def cid_from_update(update):
# def uid_from_update(update):
# def encode_base64(query):
# def callback_for_action(action, params=None):
# def callback_data_from_update(update):
# def is_group_message(update):
# def is_private_message(update):
# def original_reply_id(update):
# def is_inline_message(update):
# def message_text_from_update(update):
# def mid_from_update(update):
# def escape_markdown(text):
# def callback_str_from_dict(d):
# def wait(bot, update, t=1.5):
# def order_dict_lexi(d):
# def private_or_else_group_message(bot, chat_id, text):
# def send_or_edit_md_message(bot, chat_id, text, to_edit=None, **kwargs):
# def send_md_message(bot, chat_id, text: str, **kwargs):
# def send_message_success(bot, chat_id, text: str, add_punctuation=True, reply_markup=None, **kwargs):
# def send_message_failure(bot, chat_id, text: str, **kwargs):
# def send_action_hint(bot, chat_id, text: str, **kwargs):
# def success(text):
# def failure(text):
# def action_hint(text):
. Output only the next line. | 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 appglobals
from botlistbot import settings
from logzero import logger as log
from botcheckerworker.botchecker import BotChecker
from botcheckerworker.user_account_repository import download_session)
and context including class names, function names, or small code snippets from other files:
# Path: botlistbot/appglobals.py
# ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# ACCOUNTS_DIR = Path(ROOT_DIR) / "accounts"
# DATABASE_PATH = config('DATABASE_URL')
#
# Path: botlistbot/settings.py
# DEV = config("DEV", default=False, cast=bool)
# PORT = config("PORT", default=8443, cast=int)
# BOT_TOKEN = config("BOT_TOKEN", cast=lambda v: str(v) if v else None, default=None) or (
# str(sys.argv[1]) if len(sys.argv) > 1 else None
# )
# LOG_DIR = config("LOG_DIR", default=os.path.dirname(os.path.abspath(__file__)))
# BOT_THUMBNAIL_DIR = config(
# "BOT_THUMBNAIL_DIR",
# default="./bot-profile-pictures",
# )
# ADMINS = [
# 62056065, # JosXa
# 918962, # T3CHNO
# 522605269, # n9ghtLY
# ]
# MODERATORS = [
# 7679610, # Fabian Pastor
# 278941742, # riccardo
# 317434635, # jfowl
# 691609650, # Lulzx
# 200344026, # the scientist
# 234480941, # the one and only twitface
# ] + ADMINS
# DEVELOPER_ID = config("DEVELOPER_ID", default=62056065)
# BOT_CONSIDERED_NEW = 1 # Revision difference
# WORKER_COUNT = 5 if DEV else 40
# TEST_BOT_NAME = "gottesgebot"
# LIVE_BOT_NAME = "botlistbot"
# SELF_BOT_NAME = TEST_BOT_NAME if DEV else LIVE_BOT_NAME
# SELF_BOT_ID = "182355371" if DEV else "265482650"
# TEST_GROUP_ID = -1001118582923 # Area 51
# BOTLIST_NOTIFICATIONS_ID = -1001175567094 if DEV else -1001074366879
# BOTLISTCHAT_ID = TEST_GROUP_ID if DEV else -1001067163791
# BLSF_ID = TEST_GROUP_ID if DEV else -1001098339113
# SELF_CHANNEL_USERNAME = "botlist_testchannel" if DEV else "botlist"
# REGEX_BOT_IN_TEXT = r".*(@[a-zA-Z0-9_]{3,31}).*"
# REGEX_BOT_ONLY = r"(@[a-zA-Z0-9_]{3,31})"
# PAGE_SIZE_SUGGESTIONS_LIST = 5
# PAGE_SIZE_BOT_APPROVAL = 5
# MAX_SEARCH_RESULTS = 25
# MAX_BOTS_PER_MESSAGE = 140
# BOT_ACCEPTED_IDLE_TIME = 2 # minutes
# SUGGESTION_LIMIT = 25
# API_URL = "localhost" if DEV else "josxa.jumpingcrab.com"
# API_PORT = 6060
# RUN_BOTCHECKER = config("RUN_BOTCHECKER", True, cast=bool)
# USE_USERBOT = RUN_BOTCHECKER
# API_ID = config("API_ID", cast=lambda v: int(v) if v else None, default=None)
# API_HASH = config("API_HASH", default=None)
# USERBOT_SESSION = config("USERBOT_SESSION", default=None)
# USERBOT_PHONE = config("USERBOT_PHONE", default=None)
# PING_MESSAGES = ["/start", "/help"]
# PING_INLINEQUERIES = ["", "abc", "/test"]
# BOTCHECKER_CONCURRENT_COUNT = 20
# BOTCHECKER_INTERVAL = 3600 * 3
# DELETE_CONVERSATION_AFTER_PING = config(
# "DELETE_CONVERSATIONS_AFTER_PING", True, cast=bool
# )
# NOTIFY_NEW_PROFILE_PICTURE = not DEV
# DOWNLOAD_PROFILE_PICTURES = config("DOWNLOAD_PROFILE_PICTURES", True, cast=bool)
# DISABLE_BOT_INACTIVITY_DELTA = timedelta(days=15)
# OFFLINE_DETERMINERS = [
# "under maintenance",
# "bot turned off",
# "bot parked",
# "offline for maintenance",
# ]
# BOTBUILDER_DETERMINERS = [
# "use /off to pause your subscription",
# "use /stop to unsubscribe",
# "manybot",
# "chatfuelbot",
# ]
# FORBIDDEN_KEYWORDS = config("FORBIDDEN_KEYWORDS", cast=Csv(), default=[])
# SENTRY_URL = config("SENTRY_URL", default=None)
# SENTRY_ENVIRONMENT = config("SENTRY_ENVIRONMENT", default=None)
# DEBUG_LOG_FILE = "botlistbot.log"
# BOTLIST_REQUESTS_CHANNEL = None
# BOT_UNDER_TEST = TEST_BOT_NAME if DEV else LIVE_BOT_NAME
# TEST_USERBOT_PHONE = config("TEST_USERBOT_PHONE", default=None)
# TEST_USERBOT_SESSION = config("TEST_USERBOT_SESSION", default=None)
# TEST_GROUP_ID = 1118582923
# def is_sentry_enabled() -> bool:
. Output only the next line. | 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.")
def download_session(session_name: str, output_path: Path) -> str:
session_name = session_name.replace(".session", "") + ".session"
session = client.get_object(BUCKET_NAME, session_name)
out_path = str(output_path / session_name)
with open(out_path, 'wb') as file_data:
for d in session.stream(32 * 1024):
file_data.write(d)
log.info(f"Downloaded session '{session_name}' to '{output_path}'.")
return out_path
<|code_end|>
. Use current file imports:
(import os
from pathlib import Path
from logzero import logger as log
from decouple import config
from minio import Minio
from botlistbot import appglobals)
and context including class names, function names, or small code snippets from other files:
# Path: botlistbot/appglobals.py
# ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# ACCOUNTS_DIR = Path(ROOT_DIR) / "accounts"
# DATABASE_PATH = config('DATABASE_URL')
. Output only the next line. | 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 rules for keywords apply:
▫️Keep the keywords as short as possible
▫️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 tag #share if the bot has a dedicated 'Share' button)
▫Tag bots made with _bot creators_ (e.g. #manybot, #chatfuelbot)
▫Use #related if the bot is not standalone, but needs another application to work properly, e.g. an Android App
▫Always think in the perspective of a user in need of a bot. What query might he be putting in the search field?
"""
NEW_BOTS_INLINEQUERY = "New Bots"
SELECT_CATEGORY = "Please select a category"
SHOW_IN_CATEGORY = "Show category"
REROUTE_PRIVATE_CHAT = mdformat.action_hint("Please use this command in a private chat or make use of inlinequeries.")
BOTLISTCHAT_RULES = """*Here are the rules for @BotListChat:*\n\nShare your bots, comment, test and have fun😜👍
Rules: Speak in English, Don't spam/advertise channels or groups that aren't bot related, respect other members, use common sense. 🤖
⭐️⭐️⭐️⭐️⭐️
[Give @BotList a rating](https://goo.gl/rtSs5B)"""
BAN_MESSAGE = mdformat.action_hint("Please send me the username to ban and remove all bot submissions")
UNBAN_MESSAGE = mdformat.action_hint("Please send me the username of the user to revoke ban state for")
<|code_end|>
using the current file's imports:
import random
from botlistbot import captions
from botlistbot import mdformat
from botlistbot.dialog import emojis
and any relevant context from other files:
# Path: botlistbot/captions.py
# TEST = "{} Test".format(Emoji.ANCHOR)
# BACK_TO_MENU = "{} Back to Menu".format(Emoji.LEFTWARDS_BLACK_ARROW)
# EXIT = "🔙 Exit"
# REFRESH = "🔄 Refresh"
# ADD_BOT = "➕ Add new bot"
# EDIT_BOT = "🛠 Edit Bot"
# SEND_BOTLIST = "☑ Update BotList"
# SEND_ACTIVITY_LOGS = "Activity Logs"
# BACK = "{} Back".format(Emoji.BACK_WITH_LEFTWARDS_ARROW_ABOVE)
# BACK_TO_CATEGORY = "{} to Category".format(Emoji.BACK_WITH_LEFTWARDS_ARROW_ABOVE)
# APPROVE_BOTS = "Approve Bots"
# SEND_CONFIG_FILES = "Runtime Files"
# FIND_OFFLINE = "Find Offline Bots"
# APPROVE_SUGGESTIONS = "Approve Suggestions"
# PENDING_UPDATE = "Pending Bots"
# SUGGESTION_PENDING_EMOJI = "👓"
# CHANGE_SUGGESTION = "📝 Make Changes"
# DONE = "🔚 Done"
# SHARE = "Share"
# CATEGORIES = "📚 Categories"
# EXPLORE = "🔄 Explore"
# NEW_BOTS = "🆕 New Bots"
# SEARCH = "🔎 Search"
# CONTRIBUTING = "📤 Contributing"
# EXAMPLES = "📝 Examples"
# HELP = "❔ Help"
# ADMIN_MENU = "🛃 Admin Menu"
# SWITCH_PRIVATE = "📖️ Continue in private"
# FAVORITES = "💖 My Favorites"
# ADD_FAVORITE = "➕ Add"
# REMOVE_FAVORITE = "➖ Remove"
# REMOVE_FAVORITE_VERBOSE = "➖ Remove from 💖 Favorites"
# ADD_TO_FAVORITES = "Add to 💖 Favorites"
# PIN = "📍 Pin"
# def random_done_delete():
#
# Path: botlistbot/mdformat.py
# MAX_LINE_CHARACTERS = 31
# SMALLCAPS_CHARS = 'ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ'
# SPEC = '̶'
# EMOJI_NUMBERS = '0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣'
# def smallcaps(text):
# def strikethrough(text: str):
# def results_list(args, prefix=''):
# def number_as_emoji(n):
# def centered(text):
# def success(text):
# def love(text):
# def failure(text):
# def action_hint(text):
# def none_action(text):
#
# Path: botlistbot/dialog/emojis.py
# RECOMMEND_MODERATOR = '👥🔀'
. Output only the next line. | 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 information, please ask in the @BotListChat."""
REJECTION_PRIVATE_MESSAGE = """Sorry, but your bot submission {} was rejected.
It does not suffice the standards we impose for inclusion in the @BotList for one of the following reasons:
▫️A better bot with the same functionality is already in the @BotList.
▫️The user interface is bad in terms of usability and/or simplicity.
▫The bot is still in an early development stage
▫️Contains ads or exclusively adult content
▫️English language not supported per default (exceptions are possible)
▫NO MANYBOTS!!! 👺
For further information, please ask in the @BotListChat."""
ACCEPTANCE_PRIVATE_MESSAGE = """Congratulations, your bot submission {} has been accepted for the @BotList. You will be able to see it shortly by using the /category command, and it is going to be in the @BotList in the next two weeks.\n\nCategory: {}"""
BOTLIST_UPDATE_NOTIFICATION = """⚠️@BotList *update!*
There are {n_bots} new bots:
{new_bots}
Share your bots in @BotListChat"""
<|code_end|>
, determine the next line of code. You have imports:
import random
from botlistbot import captions
from botlistbot import mdformat
from botlistbot.dialog import emojis
and context (class names, function names, or code) available:
# Path: botlistbot/captions.py
# TEST = "{} Test".format(Emoji.ANCHOR)
# BACK_TO_MENU = "{} Back to Menu".format(Emoji.LEFTWARDS_BLACK_ARROW)
# EXIT = "🔙 Exit"
# REFRESH = "🔄 Refresh"
# ADD_BOT = "➕ Add new bot"
# EDIT_BOT = "🛠 Edit Bot"
# SEND_BOTLIST = "☑ Update BotList"
# SEND_ACTIVITY_LOGS = "Activity Logs"
# BACK = "{} Back".format(Emoji.BACK_WITH_LEFTWARDS_ARROW_ABOVE)
# BACK_TO_CATEGORY = "{} to Category".format(Emoji.BACK_WITH_LEFTWARDS_ARROW_ABOVE)
# APPROVE_BOTS = "Approve Bots"
# SEND_CONFIG_FILES = "Runtime Files"
# FIND_OFFLINE = "Find Offline Bots"
# APPROVE_SUGGESTIONS = "Approve Suggestions"
# PENDING_UPDATE = "Pending Bots"
# SUGGESTION_PENDING_EMOJI = "👓"
# CHANGE_SUGGESTION = "📝 Make Changes"
# DONE = "🔚 Done"
# SHARE = "Share"
# CATEGORIES = "📚 Categories"
# EXPLORE = "🔄 Explore"
# NEW_BOTS = "🆕 New Bots"
# SEARCH = "🔎 Search"
# CONTRIBUTING = "📤 Contributing"
# EXAMPLES = "📝 Examples"
# HELP = "❔ Help"
# ADMIN_MENU = "🛃 Admin Menu"
# SWITCH_PRIVATE = "📖️ Continue in private"
# FAVORITES = "💖 My Favorites"
# ADD_FAVORITE = "➕ Add"
# REMOVE_FAVORITE = "➖ Remove"
# REMOVE_FAVORITE_VERBOSE = "➖ Remove from 💖 Favorites"
# ADD_TO_FAVORITES = "Add to 💖 Favorites"
# PIN = "📍 Pin"
# def random_done_delete():
#
# Path: botlistbot/mdformat.py
# MAX_LINE_CHARACTERS = 31
# SMALLCAPS_CHARS = 'ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ'
# SPEC = '̶'
# EMOJI_NUMBERS = '0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣'
# def smallcaps(text):
# def strikethrough(text: str):
# def results_list(args, prefix=''):
# def number_as_emoji(n):
# def centered(text):
# def success(text):
# def love(text):
# def failure(text):
# def action_hint(text):
# def none_action(text):
#
# Path: botlistbot/dialog/emojis.py
# RECOMMEND_MODERATOR = '👥🔀'
. Output only the next line. | 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 tag #share if the bot has a dedicated 'Share' button)
▫Tag bots made with _bot creators_ (e.g. #manybot, #chatfuelbot)
▫Use #related if the bot is not standalone, but needs another application to work properly, e.g. an Android App
▫Always think in the perspective of a user in need of a bot. What query might he be putting in the search field?
"""
NEW_BOTS_INLINEQUERY = "New Bots"
SELECT_CATEGORY = "Please select a category"
SHOW_IN_CATEGORY = "Show category"
REROUTE_PRIVATE_CHAT = mdformat.action_hint("Please use this command in a private chat or make use of inlinequeries.")
BOTLISTCHAT_RULES = """*Here are the rules for @BotListChat:*\n\nShare your bots, comment, test and have fun😜👍
Rules: Speak in English, Don't spam/advertise channels or groups that aren't bot related, respect other members, use common sense. 🤖
⭐️⭐️⭐️⭐️⭐️
[Give @BotList a rating](https://goo.gl/rtSs5B)"""
BAN_MESSAGE = mdformat.action_hint("Please send me the username to ban and remove all bot submissions")
UNBAN_MESSAGE = mdformat.action_hint("Please send me the username of the user to revoke ban state for")
FAVORITES_HEADLINE = "*{}* 🔽\n_┌ from_ @BotList".format(captions.FAVORITES)
ADD_FAVORITE = mdformat.action_hint("Please send me the @username of a bot to add to your favorites")
BOTPROPERTY_STARTSWITH = "Please send me a "
SET_BOTPROPERTY = "Please send me a {} for {} ― `{}` to clear"
SELECT_BOT_TO_ACCEPT = f"""Please select a bot you want to accept for the BotList.
👍 Accept with notification
👎 Reject with notification
🗑 Drop without notice
<|code_end|>
. Write the next line using the current file imports:
import random
from botlistbot import captions
from botlistbot import mdformat
from botlistbot.dialog import emojis
and context from other files:
# Path: botlistbot/captions.py
# TEST = "{} Test".format(Emoji.ANCHOR)
# BACK_TO_MENU = "{} Back to Menu".format(Emoji.LEFTWARDS_BLACK_ARROW)
# EXIT = "🔙 Exit"
# REFRESH = "🔄 Refresh"
# ADD_BOT = "➕ Add new bot"
# EDIT_BOT = "🛠 Edit Bot"
# SEND_BOTLIST = "☑ Update BotList"
# SEND_ACTIVITY_LOGS = "Activity Logs"
# BACK = "{} Back".format(Emoji.BACK_WITH_LEFTWARDS_ARROW_ABOVE)
# BACK_TO_CATEGORY = "{} to Category".format(Emoji.BACK_WITH_LEFTWARDS_ARROW_ABOVE)
# APPROVE_BOTS = "Approve Bots"
# SEND_CONFIG_FILES = "Runtime Files"
# FIND_OFFLINE = "Find Offline Bots"
# APPROVE_SUGGESTIONS = "Approve Suggestions"
# PENDING_UPDATE = "Pending Bots"
# SUGGESTION_PENDING_EMOJI = "👓"
# CHANGE_SUGGESTION = "📝 Make Changes"
# DONE = "🔚 Done"
# SHARE = "Share"
# CATEGORIES = "📚 Categories"
# EXPLORE = "🔄 Explore"
# NEW_BOTS = "🆕 New Bots"
# SEARCH = "🔎 Search"
# CONTRIBUTING = "📤 Contributing"
# EXAMPLES = "📝 Examples"
# HELP = "❔ Help"
# ADMIN_MENU = "🛃 Admin Menu"
# SWITCH_PRIVATE = "📖️ Continue in private"
# FAVORITES = "💖 My Favorites"
# ADD_FAVORITE = "➕ Add"
# REMOVE_FAVORITE = "➖ Remove"
# REMOVE_FAVORITE_VERBOSE = "➖ Remove from 💖 Favorites"
# ADD_TO_FAVORITES = "Add to 💖 Favorites"
# PIN = "📍 Pin"
# def random_done_delete():
#
# Path: botlistbot/mdformat.py
# MAX_LINE_CHARACTERS = 31
# SMALLCAPS_CHARS = 'ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ'
# SPEC = '̶'
# EMOJI_NUMBERS = '0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣'
# def smallcaps(text):
# def strikethrough(text: str):
# def results_list(args, prefix=''):
# def number_as_emoji(n):
# def centered(text):
# def success(text):
# def love(text):
# def failure(text):
# def action_hint(text):
# def none_action(text):
#
# Path: botlistbot/dialog/emojis.py
# RECOMMEND_MODERATOR = '👥🔀'
, which may include functions, classes, or code. Output only the next line. | {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_column('bot', 'revision', revision),
)
<|code_end|>
, predict the next line using imports from the current file:
import os
from decouple import config
from playhouse.migrate import SqliteMigrator, IntegerField, migrate
from playhouse.sqlite_ext import SqliteExtDatabase
from botlistbot.models.revision import Revision
and context including class names, function names, and sometimes code from other files:
# Path: botlistbot/models/revision.py
# class Revision(BaseModel):
# nr = IntegerField(default=1)
# _instance = None
#
# @property
# def next(self):
# return self.nr + 1
#
# @staticmethod
# def get_instance() -> 'Revision':
# if not Revision._instance:
# selection = list(Revision.select())
# assert len(selection) == 1
# Revision._instance = selection[0]
# return Revision._instance
. Output only the next line. | 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
and context (classes, functions, or code) from other files:
# Path: botlistbot/settings.py
# DEV = config("DEV", default=False, cast=bool)
# PORT = config("PORT", default=8443, cast=int)
# BOT_TOKEN = config("BOT_TOKEN", cast=lambda v: str(v) if v else None, default=None) or (
# str(sys.argv[1]) if len(sys.argv) > 1 else None
# )
# LOG_DIR = config("LOG_DIR", default=os.path.dirname(os.path.abspath(__file__)))
# BOT_THUMBNAIL_DIR = config(
# "BOT_THUMBNAIL_DIR",
# default="./bot-profile-pictures",
# )
# ADMINS = [
# 62056065, # JosXa
# 918962, # T3CHNO
# 522605269, # n9ghtLY
# ]
# MODERATORS = [
# 7679610, # Fabian Pastor
# 278941742, # riccardo
# 317434635, # jfowl
# 691609650, # Lulzx
# 200344026, # the scientist
# 234480941, # the one and only twitface
# ] + ADMINS
# DEVELOPER_ID = config("DEVELOPER_ID", default=62056065)
# BOT_CONSIDERED_NEW = 1 # Revision difference
# WORKER_COUNT = 5 if DEV else 40
# TEST_BOT_NAME = "gottesgebot"
# LIVE_BOT_NAME = "botlistbot"
# SELF_BOT_NAME = TEST_BOT_NAME if DEV else LIVE_BOT_NAME
# SELF_BOT_ID = "182355371" if DEV else "265482650"
# TEST_GROUP_ID = -1001118582923 # Area 51
# BOTLIST_NOTIFICATIONS_ID = -1001175567094 if DEV else -1001074366879
# BOTLISTCHAT_ID = TEST_GROUP_ID if DEV else -1001067163791
# BLSF_ID = TEST_GROUP_ID if DEV else -1001098339113
# SELF_CHANNEL_USERNAME = "botlist_testchannel" if DEV else "botlist"
# REGEX_BOT_IN_TEXT = r".*(@[a-zA-Z0-9_]{3,31}).*"
# REGEX_BOT_ONLY = r"(@[a-zA-Z0-9_]{3,31})"
# PAGE_SIZE_SUGGESTIONS_LIST = 5
# PAGE_SIZE_BOT_APPROVAL = 5
# MAX_SEARCH_RESULTS = 25
# MAX_BOTS_PER_MESSAGE = 140
# BOT_ACCEPTED_IDLE_TIME = 2 # minutes
# SUGGESTION_LIMIT = 25
# API_URL = "localhost" if DEV else "josxa.jumpingcrab.com"
# API_PORT = 6060
# RUN_BOTCHECKER = config("RUN_BOTCHECKER", True, cast=bool)
# USE_USERBOT = RUN_BOTCHECKER
# API_ID = config("API_ID", cast=lambda v: int(v) if v else None, default=None)
# API_HASH = config("API_HASH", default=None)
# USERBOT_SESSION = config("USERBOT_SESSION", default=None)
# USERBOT_PHONE = config("USERBOT_PHONE", default=None)
# PING_MESSAGES = ["/start", "/help"]
# PING_INLINEQUERIES = ["", "abc", "/test"]
# BOTCHECKER_CONCURRENT_COUNT = 20
# BOTCHECKER_INTERVAL = 3600 * 3
# DELETE_CONVERSATION_AFTER_PING = config(
# "DELETE_CONVERSATIONS_AFTER_PING", True, cast=bool
# )
# NOTIFY_NEW_PROFILE_PICTURE = not DEV
# DOWNLOAD_PROFILE_PICTURES = config("DOWNLOAD_PROFILE_PICTURES", True, cast=bool)
# DISABLE_BOT_INACTIVITY_DELTA = timedelta(days=15)
# OFFLINE_DETERMINERS = [
# "under maintenance",
# "bot turned off",
# "bot parked",
# "offline for maintenance",
# ]
# BOTBUILDER_DETERMINERS = [
# "use /off to pause your subscription",
# "use /stop to unsubscribe",
# "manybot",
# "chatfuelbot",
# ]
# FORBIDDEN_KEYWORDS = config("FORBIDDEN_KEYWORDS", cast=Csv(), default=[])
# SENTRY_URL = config("SENTRY_URL", default=None)
# SENTRY_ENVIRONMENT = config("SENTRY_ENVIRONMENT", default=None)
# DEBUG_LOG_FILE = "botlistbot.log"
# BOTLIST_REQUESTS_CHANNEL = None
# BOT_UNDER_TEST = TEST_BOT_NAME if DEV else LIVE_BOT_NAME
# TEST_USERBOT_PHONE = config("TEST_USERBOT_PHONE", default=None)
# TEST_USERBOT_SESSION = config("TEST_USERBOT_SESSION", default=None)
# TEST_GROUP_ID = 1118582923
# def is_sentry_enabled() -> bool:
. Output only the next line. | 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")
assert os.path.exists(location)
assert os.path.exists(base_location)
assert os.path.exists(black_screen)
base_img = cv2.imread(base_location)
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from bot.providers import trainer_matches as tm
from bot.shared import LOW_CORR
import os
import cv2
and context (functions, classes, or occasionally code) from other files:
# Path: bot/providers/trainer_matches.py
# class Trainer(object):
# class BoundingTrainer(Trainer):
# def __init__(self, query, x=0, y=0):
# def get_matches(self, train, corr):
# def compare_distances(self, train_img, cluster, good_matches):
# def debug_matcher(self, img):
# def read_captured_circles(self):
# def capture_white_circles(self, x_limit=480, y_limit=670):
# def draw_circles(self, circles, cimg):
# def prep_for_white_circles(self):
# def compare(self):
# def show_area(x, y, image):
# def __init__(self, query, x=0, y=0, w=0, h=0, bounding_area=None, blacklist=None):
# def in_box(self, x, y):
# def in_blacklist(self, x, y):
# def get_matches(self, train, corr):
# def capture_white_circles(self):
# def show_area(x, y, w, h, image):
# def show_area_bounded(bounding_area, image):
#
# Path: bot/shared.py
# LOW_CORR = 2
. Output only the next line. | 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")
assert os.path.exists(location)
assert os.path.exists(base_location)
assert os.path.exists(black_screen)
base_img = cv2.imread(base_location)
trainer = tm.Trainer(base_img, 480, 50)
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from bot.providers import trainer_matches as tm
from bot.shared import LOW_CORR
import os
import cv2)
and context including class names, function names, or small code snippets from other files:
# Path: bot/providers/trainer_matches.py
# class Trainer(object):
# class BoundingTrainer(Trainer):
# def __init__(self, query, x=0, y=0):
# def get_matches(self, train, corr):
# def compare_distances(self, train_img, cluster, good_matches):
# def debug_matcher(self, img):
# def read_captured_circles(self):
# def capture_white_circles(self, x_limit=480, y_limit=670):
# def draw_circles(self, circles, cimg):
# def prep_for_white_circles(self):
# def compare(self):
# def show_area(x, y, image):
# def __init__(self, query, x=0, y=0, w=0, h=0, bounding_area=None, blacklist=None):
# def in_box(self, x, y):
# def in_blacklist(self, x, y):
# def get_matches(self, train, corr):
# def capture_white_circles(self):
# def show_area(x, y, w, h, image):
# def show_area_bounded(bounding_area, image):
#
# Path: bot/shared.py
# LOW_CORR = 2
. Output only the next line. | 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.white_query, cv2.COLOR_BGR2GRAY)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 40,
param1=50, param2=30, minRadius=5, maxRadius=60)
if circles is None:
return
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
if i[0] <= x_limit and i[1] <= y_limit:
self.circlePoints.append((i[0], i[1]))
if self._debug:
self.draw_circles(circles, cimg)
def draw_circles(self, circles, cimg):
for i in circles[0, :]:
# draw the outer circle
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
# draw the center of the circle
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
self.images.append(cimg)
def prep_for_white_circles(self):
lower, upper = ([215, 215, 215], [255, 255, 255])
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import cv2
import os
from matplotlib import pyplot as plt
from bot.common import mask_image
from sklearn.cluster import KMeans
from sklearn.metrics.pairwise import euclidean_distances
and context (functions, classes, or occasionally code) from other files:
# Path: bot/common.py
# def mask_image(lower_mask, upper_mask, img, apply_mask=False):
# """" Masks an image according to the upper and lower bounds
# Parameters
# ----------
# lower_mask : ndarray
# lower mask to apply to image, length must match image channels
# upper_mask : ndarray
# upper mask to apply to image, length must match image channels
# img : ndarray
# image to apply mask to
# apply_mask : bool
# returns the masked image instead of the mask itself
# """
# shape = np.array(img.shape).flatten()
# if len(np.array(img.shape).flatten()) == 3:
# shape_size = shape[-1]
# else:
# shape_size = 1
# assert (len(lower_mask) == shape_size)
# assert (len(upper_mask) == shape_size)
# color_min = np.array(lower_mask, np.uint8)
# color_max = np.array(upper_mask, np.uint8)
# new_img = cv2.inRange(img, color_min, color_max)
# if apply_mask:
# return cv2.bitwise_and(img, img, mask=new_img)
# return new_img
. Output only the next line. | 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', 'assets'))
window.show()
def handler(signum, frame):
if signum == signal.SIGINT:
window.__quit__()
logger.info("Exiting Yugioh-DuelLinks Bots")
signal.signal(signal.SIGINT, handler)
def inmain():
return app.exec_()
sys.exit(inmain())
@click.command()
def version():
print("Using {}".format(bot.__version__))
@click.command()
def setup():
<|code_end|>
using the current file's imports:
import logging
import logging.config
import os
import signal
import sip
import sys
import time
import traceback
import click
import yaml
import sys
import bot
from apscheduler.schedulers.background import BackgroundScheduler
from install import set_pip_test, main_install
from bot.duel_links_runtime import DuelLinkRunTime
from bot import logger
from bot.providers import get_provider
from bot.utils.common import make_config_file
from bot import logger
from bot.utils.common import make_config_file, default_config
from PyQt5.QtWidgets import QSystemTrayIcon
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QApplication
from bot.utils.common import make_config_file, default_config
from bot.duel_links_runtime import DuelLinkRunTime
from bot.dl_gui import DuelLinksGui
from bot import logger
and any relevant context from other files:
# Path: install.py
# def set_pip_test(value):
# global SKIP_PIP_TEST
# SKIP_PIP_TEST = value
#
# def main_install():
# print(Back.CYAN + Style.BRIGHT + warning)
# print(Back.CYAN + "Installing Required components to get this bot up and running")
# for index, command in enumerate(commands):
# print(Back.CYAN + "Component {}: {}{}".format(index, Fore.RED, command[0]) + Fore.WHITE)
# command_runner(command[1])
. Output only the next line. | 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.show()
def handler(signum, frame):
if signum == signal.SIGINT:
window.__quit__()
logger.info("Exiting Yugioh-DuelLinks Bots")
signal.signal(signal.SIGINT, handler)
def inmain():
return app.exec_()
sys.exit(inmain())
@click.command()
def version():
print("Using {}".format(bot.__version__))
@click.command()
def setup():
set_pip_test(True)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import logging.config
import os
import signal
import sip
import sys
import time
import traceback
import click
import yaml
import sys
import bot
from apscheduler.schedulers.background import BackgroundScheduler
from install import set_pip_test, main_install
from bot.duel_links_runtime import DuelLinkRunTime
from bot import logger
from bot.providers import get_provider
from bot.utils.common import make_config_file
from bot import logger
from bot.utils.common import make_config_file, default_config
from PyQt5.QtWidgets import QSystemTrayIcon
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QApplication
from bot.utils.common import make_config_file, default_config
from bot.duel_links_runtime import DuelLinkRunTime
from bot.dl_gui import DuelLinksGui
from bot import logger
and context (classes, functions, sometimes code) from other files:
# Path: install.py
# def set_pip_test(value):
# global SKIP_PIP_TEST
# SKIP_PIP_TEST = value
#
# def main_install():
# print(Back.CYAN + Style.BRIGHT + warning)
# print(Back.CYAN + "Installing Required components to get this bot up and running")
# for index, command in enumerate(commands):
# print(Back.CYAN + "Component {}: {}{}".format(index, Fore.RED, command[0]) + Fore.WHITE)
# command_runner(command[1])
. Output only the next line. | 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 DuelLinkRunTimeOptions
from bot.utils.data import read_json_file, write_data_file
and context from other files:
# Path: bot/duel_links_runtime.py
# class DuelLinkRunTimeOptions(object):
# """Class defines options used at runtime"""
# _active = False
#
# @property
# def active(self):
# return self._active
#
# @active.setter
# def active(self, value):
# self._active = True
#
# _last_run_at = datetime.datetime.fromtimestamp(default_timestamp)
#
# @property
# def last_run_at(self):
# return self._last_run_at
#
# @last_run_at.setter
# def last_run_at(self, value):
# if not isinstance(value, datetime.datetime):
# self.runtime_error_options("last_run_at", datetime.datetime, type(value))
# return
# if self._last_run_at == value:
# return
# self._last_run_at = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified to {}".format(inspect.getframeinfo(frame).function, value))
# self.timeout_dump()
#
# _next_run_at = datetime.datetime.fromtimestamp(default_timestamp)
#
# @property
# def next_run_at(self):
# return self._next_run_at
#
# @next_run_at.setter
# def next_run_at(self, value):
# if not isinstance(value, datetime.datetime):
# self.runtime_error_options("next_run_at", datetime.datetime, type(value))
# return
# if self._next_run_at == value:
# return
# self._next_run_at = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified to {}".format(inspect.getframeinfo(frame).function, value))
# self.timeout_dump()
# self.handle_option_change('next_run_at')
#
# _run_now = False
#
# @property
# def run_now(self):
# return self._run_now
#
# @run_now.setter
# def run_now(self, value):
# if not isinstance(value, bool):
# self.runtime_error_options("run_now", bool, type(value))
# return
# if self._run_now == value:
# return
# self._run_now = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('run_now')
#
# _stop = threading.Event()
#
# @property
# def stop(self):
# return self._stop.is_set()
#
# @stop.setter
# def stop(self, stop):
# if not isinstance(stop, bool):
# self.runtime_error_options("stop", bool, type(stop))
# return
# if self._stop == stop:
# return
# if stop:
# self._stop.set()
# else:
# self._stop.clear()
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('stop')
#
# _playmode = "autoplay"
# _available_modes = ['autoplay', 'guided']
#
# @property
# def playmode(self):
# return self._playmode
#
# @playmode.setter
# def playmode(self, playmode):
# if not isinstance(playmode, str):
# self.runtime_error_options("playmode", str, type(playmode))
# return
# if playmode not in self._available_modes:
# return
# if self._playmode == playmode:
# return
# self._playmode = playmode
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('playmode')
#
# _battle_calls = {
# "beforeStart": [],
# "afterStart" : [],
# "beforeEnd" : [],
# "afterEnd" : []
# }
#
# @property
# def battle_calls(self):
# return self._battle_calls
#
# @battle_calls.setter
# def battle_calls(self, value):
# if not isinstance(value, dict):
# self.runtime_error_options("battle_calls", dict, type(value))
# return
# if self._battle_calls == value:
# return
# self._battle_calls = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('battle_calls')
#
# @abstractmethod
# def runtime_error_options(self, option, expecting_type, got_type):
# raise NotImplementedError("runtime_error_options not implemented")
#
# @abstractmethod
# def timeout_dump(self):
# raise NotImplementedError("timeout_dump not implemented")
#
# @abstractmethod
# def handle_option_change(self, value):
# raise NotImplementedError("handle_option_change not implemented")
#
# Path: bot/utils/data.py
# def read_json_file(file=data_file):
# try:
# with open(file) as f:
# data = json.load(f, object_hook=date_hook)
# return data
# except FileNotFoundError:
# return None
#
# def write_data_file(data, file=data_file):
# with open(file, 'w') as f:
# json.dump(data, f, sort_keys=True,
# indent=4, separators=(',', ': '), default=datetime_handler)
, which may include functions, classes, or code. Output only the next line. | 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()
self.runtimeoptions.run_now = True
self.runtimeoptions.dump()
<|code_end|>
with the help of current file imports:
from unittest import TestCase
from bot.duel_links_runtime import DuelLinkRunTimeOptions
from bot.utils.data import read_json_file, write_data_file
and context from other files:
# Path: bot/duel_links_runtime.py
# class DuelLinkRunTimeOptions(object):
# """Class defines options used at runtime"""
# _active = False
#
# @property
# def active(self):
# return self._active
#
# @active.setter
# def active(self, value):
# self._active = True
#
# _last_run_at = datetime.datetime.fromtimestamp(default_timestamp)
#
# @property
# def last_run_at(self):
# return self._last_run_at
#
# @last_run_at.setter
# def last_run_at(self, value):
# if not isinstance(value, datetime.datetime):
# self.runtime_error_options("last_run_at", datetime.datetime, type(value))
# return
# if self._last_run_at == value:
# return
# self._last_run_at = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified to {}".format(inspect.getframeinfo(frame).function, value))
# self.timeout_dump()
#
# _next_run_at = datetime.datetime.fromtimestamp(default_timestamp)
#
# @property
# def next_run_at(self):
# return self._next_run_at
#
# @next_run_at.setter
# def next_run_at(self, value):
# if not isinstance(value, datetime.datetime):
# self.runtime_error_options("next_run_at", datetime.datetime, type(value))
# return
# if self._next_run_at == value:
# return
# self._next_run_at = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified to {}".format(inspect.getframeinfo(frame).function, value))
# self.timeout_dump()
# self.handle_option_change('next_run_at')
#
# _run_now = False
#
# @property
# def run_now(self):
# return self._run_now
#
# @run_now.setter
# def run_now(self, value):
# if not isinstance(value, bool):
# self.runtime_error_options("run_now", bool, type(value))
# return
# if self._run_now == value:
# return
# self._run_now = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('run_now')
#
# _stop = threading.Event()
#
# @property
# def stop(self):
# return self._stop.is_set()
#
# @stop.setter
# def stop(self, stop):
# if not isinstance(stop, bool):
# self.runtime_error_options("stop", bool, type(stop))
# return
# if self._stop == stop:
# return
# if stop:
# self._stop.set()
# else:
# self._stop.clear()
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('stop')
#
# _playmode = "autoplay"
# _available_modes = ['autoplay', 'guided']
#
# @property
# def playmode(self):
# return self._playmode
#
# @playmode.setter
# def playmode(self, playmode):
# if not isinstance(playmode, str):
# self.runtime_error_options("playmode", str, type(playmode))
# return
# if playmode not in self._available_modes:
# return
# if self._playmode == playmode:
# return
# self._playmode = playmode
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('playmode')
#
# _battle_calls = {
# "beforeStart": [],
# "afterStart" : [],
# "beforeEnd" : [],
# "afterEnd" : []
# }
#
# @property
# def battle_calls(self):
# return self._battle_calls
#
# @battle_calls.setter
# def battle_calls(self, value):
# if not isinstance(value, dict):
# self.runtime_error_options("battle_calls", dict, type(value))
# return
# if self._battle_calls == value:
# return
# self._battle_calls = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('battle_calls')
#
# @abstractmethod
# def runtime_error_options(self, option, expecting_type, got_type):
# raise NotImplementedError("runtime_error_options not implemented")
#
# @abstractmethod
# def timeout_dump(self):
# raise NotImplementedError("timeout_dump not implemented")
#
# @abstractmethod
# def handle_option_change(self, value):
# raise NotImplementedError("handle_option_change not implemented")
#
# Path: bot/utils/data.py
# def read_json_file(file=data_file):
# try:
# with open(file) as f:
# data = json.load(f, object_hook=date_hook)
# return data
# except FileNotFoundError:
# return None
#
# def write_data_file(data, file=data_file):
# with open(file, 'w') as f:
# json.dump(data, f, sort_keys=True,
# indent=4, separators=(',', ': '), default=datetime_handler)
, which may contain function names, class names, or code. Output only the next line. | 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.runtimeoptions.run_now = True
self.runtimeoptions.dump()
tmp_data = read_json_file(self.runtimeoptions._file)
runtimedict = self.runtimeoptions.dump_options()
self.assertTrue(tmp_data == runtimedict, "Expecting them to be the same")
tmp_data['run_now'] = False
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from bot.duel_links_runtime import DuelLinkRunTimeOptions
from bot.utils.data import read_json_file, write_data_file)
and context including class names, function names, or small code snippets from other files:
# Path: bot/duel_links_runtime.py
# class DuelLinkRunTimeOptions(object):
# """Class defines options used at runtime"""
# _active = False
#
# @property
# def active(self):
# return self._active
#
# @active.setter
# def active(self, value):
# self._active = True
#
# _last_run_at = datetime.datetime.fromtimestamp(default_timestamp)
#
# @property
# def last_run_at(self):
# return self._last_run_at
#
# @last_run_at.setter
# def last_run_at(self, value):
# if not isinstance(value, datetime.datetime):
# self.runtime_error_options("last_run_at", datetime.datetime, type(value))
# return
# if self._last_run_at == value:
# return
# self._last_run_at = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified to {}".format(inspect.getframeinfo(frame).function, value))
# self.timeout_dump()
#
# _next_run_at = datetime.datetime.fromtimestamp(default_timestamp)
#
# @property
# def next_run_at(self):
# return self._next_run_at
#
# @next_run_at.setter
# def next_run_at(self, value):
# if not isinstance(value, datetime.datetime):
# self.runtime_error_options("next_run_at", datetime.datetime, type(value))
# return
# if self._next_run_at == value:
# return
# self._next_run_at = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified to {}".format(inspect.getframeinfo(frame).function, value))
# self.timeout_dump()
# self.handle_option_change('next_run_at')
#
# _run_now = False
#
# @property
# def run_now(self):
# return self._run_now
#
# @run_now.setter
# def run_now(self, value):
# if not isinstance(value, bool):
# self.runtime_error_options("run_now", bool, type(value))
# return
# if self._run_now == value:
# return
# self._run_now = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('run_now')
#
# _stop = threading.Event()
#
# @property
# def stop(self):
# return self._stop.is_set()
#
# @stop.setter
# def stop(self, stop):
# if not isinstance(stop, bool):
# self.runtime_error_options("stop", bool, type(stop))
# return
# if self._stop == stop:
# return
# if stop:
# self._stop.set()
# else:
# self._stop.clear()
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('stop')
#
# _playmode = "autoplay"
# _available_modes = ['autoplay', 'guided']
#
# @property
# def playmode(self):
# return self._playmode
#
# @playmode.setter
# def playmode(self, playmode):
# if not isinstance(playmode, str):
# self.runtime_error_options("playmode", str, type(playmode))
# return
# if playmode not in self._available_modes:
# return
# if self._playmode == playmode:
# return
# self._playmode = playmode
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('playmode')
#
# _battle_calls = {
# "beforeStart": [],
# "afterStart" : [],
# "beforeEnd" : [],
# "afterEnd" : []
# }
#
# @property
# def battle_calls(self):
# return self._battle_calls
#
# @battle_calls.setter
# def battle_calls(self, value):
# if not isinstance(value, dict):
# self.runtime_error_options("battle_calls", dict, type(value))
# return
# if self._battle_calls == value:
# return
# self._battle_calls = value
# frame = inspect.currentframe()
# logger.debug("Value {} modified".format(inspect.getframeinfo(frame).function))
# self.timeout_dump()
# self.handle_option_change('battle_calls')
#
# @abstractmethod
# def runtime_error_options(self, option, expecting_type, got_type):
# raise NotImplementedError("runtime_error_options not implemented")
#
# @abstractmethod
# def timeout_dump(self):
# raise NotImplementedError("timeout_dump not implemented")
#
# @abstractmethod
# def handle_option_change(self, value):
# raise NotImplementedError("handle_option_change not implemented")
#
# Path: bot/utils/data.py
# def read_json_file(file=data_file):
# try:
# with open(file) as f:
# data = json.load(f, object_hook=date_hook)
# return data
# except FileNotFoundError:
# return None
#
# def write_data_file(data, file=data_file):
# with open(file, 'w') as f:
# json.dump(data, f, sort_keys=True,
# indent=4, separators=(',', ': '), default=datetime_handler)
. Output only the next line. | 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 cv2
import numpy as _np
from enum import Enum
from inspect import getframeinfo, currentframe
from bot.providers.predefined import Predefined
from bot.shared import nox_current_version, tupletodict
and any relevant context from other files:
# Path: bot/providers/predefined.py
# class Predefined(object):
# _config = None
# dataset = None
# version = None
# assets = None
#
# def __init__(self, config, version):
# self._config = config
# self.cache_file = config.get('locations', 'cache_file')
# self.dataset = self.dataset or self.__class__.__name__
# self.assets = config.get('locations', 'assets')
# self.version = version
# self.get_cache()
# self.check_cache()
#
# _cache = None
# _last_read = datetime.fromtimestamp(default_timestamp)
#
# @property
# def cache(self):
# return self._cache
#
# @cache.setter
# def cache(self, value):
# self._last_read = datetime.now()
# self._cache = value
#
# def check_cache(self):
# pass
#
# def get_cache(self):
# if not os.path.exists(self.cache_file):
# self.generate()
# if self.cache is None:
# self.cache = load_dict_from_hdf5(self.cache_file)
# if self.dataset in self.cache.keys():
# return
# self.generate()
#
# _duel_varient = None
#
# @property
# def duel_variant(self):
# raise NotImplementedError("Class {} did not implement duel variant property".format(self.__class__.__name__))
#
# _auto_duel = None
#
# @property
# def autoduel(self):
# raise NotImplementedError("Class {} did not implement auto duel property".format(self.__class__.__name__))
#
# # TODO: IMPLEMENT METHOD TO DETERMINE THE ACCURACY OR THE LIKELHOOD THAT THIS IS AN AUTODUEL BUTTON
#
# def determine_autoduel_status(self, img):
# vals = self.cache.get(self.dataset)
# autodueloff = vals['auto_duel_off']
# autoduelon = vals['auto_duel_on']
# current = self.get_image_stats(img, **self.autoduel)
# dist1 = np.linalg.norm(current - autoduelon)
# dist2 = np.linalg.norm(current - autodueloff)
# if dist1 < dist2:
# return True
# return False
#
# def determine_duel_variant(self, img):
# vals = self.cache.get(self.dataset)
# ver_duel_variant = vals['duel_variant']
# edges = cv2.Canny(img, 240, 255)
# current = Predefined.get_image_stats(edges, **self.duel_variant)
# dist1 = np.linalg.norm(current - ver_duel_variant)
# if dist1 <= 5:
# return True
# return False
#
# @staticmethod
# def get_image_stats(img, left=0, top=0, width=0, height=0):
# crop_img = img[top:(top + height), left:(left + width)]
# (means, stds) = cv2.meanStdDev(crop_img)
# stats = np.concatenate([means, stds]).flatten()
# return stats
#
# def write_hdf5(self, data, dataset):
# data = {dataset: data}
# save_dict_to_hdf5(data, self.cache_file, mode='a')
#
# @abstractmethod
# def generate(self):
# raise NotImplementedError("Class {} did not implement generate".format(self.__class__.__name__))
#
# @property
# def street_replay_location(self):
# return 4
#
# @property
# def quick_rankduel_location(self):
# return 2
#
# Path: bot/shared.py
# HIGH_CORR = 3
# LOW_CORR = 2
# def look_up_translation_correlation(corr):
# def tupletodict(top, left, height, width):
. Output only the next line. | 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_comparision = [
]
dataset = 'steam'
def __init__(self, *args, **kwargs):
super(SteamPredefined, self).__init__(*args, **kwargs)
def run_prechecks(self):
for file in self.files_need:
assert (os.path.exists(os.path.join(self.assets,
file))), "Missing File for stats generations: if you git cloned this repo you probably have a miss configured home!!!"
def generate(self):
self.run_prechecks()
save = {}
temp_dict = self.generate_autoduel_stats()
save = {**save, **temp_dict}
temp_dict = self.generate_duel_button_stats()
save = {**save, **temp_dict}
<|code_end|>
. Use current file imports:
import os as os
import cv2
import numpy as _np
from enum import Enum
from inspect import getframeinfo, currentframe
from bot.providers.predefined import Predefined
from bot.shared import nox_current_version, tupletodict
and context (classes, functions, or code) from other files:
# Path: bot/providers/predefined.py
# class Predefined(object):
# _config = None
# dataset = None
# version = None
# assets = None
#
# def __init__(self, config, version):
# self._config = config
# self.cache_file = config.get('locations', 'cache_file')
# self.dataset = self.dataset or self.__class__.__name__
# self.assets = config.get('locations', 'assets')
# self.version = version
# self.get_cache()
# self.check_cache()
#
# _cache = None
# _last_read = datetime.fromtimestamp(default_timestamp)
#
# @property
# def cache(self):
# return self._cache
#
# @cache.setter
# def cache(self, value):
# self._last_read = datetime.now()
# self._cache = value
#
# def check_cache(self):
# pass
#
# def get_cache(self):
# if not os.path.exists(self.cache_file):
# self.generate()
# if self.cache is None:
# self.cache = load_dict_from_hdf5(self.cache_file)
# if self.dataset in self.cache.keys():
# return
# self.generate()
#
# _duel_varient = None
#
# @property
# def duel_variant(self):
# raise NotImplementedError("Class {} did not implement duel variant property".format(self.__class__.__name__))
#
# _auto_duel = None
#
# @property
# def autoduel(self):
# raise NotImplementedError("Class {} did not implement auto duel property".format(self.__class__.__name__))
#
# # TODO: IMPLEMENT METHOD TO DETERMINE THE ACCURACY OR THE LIKELHOOD THAT THIS IS AN AUTODUEL BUTTON
#
# def determine_autoduel_status(self, img):
# vals = self.cache.get(self.dataset)
# autodueloff = vals['auto_duel_off']
# autoduelon = vals['auto_duel_on']
# current = self.get_image_stats(img, **self.autoduel)
# dist1 = np.linalg.norm(current - autoduelon)
# dist2 = np.linalg.norm(current - autodueloff)
# if dist1 < dist2:
# return True
# return False
#
# def determine_duel_variant(self, img):
# vals = self.cache.get(self.dataset)
# ver_duel_variant = vals['duel_variant']
# edges = cv2.Canny(img, 240, 255)
# current = Predefined.get_image_stats(edges, **self.duel_variant)
# dist1 = np.linalg.norm(current - ver_duel_variant)
# if dist1 <= 5:
# return True
# return False
#
# @staticmethod
# def get_image_stats(img, left=0, top=0, width=0, height=0):
# crop_img = img[top:(top + height), left:(left + width)]
# (means, stds) = cv2.meanStdDev(crop_img)
# stats = np.concatenate([means, stds]).flatten()
# return stats
#
# def write_hdf5(self, data, dataset):
# data = {dataset: data}
# save_dict_to_hdf5(data, self.cache_file, mode='a')
#
# @abstractmethod
# def generate(self):
# raise NotImplementedError("Class {} did not implement generate".format(self.__class__.__name__))
#
# @property
# def street_replay_location(self):
# return 4
#
# @property
# def quick_rankduel_location(self):
# return 2
#
# Path: bot/shared.py
# HIGH_CORR = 3
# LOW_CORR = 2
# def look_up_translation_correlation(corr):
# def tupletodict(top, left, height, width):
. Output only the next line. | 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_duel_variant, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(im, 240, 255)
a = self.get_image_stats(_np.array(edges), **self.duel_variant)
save = {
'duel_variant': a
}
return save
def get_area(self, area):
return {
SteamAreas.MAINAREA: self.main_area,
SteamAreas.CARDINFO: self.card_info_area,
SteamAreas.LOG : self.log_area
}[area]
def relative(self, x, y, area):
area = self.get_area(area)
xrel, yrel = area.get('left'), area.get('top')
return x + xrel, y + yrel
def relative_area(self, x, y, height, width, area):
area = self.get_area(area)
xrel, yrel = area.get('top'), area.get('left')
<|code_end|>
, predict the next line using imports from the current file:
import os as os
import cv2
import numpy as _np
from enum import Enum
from inspect import getframeinfo, currentframe
from bot.providers.predefined import Predefined
from bot.shared import nox_current_version, tupletodict
and context including class names, function names, and sometimes code from other files:
# Path: bot/providers/predefined.py
# class Predefined(object):
# _config = None
# dataset = None
# version = None
# assets = None
#
# def __init__(self, config, version):
# self._config = config
# self.cache_file = config.get('locations', 'cache_file')
# self.dataset = self.dataset or self.__class__.__name__
# self.assets = config.get('locations', 'assets')
# self.version = version
# self.get_cache()
# self.check_cache()
#
# _cache = None
# _last_read = datetime.fromtimestamp(default_timestamp)
#
# @property
# def cache(self):
# return self._cache
#
# @cache.setter
# def cache(self, value):
# self._last_read = datetime.now()
# self._cache = value
#
# def check_cache(self):
# pass
#
# def get_cache(self):
# if not os.path.exists(self.cache_file):
# self.generate()
# if self.cache is None:
# self.cache = load_dict_from_hdf5(self.cache_file)
# if self.dataset in self.cache.keys():
# return
# self.generate()
#
# _duel_varient = None
#
# @property
# def duel_variant(self):
# raise NotImplementedError("Class {} did not implement duel variant property".format(self.__class__.__name__))
#
# _auto_duel = None
#
# @property
# def autoduel(self):
# raise NotImplementedError("Class {} did not implement auto duel property".format(self.__class__.__name__))
#
# # TODO: IMPLEMENT METHOD TO DETERMINE THE ACCURACY OR THE LIKELHOOD THAT THIS IS AN AUTODUEL BUTTON
#
# def determine_autoduel_status(self, img):
# vals = self.cache.get(self.dataset)
# autodueloff = vals['auto_duel_off']
# autoduelon = vals['auto_duel_on']
# current = self.get_image_stats(img, **self.autoduel)
# dist1 = np.linalg.norm(current - autoduelon)
# dist2 = np.linalg.norm(current - autodueloff)
# if dist1 < dist2:
# return True
# return False
#
# def determine_duel_variant(self, img):
# vals = self.cache.get(self.dataset)
# ver_duel_variant = vals['duel_variant']
# edges = cv2.Canny(img, 240, 255)
# current = Predefined.get_image_stats(edges, **self.duel_variant)
# dist1 = np.linalg.norm(current - ver_duel_variant)
# if dist1 <= 5:
# return True
# return False
#
# @staticmethod
# def get_image_stats(img, left=0, top=0, width=0, height=0):
# crop_img = img[top:(top + height), left:(left + width)]
# (means, stds) = cv2.meanStdDev(crop_img)
# stats = np.concatenate([means, stds]).flatten()
# return stats
#
# def write_hdf5(self, data, dataset):
# data = {dataset: data}
# save_dict_to_hdf5(data, self.cache_file, mode='a')
#
# @abstractmethod
# def generate(self):
# raise NotImplementedError("Class {} did not implement generate".format(self.__class__.__name__))
#
# @property
# def street_replay_location(self):
# return 4
#
# @property
# def quick_rankduel_location(self):
# return 2
#
# Path: bot/shared.py
# HIGH_CORR = 3
# LOW_CORR = 2
# def look_up_translation_correlation(corr):
# def tupletodict(top, left, height, width):
. Output only the next line. | 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
"""
sort_value = -1
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")
@abstractmethod
<|code_end|>
, determine the next line of code. You have imports:
import logging
from abc import abstractmethod
from bot.providers.duellinks import DuelLinksInfo, alphabet
from bot.common import crop_image
and context (class names, function names, or code) available:
# Path: bot/providers/duellinks.py
# class Event(object):
# class DuelLinksInfo(object):
# class EventExecutor(object):
# class DuelLinks(object):
# class DuelError(Exception):
# def __init__(self, func, *args, **kwargs):
# def func(self):
# def args(self):
# def kwargs(self):
# def __init__(self, x, y, page, status):
# def x(self):
# def y(self):
# def page(self):
# def status(self):
# def name(self):
# def x(self, value):
# def y(self, value):
# def page(self, value):
# def status(self, value):
# def name(self, value):
# def __init__(self):
# def do_event(self, _event):
# def current_thread(self):
# def current_thread(self, thread):
# def register_thread(self, thread):
# def auto_duel_box(self):
# def current_run(self):
# def current_run(self, run):
# def sleep_factor(self):
# def sleep_factor(self, value):
# def wait_for_ui(self, amount):
# async def async_wait_for_ui(self, amount):
# def auto(self):
# def debug_battle(self):
# def check_battle_is_running(self):
# def check_battle(self):
# def scan(self):
# def method_name(self):
# def compare_with_cancel_button(self, corr=HIGH_CORR, info=None, img=None):
# def compare_with_back_button(self, corr=HIGH_CORR, info=None, img=None):
# def scan_for_ok(self, corr=HIGH_CORR, info=None, img=None):
# def scan_for_close(self, corr=HIGH_CORR, info=None, img=None):
# def get_current_page(self, img):
# def click_auto_duel(self):
# def determine_autoduel_status(self, img):
# def battle(self, info=None, check_battle=None):
# def check_if_battle(self, img):
# def verify_battle(self, img=None, log=True):
# def pass_through_initial_screen(self):
# def wait_for(self, word, try_scanning=False):
# def wait_for_auto_duel(self):
# def wait_for_white_bottom(self):
# def __init__(self, value):
# def __str__(self):
#
# Path: bot/common.py
# def crop_image(img, left=0, top=0, width=0, height=0):
# left, top, width, height = tuple(np.asanyarray([left, top, width, height], np.uint64).tolist())
# crop_img = img[top:(top + height), left:(left + width)].copy()
# return crop_img
. Output only the next line. | 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")
@abstractmethod
def event_condition(self, dl_info: DuelLinksInfo, img=None):
"""
:param dl_info:
:type dl_info: DuelLinksInfo
"""
raise NotImplementedError("event_condition not implemented")
def event_occurred(self, dl_info: DuelLinksInfo, img=None):
raise NotImplementedError("event_occured not implemented")
class StreetReplay(AbstractIgnoreEvent):
looking_for = 'Street Replay'
alphabet_set = ''.join(set(looking_for)).replace(' ', '')
def is_occurrence(self, img=None):
if img is None:
img = self.provider.get_img_from_screen_shot()
street_replay = self.provider.predefined.street_replay
<|code_end|>
with the help of current file imports:
import logging
from abc import abstractmethod
from bot.providers.duellinks import DuelLinksInfo, alphabet
from bot.common import crop_image
and context from other files:
# Path: bot/providers/duellinks.py
# class Event(object):
# class DuelLinksInfo(object):
# class EventExecutor(object):
# class DuelLinks(object):
# class DuelError(Exception):
# def __init__(self, func, *args, **kwargs):
# def func(self):
# def args(self):
# def kwargs(self):
# def __init__(self, x, y, page, status):
# def x(self):
# def y(self):
# def page(self):
# def status(self):
# def name(self):
# def x(self, value):
# def y(self, value):
# def page(self, value):
# def status(self, value):
# def name(self, value):
# def __init__(self):
# def do_event(self, _event):
# def current_thread(self):
# def current_thread(self, thread):
# def register_thread(self, thread):
# def auto_duel_box(self):
# def current_run(self):
# def current_run(self, run):
# def sleep_factor(self):
# def sleep_factor(self, value):
# def wait_for_ui(self, amount):
# async def async_wait_for_ui(self, amount):
# def auto(self):
# def debug_battle(self):
# def check_battle_is_running(self):
# def check_battle(self):
# def scan(self):
# def method_name(self):
# def compare_with_cancel_button(self, corr=HIGH_CORR, info=None, img=None):
# def compare_with_back_button(self, corr=HIGH_CORR, info=None, img=None):
# def scan_for_ok(self, corr=HIGH_CORR, info=None, img=None):
# def scan_for_close(self, corr=HIGH_CORR, info=None, img=None):
# def get_current_page(self, img):
# def click_auto_duel(self):
# def determine_autoduel_status(self, img):
# def battle(self, info=None, check_battle=None):
# def check_if_battle(self, img):
# def verify_battle(self, img=None, log=True):
# def pass_through_initial_screen(self):
# def wait_for(self, word, try_scanning=False):
# def wait_for_auto_duel(self):
# def wait_for_white_bottom(self):
# def __init__(self, value):
# def __str__(self):
#
# Path: bot/common.py
# def crop_image(img, left=0, top=0, width=0, height=0):
# left, top, width, height = tuple(np.asanyarray([left, top, width, height], np.uint64).tolist())
# crop_img = img[top:(top + height), left:(left + width)].copy()
# return crop_img
, which may contain function names, class names, or code. Output only the next line. | 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
def __init__(self, provider):
signalers = {}
for cp in CheckPoints:
<|code_end|>
. Use current file imports:
(import re
from abc import abstractmethod
from enum import Enum
from bot.modes.Events import Signal
from bot.common import crop_image
from bot.shared import LOW_CORR, alpha_numeric)
and context including class names, function names, or small code snippets from other files:
# Path: bot/modes/Events.py
# class Signal(object):
# def __init__(self):
# self.callbacks = []
# self.r_lock = threading.RLock()
#
# def connect(self, callback):
# with self.r_lock:
# callback = weak_ref(callback)
# self.callbacks.append(callback)
#
# def disconnect(self, callback):
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# if callback == weakref_callback():
# del self.callbacks[index]
# break
#
# def emit(self, *args, **kwargs):
# if len(self.callbacks) == 0:
# return
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# callback = weakref_callback()
# if callback is not None:
# callback(*args, **kwargs)
# else: # lost reference
# del self.callbacks[index]
#
# Path: bot/common.py
# def crop_image(img, left=0, top=0, width=0, height=0):
# left, top, width, height = tuple(np.asanyarray([left, top, width, height], np.uint64).tolist())
# crop_img = img[top:(top + height), left:(left + width)].copy()
# return crop_img
#
# Path: bot/shared.py
# HIGH_CORR = 3
# LOW_CORR = 2
# def look_up_translation_correlation(corr):
# def tupletodict(top, left, height, width):
. Output only the next line. | 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"
self.log(info)
self.provider.wait_for_ui(.5)
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for('NEXT', True)
self.provider.tapnsleep(self.provider.predefined.button_duel, .5)
self.provider.wait_for('NEXT', True)
self.provider.wait_for_ui(.3)
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for_white_bottom(True)
self.provider.wait_for_ui(.5)
self.provider.tapnsleep(self.provider.predefined.button_duel, .1)
dialog = True
while dialog:
dialog = self.provider.check_if_battle(self.provider.get_img_from_screen_shot())
if dialog:
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for_ui(.5)
self.provider.scan_for_ok(LOW_CORR)
self.provider.wait_for_ui(.1)
self.provider.scan_for_ok(LOW_CORR)
self.signalers[CheckPoints.afterEnding].emit(info)
def check_battle(self, info, img):
"""Will Always return true since this is the last possible battle mode available"""
<|code_end|>
. Use current file imports:
import re
from abc import abstractmethod
from enum import Enum
from bot.modes.Events import Signal
from bot.common import crop_image
from bot.shared import LOW_CORR, alpha_numeric
and context (classes, functions, or code) from other files:
# Path: bot/modes/Events.py
# class Signal(object):
# def __init__(self):
# self.callbacks = []
# self.r_lock = threading.RLock()
#
# def connect(self, callback):
# with self.r_lock:
# callback = weak_ref(callback)
# self.callbacks.append(callback)
#
# def disconnect(self, callback):
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# if callback == weakref_callback():
# del self.callbacks[index]
# break
#
# def emit(self, *args, **kwargs):
# if len(self.callbacks) == 0:
# return
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# callback = weakref_callback()
# if callback is not None:
# callback(*args, **kwargs)
# else: # lost reference
# del self.callbacks[index]
#
# Path: bot/common.py
# def crop_image(img, left=0, top=0, width=0, height=0):
# left, top, width, height = tuple(np.asanyarray([left, top, width, height], np.uint64).tolist())
# crop_img = img[top:(top + height), left:(left + width)].copy()
# return crop_img
#
# Path: bot/shared.py
# HIGH_CORR = 3
# LOW_CORR = 2
# def look_up_translation_correlation(corr):
# def tupletodict(top, left, height, width):
. Output only the next line. | 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_duel()
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"
self.log(info)
self.provider.wait_for_ui(.5)
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for('NEXT', True)
self.provider.tapnsleep(self.provider.predefined.button_duel, .5)
self.provider.wait_for('NEXT', True)
self.provider.wait_for_ui(.3)
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for_white_bottom(True)
self.provider.wait_for_ui(.5)
self.provider.tapnsleep(self.provider.predefined.button_duel, .1)
dialog = True
while dialog:
dialog = self.provider.check_if_battle(self.provider.get_img_from_screen_shot())
if dialog:
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for_ui(.5)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from abc import abstractmethod
from enum import Enum
from bot.modes.Events import Signal
from bot.common import crop_image
from bot.shared import LOW_CORR, alpha_numeric
and context:
# Path: bot/modes/Events.py
# class Signal(object):
# def __init__(self):
# self.callbacks = []
# self.r_lock = threading.RLock()
#
# def connect(self, callback):
# with self.r_lock:
# callback = weak_ref(callback)
# self.callbacks.append(callback)
#
# def disconnect(self, callback):
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# if callback == weakref_callback():
# del self.callbacks[index]
# break
#
# def emit(self, *args, **kwargs):
# if len(self.callbacks) == 0:
# return
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# callback = weakref_callback()
# if callback is not None:
# callback(*args, **kwargs)
# else: # lost reference
# del self.callbacks[index]
#
# Path: bot/common.py
# def crop_image(img, left=0, top=0, width=0, height=0):
# left, top, width, height = tuple(np.asanyarray([left, top, width, height], np.uint64).tolist())
# crop_img = img[top:(top + height), left:(left + width)].copy()
# return crop_img
#
# Path: bot/shared.py
# HIGH_CORR = 3
# LOW_CORR = 2
# def look_up_translation_correlation(corr):
# def tupletodict(top, left, height, width):
which might include code, classes, or functions. Output only the next line. | 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)
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for('NEXT', True)
self.provider.tapnsleep(self.provider.predefined.button_duel, .5)
self.provider.wait_for('NEXT', True)
self.provider.wait_for_ui(.3)
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for_white_bottom(True)
self.provider.wait_for_ui(.5)
self.provider.tapnsleep(self.provider.predefined.button_duel, .1)
dialog = True
while dialog:
dialog = self.provider.check_if_battle(self.provider.get_img_from_screen_shot())
if dialog:
self.provider.tap(*self.provider.predefined.button_duel)
self.provider.wait_for_ui(.5)
self.provider.scan_for_ok(LOW_CORR)
self.provider.wait_for_ui(.1)
self.provider.scan_for_ok(LOW_CORR)
self.signalers[CheckPoints.afterEnding].emit(info)
def check_battle(self, info, img):
"""Will Always return true since this is the last possible battle mode available"""
img = crop_image(img, **self.provider.predefined.duelist_name_area)
<|code_end|>
. Use current file imports:
(import re
from abc import abstractmethod
from enum import Enum
from bot.modes.Events import Signal
from bot.common import crop_image
from bot.shared import LOW_CORR, alpha_numeric)
and context including class names, function names, or small code snippets from other files:
# Path: bot/modes/Events.py
# class Signal(object):
# def __init__(self):
# self.callbacks = []
# self.r_lock = threading.RLock()
#
# def connect(self, callback):
# with self.r_lock:
# callback = weak_ref(callback)
# self.callbacks.append(callback)
#
# def disconnect(self, callback):
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# if callback == weakref_callback():
# del self.callbacks[index]
# break
#
# def emit(self, *args, **kwargs):
# if len(self.callbacks) == 0:
# return
# with self.r_lock:
# for index, weakref_callback in enumerate(self.callbacks):
# callback = weakref_callback()
# if callback is not None:
# callback(*args, **kwargs)
# else: # lost reference
# del self.callbacks[index]
#
# Path: bot/common.py
# def crop_image(img, left=0, top=0, width=0, height=0):
# left, top, width, height = tuple(np.asanyarray([left, top, width, height], np.uint64).tolist())
# crop_img = img[top:(top + height), left:(left + width)].copy()
# return crop_img
#
# Path: bot/shared.py
# HIGH_CORR = 3
# LOW_CORR = 2
# def look_up_translation_correlation(corr):
# def tupletodict(top, left, height, width):
. Output only the next line. | 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 bot.utils.common import DotDict
and context including class names, function names, and sometimes code from other files:
# Path: bot/utils/common.py
# class DotDict(dict):
# """dot.notation access to dictionary attributes"""
# __getattr__ = dict.get
# __setattr__ = dict.__setitem__
# __delattr__ = dict.__delitem__
. Output only the next line. | 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().isLogged():
raise BaseException('You are not authorized')
return f(*args, **kwargs)
return _inner
#decorator
def is_admin(f):
def _inner(*args, **kwargs):
if not UserSession().isLogged() or not UserSession().getUser().is_admin:
raise BaseException('You are not authorized')
return f(*args, **kwargs)
return _inner
class RequestHandler(webapp.RequestHandler):
def initialize(self, *args, **kwargs):
super(RequestHandler, self).initialize(*args, **kwargs)
<|code_end|>
. Write the next line using the current file imports:
from modules.user.model.session import UserSession
from google.appengine.ext import webapp
from lib.registry import Registry
and context from other files:
# Path: modules/user/model/session.py
# 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:
# user = User.get(self['user_key'])
# if not user:
# raise BaseException('User with key %s not found' % (self['user_key']))
# return user
# return False
#
# def setUserAsLogged(self, user):
# self['user_key'] = str(user.key())
#
# def setUserAsLoggedByKey(self, key):
# self['user_key'] = key
#
# Path: lib/registry.py
# class Registry(dict):
# def set(self, key, value):
# self[key] = value
# def get(self, key):
# if self.has_key(key):
# return self[key]
# else:
# return False
, which may include functions, classes, or code. Output only the next line. | 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/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://genshi.edgewall.org/log/.
"""Template loading and caching."""
try:
except ImportError:
__all__ = ['TemplateLoader', 'TemplateNotFound', 'directory', 'package',
'prefixed']
__docformat__ = 'restructuredtext en'
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import threading
import dummy_threading as threading
from genshi.template.base import TemplateError
from genshi.util import LRUCache
from genshi.template.markup import MarkupTemplate
from pkg_resources import resource_stream
and context (classes, functions, sometimes code) from other files:
# Path: genshi/template/base.py
# class TemplateError(Exception):
# """Base exception class for errors related to template processing."""
#
# def __init__(self, message, filename=None, lineno=-1, offset=-1):
# """Create the exception.
#
# :param message: the error message
# :param filename: the filename of the template
# :param lineno: the number of line in the template at which the error
# occurred
# :param offset: the column number at which the error occurred
# """
# if filename is None:
# filename = '<string>'
# self.msg = message #: the error message string
# if filename != '<string>' or lineno >= 0:
# message = '%s (%s, line %d)' % (self.msg, filename, lineno)
# Exception.__init__(self, message)
# self.filename = filename #: the name of the template file
# self.lineno = lineno #: the number of the line containing the error
# self.offset = offset #: the offset on the line
#
# Path: genshi/util.py
# class LRUCache(dict):
# """A dictionary-like object that stores only a certain number of items, and
# discards its least recently used item when full.
#
# >>> cache = LRUCache(3)
# >>> cache['A'] = 0
# >>> cache['B'] = 1
# >>> cache['C'] = 2
# >>> len(cache)
# 3
#
# >>> cache['A']
# 0
#
# Adding new items to the cache does not increase its size. Instead, the least
# recently used item is dropped:
#
# >>> cache['D'] = 3
# >>> len(cache)
# 3
# >>> 'B' in cache
# False
#
# Iterating over the cache returns the keys, starting with the most recently
# used:
#
# >>> for key in cache:
# ... print(key)
# D
# A
# C
#
# This code is based on the LRUCache class from ``myghtyutils.util``, written
# by Mike Bayer and released under the MIT license. See:
#
# http://svn.myghty.org/myghtyutils/trunk/lib/myghtyutils/util.py
# """
#
# class _Item(object):
# def __init__(self, key, value):
# self.prv = self.nxt = None
# self.key = key
# self.value = value
# def __repr__(self):
# return repr(self.value)
#
# def __init__(self, capacity):
# self._dict = dict()
# self.capacity = capacity
# self.head = None
# self.tail = None
#
# def __contains__(self, key):
# return key in self._dict
#
# def __iter__(self):
# cur = self.head
# while cur:
# yield cur.key
# cur = cur.nxt
#
# def __len__(self):
# return len(self._dict)
#
# def __getitem__(self, key):
# item = self._dict[key]
# self._update_item(item)
# return item.value
#
# def __setitem__(self, key, value):
# item = self._dict.get(key)
# if item is None:
# item = self._Item(key, value)
# self._dict[key] = item
# self._insert_item(item)
# else:
# item.value = value
# self._update_item(item)
# self._manage_size()
#
# def __repr__(self):
# return repr(self._dict)
#
# def _insert_item(self, item):
# item.prv = None
# item.nxt = self.head
# if self.head is not None:
# self.head.prv = item
# else:
# self.tail = item
# self.head = item
# self._manage_size()
#
# def _manage_size(self):
# while len(self._dict) > self.capacity:
# olditem = self._dict[self.tail.key]
# del self._dict[self.tail.key]
# if self.tail != self.head:
# self.tail = self.tail.prv
# self.tail.nxt = None
# else:
# self.head = self.tail = None
#
# def _update_item(self, item):
# if self.head == item:
# return
#
# prv = item.prv
# prv.nxt = item.nxt
# if item.nxt is not None:
# item.nxt.prv = prv
# else:
# self.tail = prv
#
# item.prv = None
# item.nxt = self.head
# self.head.prv = self.head = item
. Output only the next line. | 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
template was initialized by this loader; the function
is passed the template object as only argument. This
callback can be used for example to add any desired
filters to the template
:see: `LenientLookup`, `StrictLookup`
:note: Changed in 0.5: Added the `allow_exec` argument
"""
self.search_path = search_path
if self.search_path is None:
self.search_path = []
elif not isinstance(self.search_path, (list, tuple)):
self.search_path = [self.search_path]
self.auto_reload = auto_reload
"""Whether templates should be reloaded when the underlying file is
changed"""
self.default_encoding = default_encoding
self.default_class = default_class or MarkupTemplate
self.variable_lookup = variable_lookup
self.allow_exec = allow_exec
if callback is not None and not hasattr(callback, '__call__'):
raise TypeError('The "callback" parameter needs to be callable')
self.callback = callback
<|code_end|>
. Use current file imports:
import os
import threading
import dummy_threading as threading
from genshi.template.base import TemplateError
from genshi.util import LRUCache
from genshi.template.markup import MarkupTemplate
from pkg_resources import resource_stream
and context (classes, functions, or code) from other files:
# Path: genshi/template/base.py
# class TemplateError(Exception):
# """Base exception class for errors related to template processing."""
#
# def __init__(self, message, filename=None, lineno=-1, offset=-1):
# """Create the exception.
#
# :param message: the error message
# :param filename: the filename of the template
# :param lineno: the number of line in the template at which the error
# occurred
# :param offset: the column number at which the error occurred
# """
# if filename is None:
# filename = '<string>'
# self.msg = message #: the error message string
# if filename != '<string>' or lineno >= 0:
# message = '%s (%s, line %d)' % (self.msg, filename, lineno)
# Exception.__init__(self, message)
# self.filename = filename #: the name of the template file
# self.lineno = lineno #: the number of the line containing the error
# self.offset = offset #: the offset on the line
#
# Path: genshi/util.py
# class LRUCache(dict):
# """A dictionary-like object that stores only a certain number of items, and
# discards its least recently used item when full.
#
# >>> cache = LRUCache(3)
# >>> cache['A'] = 0
# >>> cache['B'] = 1
# >>> cache['C'] = 2
# >>> len(cache)
# 3
#
# >>> cache['A']
# 0
#
# Adding new items to the cache does not increase its size. Instead, the least
# recently used item is dropped:
#
# >>> cache['D'] = 3
# >>> len(cache)
# 3
# >>> 'B' in cache
# False
#
# Iterating over the cache returns the keys, starting with the most recently
# used:
#
# >>> for key in cache:
# ... print(key)
# D
# A
# C
#
# This code is based on the LRUCache class from ``myghtyutils.util``, written
# by Mike Bayer and released under the MIT license. See:
#
# http://svn.myghty.org/myghtyutils/trunk/lib/myghtyutils/util.py
# """
#
# class _Item(object):
# def __init__(self, key, value):
# self.prv = self.nxt = None
# self.key = key
# self.value = value
# def __repr__(self):
# return repr(self.value)
#
# def __init__(self, capacity):
# self._dict = dict()
# self.capacity = capacity
# self.head = None
# self.tail = None
#
# def __contains__(self, key):
# return key in self._dict
#
# def __iter__(self):
# cur = self.head
# while cur:
# yield cur.key
# cur = cur.nxt
#
# def __len__(self):
# return len(self._dict)
#
# def __getitem__(self, key):
# item = self._dict[key]
# self._update_item(item)
# return item.value
#
# def __setitem__(self, key, value):
# item = self._dict.get(key)
# if item is None:
# item = self._Item(key, value)
# self._dict[key] = item
# self._insert_item(item)
# else:
# item.value = value
# self._update_item(item)
# self._manage_size()
#
# def __repr__(self):
# return repr(self._dict)
#
# def _insert_item(self, item):
# item.prv = None
# item.nxt = self.head
# if self.head is not None:
# self.head.prv = item
# else:
# self.tail = item
# self.head = item
# self._manage_size()
#
# def _manage_size(self):
# while len(self._dict) > self.capacity:
# olditem = self._dict[self.tail.key]
# del self._dict[self.tail.key]
# if self.tail != self.head:
# self.tail = self.tail.prv
# self.tail.nxt = None
# else:
# self.head = self.tail = None
#
# def _update_item(self, item):
# if self.head == item:
# return
#
# prv = item.prv
# prv.nxt = item.nxt
# if item.nxt is not None:
# item.nxt.prv = prv
# else:
# self.tail = prv
#
# item.prv = None
# item.nxt = self.head
# self.head.prv = self.head = item
. Output only the next line. | 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 using imports from the current file:
from lib.registry import Registry
import logging
and context including class names, function names, and sometimes code from other files:
# Path: lib/registry.py
# class Registry(dict):
# def set(self, key, value):
# self[key] = value
# def get(self, key):
# if self.has_key(key):
# return self[key]
# else:
# return False
. Output only the next line. | 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('>', '>')
if quotes:
text = text.replace('"', '"')
return cls(text)
def unescape(self):
"""Reverse-escapes &, <, >, and \" and returns a `unicode` object.
>>> Markup('1 < 2').unescape()
u'1 < 2'
:return: the unescaped string
:rtype: `unicode`
:see: `genshi.core.unescape`
"""
if not self:
return ''
return unicode(self).replace('"', '"') \
.replace('>', '>') \
.replace('<', '<') \
.replace('&', '&')
<|code_end|>
, determine the next line of code. You have imports:
from functools import reduce
from itertools import chain
from genshi.util import plaintext, stripentities, striptags, stringrepr
from genshi.output import encode
from genshi.path import Path
from genshi.output import get_serializer
from genshi._speedups import Markup
import operator
and context (class names, function names, or code) available:
# Path: genshi/util.py
# def plaintext(text, keeplinebreaks=True):
# """Return the text with all entities and tags removed.
#
# >>> plaintext('<b>1 < 2</b>')
# u'1 < 2'
#
# The `keeplinebreaks` parameter can be set to ``False`` to replace any line
# breaks by simple spaces:
#
# >>> plaintext('''<b>1
# ... <
# ... 2</b>''', keeplinebreaks=False)
# u'1 < 2'
#
# :param text: the text to convert to plain text
# :param keeplinebreaks: whether line breaks in the text should be kept intact
# :return: the text with tags and entities removed
# """
# text = stripentities(striptags(text))
# if not keeplinebreaks:
# text = text.replace('\n', ' ')
# return text
#
# def stripentities(text, keepxmlentities=False):
# """Return a copy of the given text with any character or numeric entities
# replaced by the equivalent UTF-8 characters.
#
# >>> stripentities('1 < 2')
# u'1 < 2'
# >>> stripentities('more …')
# u'more \u2026'
# >>> stripentities('…')
# u'\u2026'
# >>> stripentities('…')
# u'\u2026'
#
# If the `keepxmlentities` parameter is provided and is a truth value, the
# core XML entities (&, ', >, < and ") are left intact.
#
# >>> stripentities('1 < 2 …', keepxmlentities=True)
# u'1 < 2 \u2026'
# """
# def _replace_entity(match):
# if match.group(1): # numeric entity
# ref = match.group(1)
# if ref.startswith('x'):
# ref = int(ref[1:], 16)
# else:
# ref = int(ref, 10)
# return unichr(ref)
# else: # character entity
# ref = match.group(2)
# if keepxmlentities and ref in ('amp', 'apos', 'gt', 'lt', 'quot'):
# return '&%s;' % ref
# try:
# return unichr(entities.name2codepoint[ref])
# except KeyError:
# if keepxmlentities:
# return '&%s;' % ref
# else:
# return ref
# return _STRIPENTITIES_RE.sub(_replace_entity, text)
#
# def striptags(text):
# """Return a copy of the text with any XML/HTML tags removed.
#
# >>> striptags('<span>Foo</span> bar')
# 'Foo bar'
# >>> striptags('<span class="bar">Foo</span>')
# 'Foo'
# >>> striptags('Foo<br />')
# 'Foo'
#
# HTML/XML comments are stripped, too:
#
# >>> striptags('<!-- <blub>hehe</blah> -->test')
# 'test'
#
# :param text: the string to remove tags from
# :return: the text with tags removed
# """
# return _STRIPTAGS_RE.sub('', text)
#
# def stringrepr(string):
# ascii = string.encode('ascii', 'backslashreplace')
# quoted = "'" + ascii.replace("'", "\\'") + "'"
# if len(ascii) > len(string):
# return 'u' + quoted
# return quoted
. Output only the next line. | 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.unescape`
"""
if not self:
return ''
return unicode(self).replace('"', '"') \
.replace('>', '>') \
.replace('<', '<') \
.replace('&', '&')
def stripentities(self, keepxmlentities=False):
"""Return a copy of the text with any character or numeric entities
replaced by the equivalent UTF-8 characters.
If the `keepxmlentities` parameter is provided and evaluates to `True`,
the core XML entities (``&``, ``'``, ``>``, ``<`` and
``"``) are not stripped.
:return: a `Markup` instance with entities removed
:rtype: `Markup`
:see: `genshi.util.stripentities`
"""
return Markup(stripentities(self, keepxmlentities=keepxmlentities))
<|code_end|>
, predict the next line using imports from the current file:
from functools import reduce
from itertools import chain
from genshi.util import plaintext, stripentities, striptags, stringrepr
from genshi.output import encode
from genshi.path import Path
from genshi.output import get_serializer
from genshi._speedups import Markup
import operator
and context including class names, function names, and sometimes code from other files:
# Path: genshi/util.py
# def plaintext(text, keeplinebreaks=True):
# """Return the text with all entities and tags removed.
#
# >>> plaintext('<b>1 < 2</b>')
# u'1 < 2'
#
# The `keeplinebreaks` parameter can be set to ``False`` to replace any line
# breaks by simple spaces:
#
# >>> plaintext('''<b>1
# ... <
# ... 2</b>''', keeplinebreaks=False)
# u'1 < 2'
#
# :param text: the text to convert to plain text
# :param keeplinebreaks: whether line breaks in the text should be kept intact
# :return: the text with tags and entities removed
# """
# text = stripentities(striptags(text))
# if not keeplinebreaks:
# text = text.replace('\n', ' ')
# return text
#
# def stripentities(text, keepxmlentities=False):
# """Return a copy of the given text with any character or numeric entities
# replaced by the equivalent UTF-8 characters.
#
# >>> stripentities('1 < 2')
# u'1 < 2'
# >>> stripentities('more …')
# u'more \u2026'
# >>> stripentities('…')
# u'\u2026'
# >>> stripentities('…')
# u'\u2026'
#
# If the `keepxmlentities` parameter is provided and is a truth value, the
# core XML entities (&, ', >, < and ") are left intact.
#
# >>> stripentities('1 < 2 …', keepxmlentities=True)
# u'1 < 2 \u2026'
# """
# def _replace_entity(match):
# if match.group(1): # numeric entity
# ref = match.group(1)
# if ref.startswith('x'):
# ref = int(ref[1:], 16)
# else:
# ref = int(ref, 10)
# return unichr(ref)
# else: # character entity
# ref = match.group(2)
# if keepxmlentities and ref in ('amp', 'apos', 'gt', 'lt', 'quot'):
# return '&%s;' % ref
# try:
# return unichr(entities.name2codepoint[ref])
# except KeyError:
# if keepxmlentities:
# return '&%s;' % ref
# else:
# return ref
# return _STRIPENTITIES_RE.sub(_replace_entity, text)
#
# def striptags(text):
# """Return a copy of the text with any XML/HTML tags removed.
#
# >>> striptags('<span>Foo</span> bar')
# 'Foo bar'
# >>> striptags('<span class="bar">Foo</span>')
# 'Foo'
# >>> striptags('Foo<br />')
# 'Foo'
#
# HTML/XML comments are stripped, too:
#
# >>> striptags('<!-- <blub>hehe</blah> -->test')
# 'test'
#
# :param text: the string to remove tags from
# :return: the text with tags removed
# """
# return _STRIPTAGS_RE.sub('', text)
#
# def stringrepr(string):
# ascii = string.encode('ascii', 'backslashreplace')
# quoted = "'" + ascii.replace("'", "\\'") + "'"
# if len(ascii) > len(string):
# return 'u' + quoted
# return quoted
. Output only the next line. | 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__(self, other):
return not self == other
def __eq__(self, other):
if isinstance(other, Namespace):
return self.uri == other.uri
return self.uri == other
def __getitem__(self, name):
return QName(self.uri + '}' + name)
__getattr__ = __getitem__
def __hash__(self):
return hash(self.uri)
def __repr__(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from functools import reduce
from itertools import chain
from genshi.util import plaintext, stripentities, striptags, stringrepr
from genshi.output import encode
from genshi.path import Path
from genshi.output import get_serializer
from genshi._speedups import Markup
import operator
and context:
# Path: genshi/util.py
# def plaintext(text, keeplinebreaks=True):
# """Return the text with all entities and tags removed.
#
# >>> plaintext('<b>1 < 2</b>')
# u'1 < 2'
#
# The `keeplinebreaks` parameter can be set to ``False`` to replace any line
# breaks by simple spaces:
#
# >>> plaintext('''<b>1
# ... <
# ... 2</b>''', keeplinebreaks=False)
# u'1 < 2'
#
# :param text: the text to convert to plain text
# :param keeplinebreaks: whether line breaks in the text should be kept intact
# :return: the text with tags and entities removed
# """
# text = stripentities(striptags(text))
# if not keeplinebreaks:
# text = text.replace('\n', ' ')
# return text
#
# def stripentities(text, keepxmlentities=False):
# """Return a copy of the given text with any character or numeric entities
# replaced by the equivalent UTF-8 characters.
#
# >>> stripentities('1 < 2')
# u'1 < 2'
# >>> stripentities('more …')
# u'more \u2026'
# >>> stripentities('…')
# u'\u2026'
# >>> stripentities('…')
# u'\u2026'
#
# If the `keepxmlentities` parameter is provided and is a truth value, the
# core XML entities (&, ', >, < and ") are left intact.
#
# >>> stripentities('1 < 2 …', keepxmlentities=True)
# u'1 < 2 \u2026'
# """
# def _replace_entity(match):
# if match.group(1): # numeric entity
# ref = match.group(1)
# if ref.startswith('x'):
# ref = int(ref[1:], 16)
# else:
# ref = int(ref, 10)
# return unichr(ref)
# else: # character entity
# ref = match.group(2)
# if keepxmlentities and ref in ('amp', 'apos', 'gt', 'lt', 'quot'):
# return '&%s;' % ref
# try:
# return unichr(entities.name2codepoint[ref])
# except KeyError:
# if keepxmlentities:
# return '&%s;' % ref
# else:
# return ref
# return _STRIPENTITIES_RE.sub(_replace_entity, text)
#
# def striptags(text):
# """Return a copy of the text with any XML/HTML tags removed.
#
# >>> striptags('<span>Foo</span> bar')
# 'Foo bar'
# >>> striptags('<span class="bar">Foo</span>')
# 'Foo'
# >>> striptags('Foo<br />')
# 'Foo'
#
# HTML/XML comments are stripped, too:
#
# >>> striptags('<!-- <blub>hehe</blah> -->test')
# 'test'
#
# :param text: the string to remove tags from
# :return: the text with tags removed
# """
# return _STRIPTAGS_RE.sub('', text)
#
# def stringrepr(string):
# ascii = string.encode('ascii', 'backslashreplace')
# quoted = "'" + ascii.replace("'", "\\'") + "'"
# if len(ascii) > len(string):
# return 'u' + quoted
# return quoted
which might include code, classes, or functions. Output only the next line. | 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 with the help of imports:
from modules.core.model.session.abstract import AbstractSession
from models import User
and context (classes, functions, sometimes code) from other files:
# Path: modules/core/model/session/abstract.py
# class AbstractSession(dict):
#
# namespace = 'undefined'
#
# def __init__(self):
#
# if self.namespace == 'undefined':
# raise AttributeError('namespace attribute is not defined in subclass')
#
# session = Registry().get('session')
#
# if self.namespace not in session:
# session[self.namespace] = self
# else:
# self.update(session[self.namespace])
# session[self.namespace] = self
#
# def set(self, key, value):
# self[key] = value
#
# def getSessId(self):
# return Registry().get('session').id
#
# def clear(self):
# sess = Registry().get('session')
#
# import logging
# logging.info(str(sess))
#
# sess.delete()
#
# Path: models.py
# class User(db.Model):
# name = db.StringProperty()
# access_key = db.StringProperty()
# email = db.StringProperty()
# password = db.StringProperty()
# is_admin = db.BooleanProperty()
#
# @property
# def chars(self):
# return Char.all().filter('owner = ', self.key())
#
# def generateAccessKey(self):
# import random
# random.seed()
# hash = random.getrandbits(128)
# self.access_key = "%016x" % hash
. Output only the next line. | 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.webapp import template
from lib.registry import Registry
from genshi.template import TemplateLoader
from genshi import Markup)
and context including class names, function names, or small code snippets from other files:
# Path: lib/registry.py
# class Registry(dict):
# def set(self, key, value):
# self[key] = value
# def get(self, key):
# if self.has_key(key):
# return self[key]
# else:
# return False
. Output only the next line. | template_vals['Registry']=Registry |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.