Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>"""
Parses event schemas and reports on their validity.
"""
class Command(BaseCommand):
def handle(self, *args, **options):
print("=> Searching for schema files...")
try:
if is_validation_enabled():
print("--> Schema validation enabled. Checking state..")
load_all_event_schemas()
<|code_end|>
, predict the next line using imports from the current file:
from django.core.management.base import BaseCommand
from djangoevents.exceptions import EventSchemaError
from djangoevents.schema import load_all_event_schemas, schemas
from djangoevents.settings import is_validation_enabled
and context including class names, function names, and sometimes code from other files:
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# def set_event_version(aggregate_cls, event_cls, avro_dir=None):
# def get_event_version(event_cls):
# def load_event_schema(aggregate, event):
# def event_to_schema_path(aggregate_cls, event_cls, avro_dir=None):
# def _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir):
# def _event_to_schema_path(aggregate_cls, event_cls, avro_dir, version):
# def decode_cls_name(cls):
# def parse_event_schema(spec_body):
# def get_schema_for_event(event_cls):
# def validate_event(event, schema=None):
#
# Path: djangoevents/settings.py
# def is_validation_enabled():
# config = get_config()
# return config.get('EVENT_SCHEMA_VALIDATION', {}).get('ENABLED', False)
. Output only the next line. | except EventSchemaError as e: |
Continue the code snippet: <|code_start|>"""
Parses event schemas and reports on their validity.
"""
class Command(BaseCommand):
def handle(self, *args, **options):
print("=> Searching for schema files...")
try:
if is_validation_enabled():
print("--> Schema validation enabled. Checking state..")
<|code_end|>
. Use current file imports:
from django.core.management.base import BaseCommand
from djangoevents.exceptions import EventSchemaError
from djangoevents.schema import load_all_event_schemas, schemas
from djangoevents.settings import is_validation_enabled
and context (classes, functions, or code) from other files:
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# def set_event_version(aggregate_cls, event_cls, avro_dir=None):
# def get_event_version(event_cls):
# def load_event_schema(aggregate, event):
# def event_to_schema_path(aggregate_cls, event_cls, avro_dir=None):
# def _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir):
# def _event_to_schema_path(aggregate_cls, event_cls, avro_dir, version):
# def decode_cls_name(cls):
# def parse_event_schema(spec_body):
# def get_schema_for_event(event_cls):
# def validate_event(event, schema=None):
#
# Path: djangoevents/settings.py
# def is_validation_enabled():
# config = get_config()
# return config.get('EVENT_SCHEMA_VALIDATION', {}).get('ENABLED', False)
. Output only the next line. | load_all_event_schemas() |
Based on the snippet: <|code_start|>"""
Parses event schemas and reports on their validity.
"""
class Command(BaseCommand):
def handle(self, *args, **options):
print("=> Searching for schema files...")
try:
if is_validation_enabled():
print("--> Schema validation enabled. Checking state..")
load_all_event_schemas()
except EventSchemaError as e:
print("Missing or invalid event schemas:")
print(e)
else:
print("--> Detected events:")
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.management.base import BaseCommand
from djangoevents.exceptions import EventSchemaError
from djangoevents.schema import load_all_event_schemas, schemas
from djangoevents.settings import is_validation_enabled
and context (classes, functions, sometimes code) from other files:
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# def set_event_version(aggregate_cls, event_cls, avro_dir=None):
# def get_event_version(event_cls):
# def load_event_schema(aggregate, event):
# def event_to_schema_path(aggregate_cls, event_cls, avro_dir=None):
# def _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir):
# def _event_to_schema_path(aggregate_cls, event_cls, avro_dir, version):
# def decode_cls_name(cls):
# def parse_event_schema(spec_body):
# def get_schema_for_event(event_cls):
# def validate_event(event, schema=None):
#
# Path: djangoevents/settings.py
# def is_validation_enabled():
# config = get_config()
# return config.get('EVENT_SCHEMA_VALIDATION', {}).get('ENABLED', False)
. Output only the next line. | for item in schemas.keys(): |
Using the snippet: <|code_start|>"""
Parses event schemas and reports on their validity.
"""
class Command(BaseCommand):
def handle(self, *args, **options):
print("=> Searching for schema files...")
try:
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from djangoevents.exceptions import EventSchemaError
from djangoevents.schema import load_all_event_schemas, schemas
from djangoevents.settings import is_validation_enabled
and context (class names, function names, or code) available:
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# def set_event_version(aggregate_cls, event_cls, avro_dir=None):
# def get_event_version(event_cls):
# def load_event_schema(aggregate, event):
# def event_to_schema_path(aggregate_cls, event_cls, avro_dir=None):
# def _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir):
# def _event_to_schema_path(aggregate_cls, event_cls, avro_dir, version):
# def decode_cls_name(cls):
# def parse_event_schema(spec_body):
# def get_schema_for_event(event_cls):
# def validate_event(event, schema=None):
#
# Path: djangoevents/settings.py
# def is_validation_enabled():
# config = get_config()
# return config.get('EVENT_SCHEMA_VALIDATION', {}).get('ENABLED', False)
. Output only the next line. | if is_validation_enabled(): |
Given the following code snippet before the placeholder: <|code_start|> def ready(self):
patch_domain_event()
autodiscover_modules('handlers')
autodiscover_modules('aggregates')
# Once all handlers & aggregates are loaded we can import aggregate schema files.
# `load_scheas()` assumes that all aggregates are imported at this point.
load_schemas()
def get_app_module_names():
return settings.INSTALLED_APPS
def load_schemas():
"""
Try loading all the event schemas and complain loud if failure occurred.
"""
try:
load_all_event_schemas()
except EventSchemaError as e:
warnings.warn(str(e), UserWarning)
def patch_domain_event():
"""
Patch `DomainEvent` to add `schema_version` to event payload.
"""
<|code_end|>
, predict the next line using imports from the current file:
from django.apps import AppConfig as BaseAppConfig
from django.conf import settings
from django.utils.module_loading import autodiscover_modules
from djangoevents import DomainEvent
from .exceptions import EventSchemaError
from .settings import adds_schema_version_to_event_data
from .schema import get_event_version
from .schema import load_all_event_schemas
import warnings
and context including class names, function names, and sometimes code from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/settings.py
# def adds_schema_version_to_event_data():
# config = get_config()
# return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False)
#
# Path: djangoevents/schema.py
# def get_event_version(event_cls):
# return getattr(event_cls, 'version', None) or 1
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# """
# Initializes aggregate event schemas lookup cache.
# """
# errors = []
# for aggregate in list_concrete_aggregates():
# for event in list_aggregate_events(aggregate_cls=aggregate):
# try:
# schemas[event] = load_event_schema(aggregate, event)
# except EventSchemaError as e:
# errors.append(str(e))
#
# # Serve all schema errors at once not iteratively.
# if errors:
# raise EventSchemaError("\n".join(errors))
#
# return schemas
. Output only the next line. | old_init = DomainEvent.__init__ |
Based on the snippet: <|code_start|>
class AppConfig(BaseAppConfig):
name = 'djangoevents'
def ready(self):
patch_domain_event()
autodiscover_modules('handlers')
autodiscover_modules('aggregates')
# Once all handlers & aggregates are loaded we can import aggregate schema files.
# `load_scheas()` assumes that all aggregates are imported at this point.
load_schemas()
def get_app_module_names():
return settings.INSTALLED_APPS
def load_schemas():
"""
Try loading all the event schemas and complain loud if failure occurred.
"""
try:
load_all_event_schemas()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.apps import AppConfig as BaseAppConfig
from django.conf import settings
from django.utils.module_loading import autodiscover_modules
from djangoevents import DomainEvent
from .exceptions import EventSchemaError
from .settings import adds_schema_version_to_event_data
from .schema import get_event_version
from .schema import load_all_event_schemas
import warnings
and context (classes, functions, sometimes code) from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/settings.py
# def adds_schema_version_to_event_data():
# config = get_config()
# return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False)
#
# Path: djangoevents/schema.py
# def get_event_version(event_cls):
# return getattr(event_cls, 'version', None) or 1
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# """
# Initializes aggregate event schemas lookup cache.
# """
# errors = []
# for aggregate in list_concrete_aggregates():
# for event in list_aggregate_events(aggregate_cls=aggregate):
# try:
# schemas[event] = load_event_schema(aggregate, event)
# except EventSchemaError as e:
# errors.append(str(e))
#
# # Serve all schema errors at once not iteratively.
# if errors:
# raise EventSchemaError("\n".join(errors))
#
# return schemas
. Output only the next line. | except EventSchemaError as e: |
Next line prediction: <|code_start|>
# Once all handlers & aggregates are loaded we can import aggregate schema files.
# `load_scheas()` assumes that all aggregates are imported at this point.
load_schemas()
def get_app_module_names():
return settings.INSTALLED_APPS
def load_schemas():
"""
Try loading all the event schemas and complain loud if failure occurred.
"""
try:
load_all_event_schemas()
except EventSchemaError as e:
warnings.warn(str(e), UserWarning)
def patch_domain_event():
"""
Patch `DomainEvent` to add `schema_version` to event payload.
"""
old_init = DomainEvent.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
<|code_end|>
. Use current file imports:
(from django.apps import AppConfig as BaseAppConfig
from django.conf import settings
from django.utils.module_loading import autodiscover_modules
from djangoevents import DomainEvent
from .exceptions import EventSchemaError
from .settings import adds_schema_version_to_event_data
from .schema import get_event_version
from .schema import load_all_event_schemas
import warnings)
and context including class names, function names, or small code snippets from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/settings.py
# def adds_schema_version_to_event_data():
# config = get_config()
# return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False)
#
# Path: djangoevents/schema.py
# def get_event_version(event_cls):
# return getattr(event_cls, 'version', None) or 1
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# """
# Initializes aggregate event schemas lookup cache.
# """
# errors = []
# for aggregate in list_concrete_aggregates():
# for event in list_aggregate_events(aggregate_cls=aggregate):
# try:
# schemas[event] = load_event_schema(aggregate, event)
# except EventSchemaError as e:
# errors.append(str(e))
#
# # Serve all schema errors at once not iteratively.
# if errors:
# raise EventSchemaError("\n".join(errors))
#
# return schemas
. Output only the next line. | if adds_schema_version_to_event_data(): |
Given snippet: <|code_start|>
def get_app_module_names():
return settings.INSTALLED_APPS
def load_schemas():
"""
Try loading all the event schemas and complain loud if failure occurred.
"""
try:
load_all_event_schemas()
except EventSchemaError as e:
warnings.warn(str(e), UserWarning)
def patch_domain_event():
"""
Patch `DomainEvent` to add `schema_version` to event payload.
"""
old_init = DomainEvent.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
if adds_schema_version_to_event_data():
dct = self.__dict__
key = 'schema_version'
if key not in dct:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.apps import AppConfig as BaseAppConfig
from django.conf import settings
from django.utils.module_loading import autodiscover_modules
from djangoevents import DomainEvent
from .exceptions import EventSchemaError
from .settings import adds_schema_version_to_event_data
from .schema import get_event_version
from .schema import load_all_event_schemas
import warnings
and context:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/settings.py
# def adds_schema_version_to_event_data():
# config = get_config()
# return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False)
#
# Path: djangoevents/schema.py
# def get_event_version(event_cls):
# return getattr(event_cls, 'version', None) or 1
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# """
# Initializes aggregate event schemas lookup cache.
# """
# errors = []
# for aggregate in list_concrete_aggregates():
# for event in list_aggregate_events(aggregate_cls=aggregate):
# try:
# schemas[event] = load_event_schema(aggregate, event)
# except EventSchemaError as e:
# errors.append(str(e))
#
# # Serve all schema errors at once not iteratively.
# if errors:
# raise EventSchemaError("\n".join(errors))
#
# return schemas
which might include code, classes, or functions. Output only the next line. | dct[key] = get_event_version(self.__class__) |
Using the snippet: <|code_start|>
class AppConfig(BaseAppConfig):
name = 'djangoevents'
def ready(self):
patch_domain_event()
autodiscover_modules('handlers')
autodiscover_modules('aggregates')
# Once all handlers & aggregates are loaded we can import aggregate schema files.
# `load_scheas()` assumes that all aggregates are imported at this point.
load_schemas()
def get_app_module_names():
return settings.INSTALLED_APPS
def load_schemas():
"""
Try loading all the event schemas and complain loud if failure occurred.
"""
try:
<|code_end|>
, determine the next line of code. You have imports:
from django.apps import AppConfig as BaseAppConfig
from django.conf import settings
from django.utils.module_loading import autodiscover_modules
from djangoevents import DomainEvent
from .exceptions import EventSchemaError
from .settings import adds_schema_version_to_event_data
from .schema import get_event_version
from .schema import load_all_event_schemas
import warnings
and context (class names, function names, or code) available:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/exceptions.py
# class EventSchemaError(DjangoeventsError):
# pass
#
# Path: djangoevents/settings.py
# def adds_schema_version_to_event_data():
# config = get_config()
# return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False)
#
# Path: djangoevents/schema.py
# def get_event_version(event_cls):
# return getattr(event_cls, 'version', None) or 1
#
# Path: djangoevents/schema.py
# def load_all_event_schemas():
# """
# Initializes aggregate event schemas lookup cache.
# """
# errors = []
# for aggregate in list_concrete_aggregates():
# for event in list_aggregate_events(aggregate_cls=aggregate):
# try:
# schemas[event] = load_event_schema(aggregate, event)
# except EventSchemaError as e:
# errors.append(str(e))
#
# # Serve all schema errors at once not iteratively.
# if errors:
# raise EventSchemaError("\n".join(errors))
#
# return schemas
. Output only the next line. | load_all_event_schemas() |
Here is a snippet: <|code_start|>
def test_list_subclasses_when_none():
class Parent:
pass
assert _list_subclasses(Parent) == []
def list_internal_classes():
class Parent:
class Child1:
pass
class Child2:
class GrandChild:
pass
# Please note that GrandChild is not on the list!
assert set(_list_internal_classes(Parent)) == {Parent.Child1, Parent.Child2}
def list_internal_classes_none():
class Parent:
pass
assert _list_internal_classes(Parent) == []
def test_list_aggregates_skip_abstract():
<|code_end|>
. Write the next line using the current file imports:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest
and context from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
, which may include functions, classes, or code. Output only the next line. | class Aggregate1(BaseAggregate): |
Given the following code snippet before the placeholder: <|code_start|>def list_internal_classes_none():
class Parent:
pass
assert _list_internal_classes(Parent) == []
def test_list_aggregates_skip_abstract():
class Aggregate1(BaseAggregate):
pass
@abstract
class Aggregate2(BaseAggregate):
pass
with mock.patch('djangoevents.utils._list_subclasses') as list_subclasses:
list_subclasses.return_value = [Aggregate1, Aggregate2]
aggregates = list_concrete_aggregates()
assert aggregates == [Aggregate1]
def test_list_aggregates_none_present():
with mock.patch('djangoevents.utils._list_subclasses') as list_subclasses:
list_subclasses.return_value = []
aggregates = list_concrete_aggregates()
assert aggregates == []
def test_list_events_sample_event_appart_from_abstract():
class Aggregate(BaseAggregate):
<|code_end|>
, predict the next line using imports from the current file:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
. Output only the next line. | class Evt1(DomainEvent): |
Based on the snippet: <|code_start|> class Parent:
pass
assert _list_subclasses(Parent) == []
def list_internal_classes():
class Parent:
class Child1:
pass
class Child2:
class GrandChild:
pass
# Please note that GrandChild is not on the list!
assert set(_list_internal_classes(Parent)) == {Parent.Child1, Parent.Child2}
def list_internal_classes_none():
class Parent:
pass
assert _list_internal_classes(Parent) == []
def test_list_aggregates_skip_abstract():
class Aggregate1(BaseAggregate):
pass
<|code_end|>
, predict the immediate next line with the help of imports:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
. Output only the next line. | @abstract |
Using the snippet: <|code_start|> class Evt2(DomainEvent):
def mutate_event(self, *args, **kwargs):
pass
class Evt3(DomainEvent):
# No mutate_event present
pass
@abstract
class Evt4(DomainEvent):
def mutate_event(self, *args, **kwargs):
pass
events = list_aggregate_events(Aggregate)
assert set(events) == {Aggregate.Evt1, Aggregate.Evt2}
def test_list_events_not_an_aggregate():
events = list_aggregate_events(list)
assert events == []
@pytest.mark.parametrize('name, expected_output', [
('UserRegistered', 'user_registered'),
('UserRegisteredWithEmail', 'user_registered_with_email'),
('HttpResponse', 'http_response'),
('HTTPResponse', 'http_response'),
('already_snake', 'already_snake'),
])
def test_camel_case_to_snake_case(name, expected_output):
<|code_end|>
, determine the next line of code. You have imports:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest
and context (class names, function names, or code) available:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
. Output only the next line. | assert expected_output == camel_case_to_snake_case(name) |
Next line prediction: <|code_start|> aggregates = list_concrete_aggregates()
assert aggregates == [Aggregate1]
def test_list_aggregates_none_present():
with mock.patch('djangoevents.utils._list_subclasses') as list_subclasses:
list_subclasses.return_value = []
aggregates = list_concrete_aggregates()
assert aggregates == []
def test_list_events_sample_event_appart_from_abstract():
class Aggregate(BaseAggregate):
class Evt1(DomainEvent):
def mutate_event(self, *args, **kwargs):
pass
class Evt2(DomainEvent):
def mutate_event(self, *args, **kwargs):
pass
class Evt3(DomainEvent):
# No mutate_event present
pass
@abstract
class Evt4(DomainEvent):
def mutate_event(self, *args, **kwargs):
pass
<|code_end|>
. Use current file imports:
(from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
. Output only the next line. | events = list_aggregate_events(Aggregate) |
Predict the next line after this snippet: <|code_start|>def list_internal_classes():
class Parent:
class Child1:
pass
class Child2:
class GrandChild:
pass
# Please note that GrandChild is not on the list!
assert set(_list_internal_classes(Parent)) == {Parent.Child1, Parent.Child2}
def list_internal_classes_none():
class Parent:
pass
assert _list_internal_classes(Parent) == []
def test_list_aggregates_skip_abstract():
class Aggregate1(BaseAggregate):
pass
@abstract
class Aggregate2(BaseAggregate):
pass
with mock.patch('djangoevents.utils._list_subclasses') as list_subclasses:
list_subclasses.return_value = [Aggregate1, Aggregate2]
<|code_end|>
using the current file's imports:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest
and any relevant context from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
. Output only the next line. | aggregates = list_concrete_aggregates() |
Next line prediction: <|code_start|>
def test_list_subclasses():
class Parent:
pass
class Child(Parent):
pass
class GrandChild(Child):
pass
<|code_end|>
. Use current file imports:
(from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
. Output only the next line. | assert set(_list_subclasses(Parent)) == {Child, GrandChild} |
Given snippet: <|code_start|>def test_list_subclasses():
class Parent:
pass
class Child(Parent):
pass
class GrandChild(Child):
pass
assert set(_list_subclasses(Parent)) == {Child, GrandChild}
def test_list_subclasses_when_none():
class Parent:
pass
assert _list_subclasses(Parent) == []
def list_internal_classes():
class Parent:
class Child1:
pass
class Child2:
class GrandChild:
pass
# Please note that GrandChild is not on the list!
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils import _list_internal_classes
from unittest import mock
import pytest
and context:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils.py
# def camel_case_to_snake_case(text):
#
# def repl(match):
# sep = match.group().lower()
# if match.start() > 0:
# sep = '_%s' % sep
# return sep
#
# return re.sub(r'[A-Z][a-z]', repl, text).lower()
#
# Path: djangoevents/utils.py
# def list_aggregate_events(aggregate_cls):
# """
# Lists all aggregate_cls events defined within the application.
# Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned.
# """
# events = _list_internal_classes(aggregate_cls, DomainEvent)
# return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
#
# Path: djangoevents/utils.py
# def list_concrete_aggregates():
# """
# Lists all non abstract aggregates defined within the application.
# """
# aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity))
# return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()]
#
# Path: djangoevents/utils.py
# def _list_subclasses(cls):
# """
# Recursively lists all subclasses of `cls`.
# """
# subclasses = cls.__subclasses__()
#
# for subclass in cls.__subclasses__():
# subclasses += _list_subclasses(subclass)
#
# return subclasses
#
# Path: djangoevents/utils.py
# def _list_internal_classes(cls, base_class=None):
# base_class = base_class or object
#
# return [cls_attribute for cls_attribute in cls.__dict__.values()
# if inspect.isclass(cls_attribute)
# and issubclass(cls_attribute, base_class)]
which might include code, classes, or functions. Output only the next line. | assert set(_list_internal_classes(Parent)) == {Parent.Child1, Parent.Child2} |
Predict the next line after this snippet: <|code_start|>
def test_subclass_of_abstract_event_is_not_abstract():
class Aggregate(BaseAggregate):
@abstract
<|code_end|>
using the current file's imports:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from djangoevents.utils_abstract import is_abstract
and any relevant context from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils_abstract.py
# def is_abstract(cls):
# return cls in _abstract_classes
. Output only the next line. | class Event1(DomainEvent): |
Continue the code snippet: <|code_start|>
def test_subclass_of_abstract_event_is_not_abstract():
class Aggregate(BaseAggregate):
@abstract
class Event1(DomainEvent):
pass
class Event2(Event1):
pass
<|code_end|>
. Use current file imports:
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from djangoevents.utils_abstract import is_abstract
and context (classes, functions, or code) from other files:
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# """
# `EventSourcedEntity` with saner mutator routing & naming:
#
# >>> class Asset(BaseAggregate):
# >>> class Created(BaseAggregate.Created):
# >>> def mutate(event, klass):
# >>> return klass(...)
# >>>
# >>> class Updated(DomainEvent):
# >>> def mutate(event, instance):
# >>> instance.connect = True
# >>> return instance
# """
#
# @classmethod
# def is_abstract_class(cls):
# return is_abstract(cls)
#
# @classmethod
# def mutate(cls, aggregate=None, event=None):
# if aggregate:
# aggregate._validate_originator(event)
#
# if not hasattr(event, 'mutate_event'):
# msg = "{} does not provide a mutate_event() method.".format(event.__class__)
# raise NotImplementedError(msg)
#
# aggregate = event.mutate_event(event, aggregate or cls)
# aggregate._increment_version()
# return aggregate
#
# @classmethod
# def create_for_event(cls, event):
# aggregate = cls(
# entity_id=event.entity_id,
# domain_event_id=event.domain_event_id,
# entity_version=event.entity_version,
# )
# return aggregate
#
# Path: djangoevents/domain.py
# class BaseAggregate(EventSourcedEntity):
# class BaseEntity(BaseAggregate):
# def is_abstract_class(cls):
# def mutate(cls, aggregate=None, event=None):
# def create_for_event(cls, event):
# def is_abstract_class(cls):
# def mutate(cls, entity=None, event=None):
#
# Path: djangoevents/utils_abstract.py
# def abstract(cls):
# """
# Decorator marking classes as abstract.
#
# The "abstract" mark is an internal tag. Classes can be checked for
# being abstract with the `is_abstract` function. The tag is non
# inheritable: every class or subclass has to be explicitly marked
# with the decorator to be considered abstract.
# """
#
# _abstract_classes.add(cls)
# return cls
#
# Path: djangoevents/utils_abstract.py
# def is_abstract(cls):
# return cls in _abstract_classes
. Output only the next line. | assert is_abstract(Aggregate.Event1) |
Using the snippet: <|code_start|> def version(self):
return int(self.__getElement('version'))
def changeset(self):
return self.__getElement('changeset')
def timestamp(self):
return dateutil.parser.isoparse(self.__getElement('timestamp'))
def user(self):
return self.__getElement('user')
def uid(self):
return self.__getElement('uid')
def userid(self):
return self.__getElement('uid')
def lat(self):
return float(self.__getElement('lat')) if self.__getElement('lat') else None
def lon(self):
return float(self.__getElement('lon')) if self.__getElement('lon') else None
def geometry(self):
return self.geometry()
def centerLat(self):
return float(self.__getElement('center')['lat']) if self.__getElement('center') else None
def centerLon(self):
return float(self.__getElement('center')['lon']) if self.__getElement('center') else None
### nodes
def __nodes(self):
return self.__getElement('nodes') if self._json is not None else self._soup.find_all('nd')
def nodes(self, shallow=True):
nodes = self.__nodes()
if nodes is None or len(nodes) == 0:
return []
<|code_end|>
, determine the next line of code. You have imports:
import copy
import dateutil.parser
import geojson
import re
import OSMPythonTools
from OSMPythonTools.internal.singletonApi import SingletonApi
from OSMPythonTools.internal.elementShallow import ElementShallow
and context (class names, function names, or code) available:
# Path: OSMPythonTools/internal/singletonApi.py
# class SingletonApi():
# __instance = None
# def __init__(self, *args, **kwargs):
# from OSMPythonTools.api import Api
# if not SingletonApi.__instance:
# SingletonApi.__instance = Api(*args, **kwargs)
# def __getattr__(self, name):
# return getattr(self.__instance, name)
#
# Path: OSMPythonTools/internal/elementShallow.py
# class ElementShallow(Response):
# def __init__(self, cacheMetadata):
# super().__init__(cacheMetadata)
# def type(self):
# return None
# def id(self):
# return None
# def typeId(self):
# return self.type() + '/' + str(self.id()) if self.type() != None and self.id() != None else None
# def typeIdShort(self):
# return self.type()[0] + str(self.id()) if self.type() != None and self.id() != None else None
# def areaId(self):
# return self._areaId(self.type(), self.id())
# def _areaId(self, type, id):
# if type == 'way':
# return id + 2400000000
# elif type == 'relation':
# return id + 3600000000
# else:
# return None
. Output only the next line. | api = SingletonApi() |
Continue the code snippet: <|code_start|>
def _extendAndRaiseException(e, msg):
msgComplete = str(e) + msg
OSMPythonTools.logger.exception(msgComplete)
raise(Exception(msgComplete))
<|code_end|>
. Use current file imports:
import copy
import dateutil.parser
import geojson
import re
import OSMPythonTools
from OSMPythonTools.internal.singletonApi import SingletonApi
from OSMPythonTools.internal.elementShallow import ElementShallow
and context (classes, functions, or code) from other files:
# Path: OSMPythonTools/internal/singletonApi.py
# class SingletonApi():
# __instance = None
# def __init__(self, *args, **kwargs):
# from OSMPythonTools.api import Api
# if not SingletonApi.__instance:
# SingletonApi.__instance = Api(*args, **kwargs)
# def __getattr__(self, name):
# return getattr(self.__instance, name)
#
# Path: OSMPythonTools/internal/elementShallow.py
# class ElementShallow(Response):
# def __init__(self, cacheMetadata):
# super().__init__(cacheMetadata)
# def type(self):
# return None
# def id(self):
# return None
# def typeId(self):
# return self.type() + '/' + str(self.id()) if self.type() != None and self.id() != None else None
# def typeIdShort(self):
# return self.type()[0] + str(self.id()) if self.type() != None and self.id() != None else None
# def areaId(self):
# return self._areaId(self.type(), self.id())
# def _areaId(self, type, id):
# if type == 'way':
# return id + 2400000000
# elif type == 'relation':
# return id + 3600000000
# else:
# return None
. Output only the next line. | class Element(ElementShallow): |
Continue the code snippet: <|code_start|>
@pytest.mark.parametrize(('cachingStrategyF'), [
lambda: CachingStrategy.use(JSON),
lambda: CachingStrategy.use(Pickle),
lambda: CachingStrategy.use(Pickle, gzip=False),
])
def test_cache(cachingStrategyF):
cachingStrategy = cachingStrategyF()
<|code_end|>
. Use current file imports:
import pytest
from OSMPythonTools.api import Api
from OSMPythonTools.cachingStrategy import CachingStrategy, JSON, Pickle
and context (classes, functions, or code) from other files:
# Path: OSMPythonTools/api.py
# class Api(CacheObject):
# def __init__(self, endpoint='http://www.openstreetmap.org/api/0.6/', **kwargs):
# super().__init__('api', endpoint, jsonResult=False, **kwargs)
#
# def _queryString(self, query, params={}, history=False):
# query = query + ('/history' if history else '')
# return (query, query, params)
#
# def _queryRequest(self, endpoint, queryString, params={}):
# return endpoint + queryString
#
# def _rawToResult(self, data, queryString, params, kwargs, cacheMetadata=None, shallow=False):
# return ApiResult(data, queryString, params, cacheMetadata=cacheMetadata, shallow=shallow, history=kwargs['history'] if 'history' in kwargs else False)
#
# Path: OSMPythonTools/cachingStrategy/json.py
# class JSON(CachingStrategyBase):
# def __init__(self, cacheDir='cache'):
# self._cacheDir = cacheDir
#
# def _filename(self, key):
# return os.path.join(self._cacheDir, key)
#
# def get(self, key):
# filename = self._filename(key)
# data = None
# if not os.path.exists(self._cacheDir):
# os.makedirs(self._cacheDir)
# if os.path.exists(filename):
# with open(filename, 'r') as file:
# data = ujson.load(file)
# return data
#
# def set(self, key, value):
# with open(self._filename(key), 'w') as file:
# ujson.dump(value, file)
#
# Path: OSMPythonTools/cachingStrategy/pickle.py
# class Pickle(CachingStrategyBase):
# def __init__(self, cacheFile='cache', gzip=True):
# self._cacheFile = cacheFile + '.pickle' + ('.gzip' if gzip else '')
# self._open = libraryGzip.open if gzip else open
# self.close()
#
# def get(self, key):
# if self._cache is None:
# self.open()
# return self._cache[key] if key in self._cache else None
#
# def set(self, key, value):
# if self._cache is None:
# self.open()
# with self._open(self._cacheFile, 'ab') as file:
# pickle.dump((key, value), file)
# self._cache[key] = value
#
# def open(self):
# if os.path.exists(self._cacheFile):
# with self._open(self._cacheFile, 'rb') as file:
# self._cache = {}
# try:
# while True:
# k, v = pickle.load(file)
# self._cache[k] = v
# except EOFError:
# pass
# else:
# self._cache = {}
#
# def close(self):
# self._cache = None
#
# Path: OSMPythonTools/cachingStrategy/strategy.py
# class CachingStrategy():
# __strategy = JSON()
# @classmethod
# def use(cls, strategy, **kwargs):
# cls.__strategy.close()
# cls.__strategy = strategy(**kwargs)
# return cls.__strategy
# @classmethod
# def get(cls, key):
# return cls.__strategy.get(key)
# @classmethod
# def set(cls, key, value):
# cls.__strategy.set(key, value)
. Output only the next line. | api = Api() |
Based on the snippet: <|code_start|>
class CacheObject:
def __init__(self, prefix, endpoint, waitBetweenQueries=None, jsonResult=True, userAgent=None):
self._prefix = prefix
self._endpoint = endpoint
self.__waitBetweenQueries = waitBetweenQueries
self.__lastQuery = None
self.__jsonResult = jsonResult
self.__userAgentProvidedByUser = userAgent
def query(self, *args, onlyCached=False, shallow=False, **kwargs):
queryString, hashString, params = self._queryString(*args, **kwargs)
key = self._prefix + '-' + self.__hash(hashString + ('????' + urllib.parse.urlencode(sorted(params.items())) if params else ''))
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import hashlib
import os
import time
import ujson
import urllib.request
import OSMPythonTools
from OSMPythonTools.cachingStrategy import CachingStrategy
and context (classes, functions, sometimes code) from other files:
# Path: OSMPythonTools/cachingStrategy/strategy.py
# class CachingStrategy():
# __strategy = JSON()
# @classmethod
# def use(cls, strategy, **kwargs):
# cls.__strategy.close()
# cls.__strategy = strategy(**kwargs)
# return cls.__strategy
# @classmethod
# def get(cls, key):
# return cls.__strategy.get(key)
# @classmethod
# def set(cls, key, value):
# cls.__strategy.set(key, value)
. Output only the next line. | data = CachingStrategy.get(key) |
Next line prediction: <|code_start|>
def metadata(x):
assert x.version() != None and x.version() != '' and float(x.version()) > 0
assert x.generator() != None and x.generator() != ''
assert x.copyright() != None and x.copyright() != ''
assert x.attribution() != None and x.attribution() != ''
assert x.license() != None and x.license() != ''
def test_node():
<|code_end|>
. Use current file imports:
(from OSMPythonTools.api import Api)
and context including class names, function names, or small code snippets from other files:
# Path: OSMPythonTools/api.py
# class Api(CacheObject):
# def __init__(self, endpoint='http://www.openstreetmap.org/api/0.6/', **kwargs):
# super().__init__('api', endpoint, jsonResult=False, **kwargs)
#
# def _queryString(self, query, params={}, history=False):
# query = query + ('/history' if history else '')
# return (query, query, params)
#
# def _queryRequest(self, endpoint, queryString, params={}):
# return endpoint + queryString
#
# def _rawToResult(self, data, queryString, params, kwargs, cacheMetadata=None, shallow=False):
# return ApiResult(data, queryString, params, cacheMetadata=cacheMetadata, shallow=shallow, history=kwargs['history'] if 'history' in kwargs else False)
. Output only the next line. | api = Api() |
Using the snippet: <|code_start|>
@click.command(
help='Print or check SHA1 checksums',
)
@click.help_option('-h', '--help')
@click.option('-c', '--check', is_flag=True, default=False, help='read SHA1 sums from the FILEs and check them')
@click.option('--tag', is_flag=True, default=False, help='Output a BSD-style checksum file')
@click.option('--quiet', is_flag=True, default=False, help="don't print OK for each successfully verified file")
@click.option('--status', is_flag=True, default=False, help="don't output anything, status code shows success")
@click.argument('files', metavar='FILE', required=False, nargs=-1, type=click.File('rb'))
def subcommand(check, tag, quiet, status, files):
if len(files) == 0:
files = (click.get_binary_stream('stdin'),)
<|code_end|>
, determine the next line of code. You have imports:
import sys
from ..hasher import HasherCommand
from ...vendor import click
and context (class names, function names, or code) available:
# Path: pycoreutils/commands/hasher.py
# class HasherCommand(object):
# def __init__(self, algorithm, tag=False, quiet=False, status=False):
# """
# :param algorithm: the hashing algorithm to use (eg. 'sha1', 'md5')
# """
# self.algorithm = algorithm
# self.tag = tag
# self.quiet = quiet
# self.status = status
#
# hashlen = len(hashlib.new(algorithm).hexdigest())
# self.checksum_line_regex = re.compile('^(?P<checksum>[a-f0-9]{{{hashlen}}}) (?P<filepath>.+)$'.format(hashlen=hashlen).encode('ascii'))
#
# def process_files(self, files, check=False):
# success = True
#
# if check and self.tag:
# raise click.BadOptionUsage('the --tag option is meaningless when verifying checksums')
#
# if not check and (self.status or self.quiet):
# raise click.BadOptionUsage('--status is only meaningful when verifying checksums')
#
# for file in files:
# if not check:
# # in testing, BytesIO has not attribute "name"
# filepath = getattr(file, 'name', '-')
# checksum = self.checksum_calculator(file)
# if self.tag:
# click.echo('{} ({}) = {}'.format(self.algorithm.upper(), filepath, checksum))
# else:
# click.echo('{} {}'.format(checksum, filepath))
# else:
# success = self.checksum_verifier(file) and success
#
# return success
#
# def checksum_calculator(self, file):
# """
# Computes a checksum using the class' algorithm
# Returns a unicode of the hexdigest
#
# Assumes the file is opened in binary mode
# """
# h = hashlib.new(self.algorithm)
# for data in iter(functools.partial(file.read, 4096), b''):
# h.update(data)
# return h.hexdigest()
#
# def checksum_verifier(self, file):
# noformat_count = 0
# nomatch_count = 0
# noread_count = 0
#
# for line in file:
# match = self.checksum_line_regex.match(line)
# if not match:
# noformat_count += 1
# else:
# group = match.groupdict()
# checksum = group['checksum']
# filepath = click.format_filename(group['filepath'])
# try:
# with click.open_file(filepath, 'rb') as fd:
# calculated_checksum = self.checksum_calculator(fd).encode('ascii')
# except IOError:
# noread_count += 1
# if not self.status:
# click.echo('{}: FAILED open or read'.format(filepath))
# continue
#
# if checksum == calculated_checksum:
# output = 'OK'
# else:
# output = 'FAILED'
# nomatch_count += 1
#
# if not self.status:
# if not self.quiet or output != 'OK':
# click.echo('{}: {}'.format(filepath, output))
#
# if not self.status:
# if noformat_count == 1:
# click.echo('WARNING: 1 line is improperly formatted', err=True)
# if noformat_count > 1:
# click.echo('WARNING: {} lines are improperly formatted'.format(noformat_count), err=True)
# if noread_count == 1:
# click.echo('WARNING: 1 listed file could not be read', err=True)
# if noread_count > 1:
# click.echo('WARNING: {} listed files could not be read'.format(noread_count), err=True)
# if nomatch_count == 1:
# click.echo('WARNING: 1 computed checksum did NOT match', err=True)
# if nomatch_count > 1:
# click.echo('WARNING: {} computed checksum did NOT match'.format(nomatch_count), err=True)
#
# return noformat_count + nomatch_count + noread_count == 0
. Output only the next line. | hasher = HasherCommand('sha1', tag, quiet, status) |
Given the following code snippet before the placeholder: <|code_start|>
@click.command(
help='Print or check SHA224 checksums',
)
@click.help_option('-h', '--help')
@click.option('-c', '--check', is_flag=True, default=False, help='read SHA224 sums from the FILEs and check them')
@click.option('--tag', is_flag=True, default=False, help='Output a BSD-style checksum file')
@click.option('--quiet', is_flag=True, default=False, help="don't print OK for each successfully verified file")
@click.option('--status', is_flag=True, default=False, help="don't output anything, status code shows success")
@click.argument('files', metavar='FILE', required=False, nargs=-1, type=click.File('rb'))
def subcommand(check, tag, quiet, status, files):
if len(files) == 0:
files = (click.get_binary_stream('stdin'),)
<|code_end|>
, predict the next line using imports from the current file:
import sys
from ..hasher import HasherCommand
from ...vendor import click
and context including class names, function names, and sometimes code from other files:
# Path: pycoreutils/commands/hasher.py
# class HasherCommand(object):
# def __init__(self, algorithm, tag=False, quiet=False, status=False):
# """
# :param algorithm: the hashing algorithm to use (eg. 'sha1', 'md5')
# """
# self.algorithm = algorithm
# self.tag = tag
# self.quiet = quiet
# self.status = status
#
# hashlen = len(hashlib.new(algorithm).hexdigest())
# self.checksum_line_regex = re.compile('^(?P<checksum>[a-f0-9]{{{hashlen}}}) (?P<filepath>.+)$'.format(hashlen=hashlen).encode('ascii'))
#
# def process_files(self, files, check=False):
# success = True
#
# if check and self.tag:
# raise click.BadOptionUsage('the --tag option is meaningless when verifying checksums')
#
# if not check and (self.status or self.quiet):
# raise click.BadOptionUsage('--status is only meaningful when verifying checksums')
#
# for file in files:
# if not check:
# # in testing, BytesIO has not attribute "name"
# filepath = getattr(file, 'name', '-')
# checksum = self.checksum_calculator(file)
# if self.tag:
# click.echo('{} ({}) = {}'.format(self.algorithm.upper(), filepath, checksum))
# else:
# click.echo('{} {}'.format(checksum, filepath))
# else:
# success = self.checksum_verifier(file) and success
#
# return success
#
# def checksum_calculator(self, file):
# """
# Computes a checksum using the class' algorithm
# Returns a unicode of the hexdigest
#
# Assumes the file is opened in binary mode
# """
# h = hashlib.new(self.algorithm)
# for data in iter(functools.partial(file.read, 4096), b''):
# h.update(data)
# return h.hexdigest()
#
# def checksum_verifier(self, file):
# noformat_count = 0
# nomatch_count = 0
# noread_count = 0
#
# for line in file:
# match = self.checksum_line_regex.match(line)
# if not match:
# noformat_count += 1
# else:
# group = match.groupdict()
# checksum = group['checksum']
# filepath = click.format_filename(group['filepath'])
# try:
# with click.open_file(filepath, 'rb') as fd:
# calculated_checksum = self.checksum_calculator(fd).encode('ascii')
# except IOError:
# noread_count += 1
# if not self.status:
# click.echo('{}: FAILED open or read'.format(filepath))
# continue
#
# if checksum == calculated_checksum:
# output = 'OK'
# else:
# output = 'FAILED'
# nomatch_count += 1
#
# if not self.status:
# if not self.quiet or output != 'OK':
# click.echo('{}: {}'.format(filepath, output))
#
# if not self.status:
# if noformat_count == 1:
# click.echo('WARNING: 1 line is improperly formatted', err=True)
# if noformat_count > 1:
# click.echo('WARNING: {} lines are improperly formatted'.format(noformat_count), err=True)
# if noread_count == 1:
# click.echo('WARNING: 1 listed file could not be read', err=True)
# if noread_count > 1:
# click.echo('WARNING: {} listed files could not be read'.format(noread_count), err=True)
# if nomatch_count == 1:
# click.echo('WARNING: 1 computed checksum did NOT match', err=True)
# if nomatch_count > 1:
# click.echo('WARNING: {} computed checksum did NOT match'.format(nomatch_count), err=True)
#
# return noformat_count + nomatch_count + noread_count == 0
. Output only the next line. | hasher = HasherCommand('sha224', tag, quiet, status) |
Next line prediction: <|code_start|>
@click.command(
help='Print or check SHA512 checksums',
)
@click.help_option('-h', '--help')
@click.option('-c', '--check', is_flag=True, default=False, help='read SHA512 sums from the FILEs and check them')
@click.option('--tag', is_flag=True, default=False, help='Output a BSD-style checksum file')
@click.option('--quiet', is_flag=True, default=False, help="don't print OK for each successfully verified file")
@click.option('--status', is_flag=True, default=False, help="don't output anything, status code shows success")
@click.argument('files', metavar='FILE', required=False, nargs=-1, type=click.File('rb'))
def subcommand(check, tag, quiet, status, files):
if len(files) == 0:
files = (click.get_binary_stream('stdin'),)
<|code_end|>
. Use current file imports:
(import sys
from ..hasher import HasherCommand
from ...vendor import click)
and context including class names, function names, or small code snippets from other files:
# Path: pycoreutils/commands/hasher.py
# class HasherCommand(object):
# def __init__(self, algorithm, tag=False, quiet=False, status=False):
# """
# :param algorithm: the hashing algorithm to use (eg. 'sha1', 'md5')
# """
# self.algorithm = algorithm
# self.tag = tag
# self.quiet = quiet
# self.status = status
#
# hashlen = len(hashlib.new(algorithm).hexdigest())
# self.checksum_line_regex = re.compile('^(?P<checksum>[a-f0-9]{{{hashlen}}}) (?P<filepath>.+)$'.format(hashlen=hashlen).encode('ascii'))
#
# def process_files(self, files, check=False):
# success = True
#
# if check and self.tag:
# raise click.BadOptionUsage('the --tag option is meaningless when verifying checksums')
#
# if not check and (self.status or self.quiet):
# raise click.BadOptionUsage('--status is only meaningful when verifying checksums')
#
# for file in files:
# if not check:
# # in testing, BytesIO has not attribute "name"
# filepath = getattr(file, 'name', '-')
# checksum = self.checksum_calculator(file)
# if self.tag:
# click.echo('{} ({}) = {}'.format(self.algorithm.upper(), filepath, checksum))
# else:
# click.echo('{} {}'.format(checksum, filepath))
# else:
# success = self.checksum_verifier(file) and success
#
# return success
#
# def checksum_calculator(self, file):
# """
# Computes a checksum using the class' algorithm
# Returns a unicode of the hexdigest
#
# Assumes the file is opened in binary mode
# """
# h = hashlib.new(self.algorithm)
# for data in iter(functools.partial(file.read, 4096), b''):
# h.update(data)
# return h.hexdigest()
#
# def checksum_verifier(self, file):
# noformat_count = 0
# nomatch_count = 0
# noread_count = 0
#
# for line in file:
# match = self.checksum_line_regex.match(line)
# if not match:
# noformat_count += 1
# else:
# group = match.groupdict()
# checksum = group['checksum']
# filepath = click.format_filename(group['filepath'])
# try:
# with click.open_file(filepath, 'rb') as fd:
# calculated_checksum = self.checksum_calculator(fd).encode('ascii')
# except IOError:
# noread_count += 1
# if not self.status:
# click.echo('{}: FAILED open or read'.format(filepath))
# continue
#
# if checksum == calculated_checksum:
# output = 'OK'
# else:
# output = 'FAILED'
# nomatch_count += 1
#
# if not self.status:
# if not self.quiet or output != 'OK':
# click.echo('{}: {}'.format(filepath, output))
#
# if not self.status:
# if noformat_count == 1:
# click.echo('WARNING: 1 line is improperly formatted', err=True)
# if noformat_count > 1:
# click.echo('WARNING: {} lines are improperly formatted'.format(noformat_count), err=True)
# if noread_count == 1:
# click.echo('WARNING: 1 listed file could not be read', err=True)
# if noread_count > 1:
# click.echo('WARNING: {} listed files could not be read'.format(noread_count), err=True)
# if nomatch_count == 1:
# click.echo('WARNING: 1 computed checksum did NOT match', err=True)
# if nomatch_count > 1:
# click.echo('WARNING: {} computed checksum did NOT match'.format(nomatch_count), err=True)
#
# return noformat_count + nomatch_count + noread_count == 0
. Output only the next line. | hasher = HasherCommand('sha512', tag, quiet, status) |
Predict the next line for this snippet: <|code_start|>
@click.command(
help='Print or check SHA384 checksums',
)
@click.help_option('-h', '--help')
@click.option('-c', '--check', is_flag=True, default=False, help='read SHA384 sums from the FILEs and check them')
@click.option('--tag', is_flag=True, default=False, help='Output a BSD-style checksum file')
@click.option('--quiet', is_flag=True, default=False, help="don't print OK for each successfully verified file")
@click.option('--status', is_flag=True, default=False, help="don't output anything, status code shows success")
@click.argument('files', metavar='FILE', required=False, nargs=-1, type=click.File('rb'))
def subcommand(check, tag, quiet, status, files):
if len(files) == 0:
files = (click.get_binary_stream('stdin'),)
<|code_end|>
with the help of current file imports:
import sys
from ..hasher import HasherCommand
from ...vendor import click
and context from other files:
# Path: pycoreutils/commands/hasher.py
# class HasherCommand(object):
# def __init__(self, algorithm, tag=False, quiet=False, status=False):
# """
# :param algorithm: the hashing algorithm to use (eg. 'sha1', 'md5')
# """
# self.algorithm = algorithm
# self.tag = tag
# self.quiet = quiet
# self.status = status
#
# hashlen = len(hashlib.new(algorithm).hexdigest())
# self.checksum_line_regex = re.compile('^(?P<checksum>[a-f0-9]{{{hashlen}}}) (?P<filepath>.+)$'.format(hashlen=hashlen).encode('ascii'))
#
# def process_files(self, files, check=False):
# success = True
#
# if check and self.tag:
# raise click.BadOptionUsage('the --tag option is meaningless when verifying checksums')
#
# if not check and (self.status or self.quiet):
# raise click.BadOptionUsage('--status is only meaningful when verifying checksums')
#
# for file in files:
# if not check:
# # in testing, BytesIO has not attribute "name"
# filepath = getattr(file, 'name', '-')
# checksum = self.checksum_calculator(file)
# if self.tag:
# click.echo('{} ({}) = {}'.format(self.algorithm.upper(), filepath, checksum))
# else:
# click.echo('{} {}'.format(checksum, filepath))
# else:
# success = self.checksum_verifier(file) and success
#
# return success
#
# def checksum_calculator(self, file):
# """
# Computes a checksum using the class' algorithm
# Returns a unicode of the hexdigest
#
# Assumes the file is opened in binary mode
# """
# h = hashlib.new(self.algorithm)
# for data in iter(functools.partial(file.read, 4096), b''):
# h.update(data)
# return h.hexdigest()
#
# def checksum_verifier(self, file):
# noformat_count = 0
# nomatch_count = 0
# noread_count = 0
#
# for line in file:
# match = self.checksum_line_regex.match(line)
# if not match:
# noformat_count += 1
# else:
# group = match.groupdict()
# checksum = group['checksum']
# filepath = click.format_filename(group['filepath'])
# try:
# with click.open_file(filepath, 'rb') as fd:
# calculated_checksum = self.checksum_calculator(fd).encode('ascii')
# except IOError:
# noread_count += 1
# if not self.status:
# click.echo('{}: FAILED open or read'.format(filepath))
# continue
#
# if checksum == calculated_checksum:
# output = 'OK'
# else:
# output = 'FAILED'
# nomatch_count += 1
#
# if not self.status:
# if not self.quiet or output != 'OK':
# click.echo('{}: {}'.format(filepath, output))
#
# if not self.status:
# if noformat_count == 1:
# click.echo('WARNING: 1 line is improperly formatted', err=True)
# if noformat_count > 1:
# click.echo('WARNING: {} lines are improperly formatted'.format(noformat_count), err=True)
# if noread_count == 1:
# click.echo('WARNING: 1 listed file could not be read', err=True)
# if noread_count > 1:
# click.echo('WARNING: {} listed files could not be read'.format(noread_count), err=True)
# if nomatch_count == 1:
# click.echo('WARNING: 1 computed checksum did NOT match', err=True)
# if nomatch_count > 1:
# click.echo('WARNING: {} computed checksum did NOT match'.format(nomatch_count), err=True)
#
# return noformat_count + nomatch_count + noread_count == 0
, which may contain function names, class names, or code. Output only the next line. | hasher = HasherCommand('sha384', tag, quiet, status) |
Continue the code snippet: <|code_start|>
@click.command(
help='Print or check MD5 checksums',
)
@click.help_option('-h', '--help')
@click.option('-c', '--check', is_flag=True, default=False, help='read MD5 sums from the FILEs and check them')
@click.option('--tag', is_flag=True, default=False, help='Output a BSD-style checksum file')
@click.option('--quiet', is_flag=True, default=False, help="don't print OK for each successfully verified file")
@click.option('--status', is_flag=True, default=False, help="don't output anything, status code shows success")
@click.argument('files', metavar='FILE', required=False, nargs=-1, type=click.File('rb'))
def subcommand(check, tag, quiet, status, files):
if len(files) == 0:
files = (click.get_binary_stream('stdin'),)
<|code_end|>
. Use current file imports:
import sys
from ..hasher import HasherCommand
from ...vendor import click
and context (classes, functions, or code) from other files:
# Path: pycoreutils/commands/hasher.py
# class HasherCommand(object):
# def __init__(self, algorithm, tag=False, quiet=False, status=False):
# """
# :param algorithm: the hashing algorithm to use (eg. 'sha1', 'md5')
# """
# self.algorithm = algorithm
# self.tag = tag
# self.quiet = quiet
# self.status = status
#
# hashlen = len(hashlib.new(algorithm).hexdigest())
# self.checksum_line_regex = re.compile('^(?P<checksum>[a-f0-9]{{{hashlen}}}) (?P<filepath>.+)$'.format(hashlen=hashlen).encode('ascii'))
#
# def process_files(self, files, check=False):
# success = True
#
# if check and self.tag:
# raise click.BadOptionUsage('the --tag option is meaningless when verifying checksums')
#
# if not check and (self.status or self.quiet):
# raise click.BadOptionUsage('--status is only meaningful when verifying checksums')
#
# for file in files:
# if not check:
# # in testing, BytesIO has not attribute "name"
# filepath = getattr(file, 'name', '-')
# checksum = self.checksum_calculator(file)
# if self.tag:
# click.echo('{} ({}) = {}'.format(self.algorithm.upper(), filepath, checksum))
# else:
# click.echo('{} {}'.format(checksum, filepath))
# else:
# success = self.checksum_verifier(file) and success
#
# return success
#
# def checksum_calculator(self, file):
# """
# Computes a checksum using the class' algorithm
# Returns a unicode of the hexdigest
#
# Assumes the file is opened in binary mode
# """
# h = hashlib.new(self.algorithm)
# for data in iter(functools.partial(file.read, 4096), b''):
# h.update(data)
# return h.hexdigest()
#
# def checksum_verifier(self, file):
# noformat_count = 0
# nomatch_count = 0
# noread_count = 0
#
# for line in file:
# match = self.checksum_line_regex.match(line)
# if not match:
# noformat_count += 1
# else:
# group = match.groupdict()
# checksum = group['checksum']
# filepath = click.format_filename(group['filepath'])
# try:
# with click.open_file(filepath, 'rb') as fd:
# calculated_checksum = self.checksum_calculator(fd).encode('ascii')
# except IOError:
# noread_count += 1
# if not self.status:
# click.echo('{}: FAILED open or read'.format(filepath))
# continue
#
# if checksum == calculated_checksum:
# output = 'OK'
# else:
# output = 'FAILED'
# nomatch_count += 1
#
# if not self.status:
# if not self.quiet or output != 'OK':
# click.echo('{}: {}'.format(filepath, output))
#
# if not self.status:
# if noformat_count == 1:
# click.echo('WARNING: 1 line is improperly formatted', err=True)
# if noformat_count > 1:
# click.echo('WARNING: {} lines are improperly formatted'.format(noformat_count), err=True)
# if noread_count == 1:
# click.echo('WARNING: 1 listed file could not be read', err=True)
# if noread_count > 1:
# click.echo('WARNING: {} listed files could not be read'.format(noread_count), err=True)
# if nomatch_count == 1:
# click.echo('WARNING: 1 computed checksum did NOT match', err=True)
# if nomatch_count > 1:
# click.echo('WARNING: {} computed checksum did NOT match'.format(nomatch_count), err=True)
#
# return noformat_count + nomatch_count + noread_count == 0
. Output only the next line. | hasher = HasherCommand('md5', tag, quiet, status) |
Predict the next line after this snippet: <|code_start|>from __future__ import unicode_literals
class TestBaseName(PycoreutilsBaseTest):
def test_get_base_name(self):
pairs = (
('/path/to/file.c', 'file.c', '', '/'),
('/path/to/file.c', 'file', '.c', '/'),
('', '', '.c', '/'),
('c:\\system32\\etc\\hosts.txt', 'hosts.txt', '', '\\'),
)
for name, expected, suffix, sep in pairs:
<|code_end|>
using the current file's imports:
from .base import PycoreutilsBaseTest
from pycoreutils.commands._basename.command import get_base_name
and any relevant context from other files:
# Path: tests/base.py
# class PycoreutilsBaseTest(unittest.TestCase):
# def setUp(self):
# self.runner = CliRunner()
# self.cli = cli
#
# Path: pycoreutils/commands/_basename/command.py
# def get_base_name(name, suffix, separator):
# base_name = name.split(separator)[-1]
# if suffix and base_name.endswith(suffix):
# base_name = base_name[:-len(suffix)]
#
# return base_name
. Output only the next line. | self.assertEqual(get_base_name(name, suffix, sep), expected) |
Using the snippet: <|code_start|>
@click.command(
help='Print or check SHA256 checksums',
)
@click.help_option('-h', '--help')
@click.option('-c', '--check', is_flag=True, default=False, help='read SHA256 sums from the FILEs and check them')
@click.option('--tag', is_flag=True, default=False, help='Output a BSD-style checksum file')
@click.option('--quiet', is_flag=True, default=False, help="don't print OK for each successfully verified file")
@click.option('--status', is_flag=True, default=False, help="don't output anything, status code shows success")
@click.argument('files', metavar='FILE', required=False, nargs=-1, type=click.File('rb'))
def subcommand(check, tag, quiet, status, files):
if len(files) == 0:
files = (click.get_binary_stream('stdin'),)
<|code_end|>
, determine the next line of code. You have imports:
import sys
from ..hasher import HasherCommand
from ...vendor import click
and context (class names, function names, or code) available:
# Path: pycoreutils/commands/hasher.py
# class HasherCommand(object):
# def __init__(self, algorithm, tag=False, quiet=False, status=False):
# """
# :param algorithm: the hashing algorithm to use (eg. 'sha1', 'md5')
# """
# self.algorithm = algorithm
# self.tag = tag
# self.quiet = quiet
# self.status = status
#
# hashlen = len(hashlib.new(algorithm).hexdigest())
# self.checksum_line_regex = re.compile('^(?P<checksum>[a-f0-9]{{{hashlen}}}) (?P<filepath>.+)$'.format(hashlen=hashlen).encode('ascii'))
#
# def process_files(self, files, check=False):
# success = True
#
# if check and self.tag:
# raise click.BadOptionUsage('the --tag option is meaningless when verifying checksums')
#
# if not check and (self.status or self.quiet):
# raise click.BadOptionUsage('--status is only meaningful when verifying checksums')
#
# for file in files:
# if not check:
# # in testing, BytesIO has not attribute "name"
# filepath = getattr(file, 'name', '-')
# checksum = self.checksum_calculator(file)
# if self.tag:
# click.echo('{} ({}) = {}'.format(self.algorithm.upper(), filepath, checksum))
# else:
# click.echo('{} {}'.format(checksum, filepath))
# else:
# success = self.checksum_verifier(file) and success
#
# return success
#
# def checksum_calculator(self, file):
# """
# Computes a checksum using the class' algorithm
# Returns a unicode of the hexdigest
#
# Assumes the file is opened in binary mode
# """
# h = hashlib.new(self.algorithm)
# for data in iter(functools.partial(file.read, 4096), b''):
# h.update(data)
# return h.hexdigest()
#
# def checksum_verifier(self, file):
# noformat_count = 0
# nomatch_count = 0
# noread_count = 0
#
# for line in file:
# match = self.checksum_line_regex.match(line)
# if not match:
# noformat_count += 1
# else:
# group = match.groupdict()
# checksum = group['checksum']
# filepath = click.format_filename(group['filepath'])
# try:
# with click.open_file(filepath, 'rb') as fd:
# calculated_checksum = self.checksum_calculator(fd).encode('ascii')
# except IOError:
# noread_count += 1
# if not self.status:
# click.echo('{}: FAILED open or read'.format(filepath))
# continue
#
# if checksum == calculated_checksum:
# output = 'OK'
# else:
# output = 'FAILED'
# nomatch_count += 1
#
# if not self.status:
# if not self.quiet or output != 'OK':
# click.echo('{}: {}'.format(filepath, output))
#
# if not self.status:
# if noformat_count == 1:
# click.echo('WARNING: 1 line is improperly formatted', err=True)
# if noformat_count > 1:
# click.echo('WARNING: {} lines are improperly formatted'.format(noformat_count), err=True)
# if noread_count == 1:
# click.echo('WARNING: 1 listed file could not be read', err=True)
# if noread_count > 1:
# click.echo('WARNING: {} listed files could not be read'.format(noread_count), err=True)
# if nomatch_count == 1:
# click.echo('WARNING: 1 computed checksum did NOT match', err=True)
# if nomatch_count > 1:
# click.echo('WARNING: {} computed checksum did NOT match'.format(nomatch_count), err=True)
#
# return noformat_count + nomatch_count + noread_count == 0
. Output only the next line. | hasher = HasherCommand('sha256', tag, quiet, status) |
Predict the next line for this snippet: <|code_start|>
class PycoreutilsBaseTest(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
<|code_end|>
with the help of current file imports:
import unittest
from pycoreutils.main import cli
from pycoreutils.vendor.click.testing import CliRunner
and context from other files:
# Path: pycoreutils/main.py
# @click.command(
# cls=PycoreutilsMulticommand,
# epilog='See "COMMAND -h" to read about a specific subcommand',
# short_help='%(prog)s [-h] COMMAND [args]',
# )
# @click.help_option('-h', '--help')
# @click.version_option(__version__, '-v', '--version', message='%(prog)s v%(version)s')
# def cli():
# '''
# Coreutils in Pure Python
#
# \b
# ____ _ _ ___ _____ ____ ____ __ __ ____ ____ __ ___
# ( _ \( \/ )/ __)( _ )( _ \( ___)( )( )(_ _)(_ _)( ) / __)
# )___/ \ /( (__ )(_)( ) / )__) )(__)( )( _)(_ )(__ \__ \\
# (__) (__) \___)(_____)(_)\_)(____)(______) (__) (____)(____)(___/
# '''
# pass
, which may contain function names, class names, or code. Output only the next line. | self.cli = cli |
Using the snippet: <|code_start|>
def build_config_var(beta=False, external=False):
"""
Create the configuration key which will be used to locate
the base tiddlywiki file.
"""
base = 'base_tiddlywiki'
if external:
base += '_external'
if beta:
base += '_beta'
return base
class Serialization(WikiSerialization):
"""
Subclass of the standard TiddlyWiki serialization to allow
choosing beta or externalized versions of the base empty.html
in which the tiddlers will be servered.
Also, if the TiddlyWiki is not being downloaded, add
the UniversalBackstage by injecting a script tag.
"""
def list_tiddlers(self, tiddlers):
"""
Override tiddlers.link so the location in noscript is to
/tiddlers.
"""
<|code_end|>
, determine the next line of code. You have imports:
import logging
from tiddlyweb.util import read_utf8_file
from tiddlywebwiki.serialization import Serialization as WikiSerialization
from tiddlywebplugins.tiddlyspace.web import (determine_host,
determine_space, determine_space_recipe)
and context (class names, function names, or code) available:
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
# """
# Extract the current HTTP host from the environment.
# Return that plus the server_host from config. This is
# used to help calculate what space we are in when HTTP
# requests are made.
# """
# server_host = environ['tiddlyweb.config']['server_host']
# port = int(server_host['port'])
# if port == 80 or port == 443:
# host_url = server_host['host']
# else:
# host_url = '%s:%s' % (server_host['host'], port)
#
# http_host = environ.get('HTTP_HOST', host_url)
# if ':' in http_host:
# for port in [':80', ':443']:
# if http_host.endswith(port):
# http_host = http_host.replace(port, '')
# break
# return http_host, host_url
#
# def determine_space(environ, http_host):
# """
# Calculate the space associated with a subdomain.
# """
# server_host = environ['tiddlyweb.config']['server_host']['host']
# if '.%s' % server_host in http_host:
# return http_host.rsplit('.', server_host.count('.') + 1)[0]
# else:
# if ':' in http_host:
# http_host = http_host.split(':', 1)[0]
# store = environ['tiddlyweb.store']
# tiddler = Tiddler(http_host, 'MAPSPACE')
# try:
# tiddler = store.get(tiddler)
# return tiddler.fields['mapped_space']
# except (KeyError, StoreError):
# pass
# return None
#
# def determine_space_recipe(environ, space_name):
# """
# Given a space name, check if the current user is a member of that
# named space. If so, use the private recipe.
# """
# store = environ['tiddlyweb.store']
# usersign = environ['tiddlyweb.usersign']
# try:
# space = Space(space_name)
# recipe = Recipe(space.public_recipe())
# recipe = store.get(recipe)
# except (ValueError, StoreError), exc:
# raise HTTP404('Space for %s does not exist: %s' % (space_name, exc))
#
# try:
# recipe.policy.allows(usersign, 'manage')
# space_type = 'private'
# except PermissionsError:
# space_type = 'public'
#
# recipe_name_method = getattr(space, '%s_recipe' % space_type)
# recipe_name = recipe_name_method()
# return recipe_name
. Output only the next line. | http_host, _ = determine_host(self.environ) |
Based on the snippet: <|code_start|>
def build_config_var(beta=False, external=False):
"""
Create the configuration key which will be used to locate
the base tiddlywiki file.
"""
base = 'base_tiddlywiki'
if external:
base += '_external'
if beta:
base += '_beta'
return base
class Serialization(WikiSerialization):
"""
Subclass of the standard TiddlyWiki serialization to allow
choosing beta or externalized versions of the base empty.html
in which the tiddlers will be servered.
Also, if the TiddlyWiki is not being downloaded, add
the UniversalBackstage by injecting a script tag.
"""
def list_tiddlers(self, tiddlers):
"""
Override tiddlers.link so the location in noscript is to
/tiddlers.
"""
http_host, _ = determine_host(self.environ)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from tiddlyweb.util import read_utf8_file
from tiddlywebwiki.serialization import Serialization as WikiSerialization
from tiddlywebplugins.tiddlyspace.web import (determine_host,
determine_space, determine_space_recipe)
and context (classes, functions, sometimes code) from other files:
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
# """
# Extract the current HTTP host from the environment.
# Return that plus the server_host from config. This is
# used to help calculate what space we are in when HTTP
# requests are made.
# """
# server_host = environ['tiddlyweb.config']['server_host']
# port = int(server_host['port'])
# if port == 80 or port == 443:
# host_url = server_host['host']
# else:
# host_url = '%s:%s' % (server_host['host'], port)
#
# http_host = environ.get('HTTP_HOST', host_url)
# if ':' in http_host:
# for port in [':80', ':443']:
# if http_host.endswith(port):
# http_host = http_host.replace(port, '')
# break
# return http_host, host_url
#
# def determine_space(environ, http_host):
# """
# Calculate the space associated with a subdomain.
# """
# server_host = environ['tiddlyweb.config']['server_host']['host']
# if '.%s' % server_host in http_host:
# return http_host.rsplit('.', server_host.count('.') + 1)[0]
# else:
# if ':' in http_host:
# http_host = http_host.split(':', 1)[0]
# store = environ['tiddlyweb.store']
# tiddler = Tiddler(http_host, 'MAPSPACE')
# try:
# tiddler = store.get(tiddler)
# return tiddler.fields['mapped_space']
# except (KeyError, StoreError):
# pass
# return None
#
# def determine_space_recipe(environ, space_name):
# """
# Given a space name, check if the current user is a member of that
# named space. If so, use the private recipe.
# """
# store = environ['tiddlyweb.store']
# usersign = environ['tiddlyweb.usersign']
# try:
# space = Space(space_name)
# recipe = Recipe(space.public_recipe())
# recipe = store.get(recipe)
# except (ValueError, StoreError), exc:
# raise HTTP404('Space for %s does not exist: %s' % (space_name, exc))
#
# try:
# recipe.policy.allows(usersign, 'manage')
# space_type = 'private'
# except PermissionsError:
# space_type = 'public'
#
# recipe_name_method = getattr(space, '%s_recipe' % space_type)
# recipe_name = recipe_name_method()
# return recipe_name
. Output only the next line. | space_name = determine_space(self.environ, http_host) |
Using the snippet: <|code_start|> """
Create the configuration key which will be used to locate
the base tiddlywiki file.
"""
base = 'base_tiddlywiki'
if external:
base += '_external'
if beta:
base += '_beta'
return base
class Serialization(WikiSerialization):
"""
Subclass of the standard TiddlyWiki serialization to allow
choosing beta or externalized versions of the base empty.html
in which the tiddlers will be servered.
Also, if the TiddlyWiki is not being downloaded, add
the UniversalBackstage by injecting a script tag.
"""
def list_tiddlers(self, tiddlers):
"""
Override tiddlers.link so the location in noscript is to
/tiddlers.
"""
http_host, _ = determine_host(self.environ)
space_name = determine_space(self.environ, http_host)
if space_name:
<|code_end|>
, determine the next line of code. You have imports:
import logging
from tiddlyweb.util import read_utf8_file
from tiddlywebwiki.serialization import Serialization as WikiSerialization
from tiddlywebplugins.tiddlyspace.web import (determine_host,
determine_space, determine_space_recipe)
and context (class names, function names, or code) available:
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
# """
# Extract the current HTTP host from the environment.
# Return that plus the server_host from config. This is
# used to help calculate what space we are in when HTTP
# requests are made.
# """
# server_host = environ['tiddlyweb.config']['server_host']
# port = int(server_host['port'])
# if port == 80 or port == 443:
# host_url = server_host['host']
# else:
# host_url = '%s:%s' % (server_host['host'], port)
#
# http_host = environ.get('HTTP_HOST', host_url)
# if ':' in http_host:
# for port in [':80', ':443']:
# if http_host.endswith(port):
# http_host = http_host.replace(port, '')
# break
# return http_host, host_url
#
# def determine_space(environ, http_host):
# """
# Calculate the space associated with a subdomain.
# """
# server_host = environ['tiddlyweb.config']['server_host']['host']
# if '.%s' % server_host in http_host:
# return http_host.rsplit('.', server_host.count('.') + 1)[0]
# else:
# if ':' in http_host:
# http_host = http_host.split(':', 1)[0]
# store = environ['tiddlyweb.store']
# tiddler = Tiddler(http_host, 'MAPSPACE')
# try:
# tiddler = store.get(tiddler)
# return tiddler.fields['mapped_space']
# except (KeyError, StoreError):
# pass
# return None
#
# def determine_space_recipe(environ, space_name):
# """
# Given a space name, check if the current user is a member of that
# named space. If so, use the private recipe.
# """
# store = environ['tiddlyweb.store']
# usersign = environ['tiddlyweb.usersign']
# try:
# space = Space(space_name)
# recipe = Recipe(space.public_recipe())
# recipe = store.get(recipe)
# except (ValueError, StoreError), exc:
# raise HTTP404('Space for %s does not exist: %s' % (space_name, exc))
#
# try:
# recipe.policy.allows(usersign, 'manage')
# space_type = 'private'
# except PermissionsError:
# space_type = 'public'
#
# recipe_name_method = getattr(space, '%s_recipe' % space_type)
# recipe_name = recipe_name_method()
# return recipe_name
. Output only the next line. | recipe_name = determine_space_recipe(self.environ, space_name) |
Predict the next line after this snippet: <|code_start|> if not secondary_cookie_only:
cookie_header_string = make_cookie('tiddlyweb_user', usersign,
mac_key=secret, path=self._cookie_path(environ),
expires=cookie_age)
headers.append(('Set-Cookie', cookie_header_string))
start_response('303 See Other', headers)
return [uri]
def _render_form(self, environ, start_response, openid='',
message='', form=''):
"""
Send out a CSRF protected form for doing openid login.
This isn't generally used in TiddlySpace, client side
interfaces POST their own data.
"""
redirect = environ['tiddlyweb.query'].get(
'tiddlyweb_redirect', ['/'])[0]
start_response('200 OK', [(
'Content-Type', 'text/html')])
environ['tiddlyweb.title'] = 'OpenID Login'
return ["""
<div id='content'>
<div class='message'>%s</div>
<pre>
<form action="" method="POST">
OpenID: <input name="openid" size="60" value="%s"/>
<input type="hidden" name="tiddlyweb_redirect" value="%s" />
%s
</pre>
<|code_end|>
using the current file's imports:
import urlparse
from tiddlyweb.web.util import server_host_url, make_cookie
from tiddlywebplugins.openid2 import Challenger as OpenID
from tiddlywebplugins.tiddlyspace.cookie_form import FORM_FINISH
and any relevant context from other files:
# Path: tiddlywebplugins/tiddlyspace/cookie_form.py
# FORM_FINISH = """
# <input type="hidden" id="csrf_token" name="csrf_token" />
# <input type="submit" value="submit" />
# </form>
# <script type="text/javascript"
# src="/bags/tiddlyspace/tiddlers/TiddlySpaceCSRF"></script>
# <script type="text/javascript">
# var csrfToken = window.getCSRFToken(),
# el = null;
#
# if (csrfToken) {
# el = document.getElementById('csrf_token');
# el.value = csrfToken;
# }
# </script>
# """
. Output only the next line. | </div>""" % (message, openid, redirect, FORM_FINISH)] |
Given the following code snippet before the placeholder: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
<|code_end|>
, predict the next line using imports from the current file:
import simplejson
import httplib2
import wsgi_intercept
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from test.fixtures import make_test_env, make_fake_space, get_auth
and context including class names, function names, and sometimes code from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | make_fake_space(module.store, 'fnd') |
Here is a snippet: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
make_fake_space(module.store, 'fnd')
make_fake_space(module.store, 'cdent')
make_fake_space(module.store, 'psd')
users = {
'fnd': 'foo',
'cdent': 'bar',
'psd': 'baz'
}
for username, password in users.items():
user = User(username)
user.set_password(password)
module.store.put(user)
def remove_subscription(subscribed, subscriber, cookie=None):
return add_subscription(subscribed, subscriber, cookie=cookie,
unsubscribe=True)
def add_subscription(subscribed, subscriber, cookie=None, unsubscribe=False):
if not cookie:
<|code_end|>
. Write the next line using the current file imports:
import simplejson
import httplib2
import wsgi_intercept
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from test.fixtures import make_test_env, make_fake_space, get_auth
and context from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
, which may include functions, classes, or code. Output only the next line. | cookie = get_auth('fnd', 'foo') |
Here is a snippet: <|code_start|> If hsearch is False, don't bother updating the whoosh index
for this test instance. We do this by removing the store HOOK
used by whoosh.
"""
global SESSION_COUNT
# bump up a level if we're already in the test instance
if os.getcwd().endswith('test_instance'):
os.chdir('..')
try:
shutil.rmtree('test_instance')
except:
pass
os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
if SESSION_COUNT > 1:
del sys.modules['tiddlywebplugins.tiddlyspace.store']
del sys.modules['tiddlywebplugins.mysql3']
del sys.modules['tiddlywebplugins.sqlalchemy3']
tiddlywebplugins.mysql3.Session.remove()
clear_hooks(HOOKS)
SESSION_COUNT += 1
db_config = init_config['server_store'][1]['db_config']
db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
init_config['server_store'][1]['db_config'] = db_config
init_config['log_level'] = 'DEBUG'
if sys.path[0] != os.getcwd():
sys.path.insert(0, os.getcwd())
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import shutil
import httplib2
import Cookie
import tiddlywebplugins.tiddlyspace.store
import tiddlywebplugins.mysql3
import tiddlywebplugins.sqlalchemy3
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.config import config
from tiddlyweb.store import HOOKS
from tiddlywebplugins.utils import get_store
from tiddlywebplugins.imaker import spawn
from tiddlywebplugins.tiddlyspace import instance as instance_module
from tiddlywebplugins.tiddlyspace.config import config as init_config
from tiddlywebplugins.tiddlyspace.spaces import make_space
from tiddlyweb.web import serve
from tiddlywebplugins.whoosher import _tiddler_change_handler
and context from other files:
# Path: tiddlywebplugins/tiddlyspace/instance.py
#
# Path: tiddlywebplugins/tiddlyspace/config.py
# PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
# TIDDLYWIKI_BETA = resource_filename(PACKAGE_NAME, 'resources/beta.html')
# TIDDLYWIKI_EXTERNAL_BETA = resource_filename(PACKAGE_NAME,
# 'resources/external_beta.html')
# TIDDLYWIKI_EXTERNAL = resource_filename(PACKAGE_NAME,
# 'resources/external.html')
#
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def make_space(space_name, store, member):
# """
# The details of creating the bags and recipes that make up a space.
# """
# space = Space(space_name)
#
# for bag_name in space.list_bags():
# bag = Bag(bag_name)
# bag.policy = _make_policy(member)
# if Space.bag_is_public(bag_name):
# bag.policy.read = []
# store.put(bag)
#
# info_tiddler = Tiddler('SiteInfo', space.public_bag())
# info_tiddler.text = 'Space %s' % space_name
# info_tiddler.modifier = store.environ.get('tiddlyweb.usersign',
# {}).get('name', 'GUEST')
# store.put(info_tiddler)
#
# # Duplicate GettingStarted into public bag.
# getting_started_tiddler = Tiddler(GETTING_STARTED_TIDDLER['title'],
# GETTING_STARTED_TIDDLER['bag'])
# try:
# getting_started_tiddler = store.get(getting_started_tiddler)
# getting_started_tiddler.bag = space.public_bag()
# store.put(getting_started_tiddler)
# except StoreError:
# pass
#
# public_recipe = Recipe(space.public_recipe())
# public_recipe.set_recipe(space.public_recipe_list())
# private_recipe = Recipe(space.private_recipe())
# private_recipe.set_recipe(space.private_recipe_list())
# private_recipe.policy = _make_policy(member)
# public_recipe.policy = _make_policy(member)
# public_recipe.policy.read = []
# store.put(public_recipe)
# store.put(private_recipe)
, which may include functions, classes, or code. Output only the next line. | spawn('test_instance', init_config, instance_module) |
Predict the next line after this snippet: <|code_start|> cookie = Cookie.SimpleCookie()
cookie.load(user_cookie)
return cookie['tiddlyweb_user'].value
def make_test_env(module, hsearch=False):
"""
If hsearch is False, don't bother updating the whoosh index
for this test instance. We do this by removing the store HOOK
used by whoosh.
"""
global SESSION_COUNT
# bump up a level if we're already in the test instance
if os.getcwd().endswith('test_instance'):
os.chdir('..')
try:
shutil.rmtree('test_instance')
except:
pass
os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
if SESSION_COUNT > 1:
del sys.modules['tiddlywebplugins.tiddlyspace.store']
del sys.modules['tiddlywebplugins.mysql3']
del sys.modules['tiddlywebplugins.sqlalchemy3']
tiddlywebplugins.mysql3.Session.remove()
clear_hooks(HOOKS)
SESSION_COUNT += 1
<|code_end|>
using the current file's imports:
import os
import sys
import shutil
import httplib2
import Cookie
import tiddlywebplugins.tiddlyspace.store
import tiddlywebplugins.mysql3
import tiddlywebplugins.sqlalchemy3
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.config import config
from tiddlyweb.store import HOOKS
from tiddlywebplugins.utils import get_store
from tiddlywebplugins.imaker import spawn
from tiddlywebplugins.tiddlyspace import instance as instance_module
from tiddlywebplugins.tiddlyspace.config import config as init_config
from tiddlywebplugins.tiddlyspace.spaces import make_space
from tiddlyweb.web import serve
from tiddlywebplugins.whoosher import _tiddler_change_handler
and any relevant context from other files:
# Path: tiddlywebplugins/tiddlyspace/instance.py
#
# Path: tiddlywebplugins/tiddlyspace/config.py
# PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
# TIDDLYWIKI_BETA = resource_filename(PACKAGE_NAME, 'resources/beta.html')
# TIDDLYWIKI_EXTERNAL_BETA = resource_filename(PACKAGE_NAME,
# 'resources/external_beta.html')
# TIDDLYWIKI_EXTERNAL = resource_filename(PACKAGE_NAME,
# 'resources/external.html')
#
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def make_space(space_name, store, member):
# """
# The details of creating the bags and recipes that make up a space.
# """
# space = Space(space_name)
#
# for bag_name in space.list_bags():
# bag = Bag(bag_name)
# bag.policy = _make_policy(member)
# if Space.bag_is_public(bag_name):
# bag.policy.read = []
# store.put(bag)
#
# info_tiddler = Tiddler('SiteInfo', space.public_bag())
# info_tiddler.text = 'Space %s' % space_name
# info_tiddler.modifier = store.environ.get('tiddlyweb.usersign',
# {}).get('name', 'GUEST')
# store.put(info_tiddler)
#
# # Duplicate GettingStarted into public bag.
# getting_started_tiddler = Tiddler(GETTING_STARTED_TIDDLER['title'],
# GETTING_STARTED_TIDDLER['bag'])
# try:
# getting_started_tiddler = store.get(getting_started_tiddler)
# getting_started_tiddler.bag = space.public_bag()
# store.put(getting_started_tiddler)
# except StoreError:
# pass
#
# public_recipe = Recipe(space.public_recipe())
# public_recipe.set_recipe(space.public_recipe_list())
# private_recipe = Recipe(space.private_recipe())
# private_recipe.set_recipe(space.private_recipe_list())
# private_recipe.policy = _make_policy(member)
# public_recipe.policy = _make_policy(member)
# public_recipe.policy.read = []
# store.put(public_recipe)
# store.put(private_recipe)
. Output only the next line. | db_config = init_config['server_store'][1]['db_config'] |
Continue the code snippet: <|code_start|> init_config['server_store'][1]['db_config'] = db_config
init_config['log_level'] = 'DEBUG'
if sys.path[0] != os.getcwd():
sys.path.insert(0, os.getcwd())
spawn('test_instance', init_config, instance_module)
os.chdir('test_instance')
os.symlink('../tiddlywebplugins/templates', 'templates')
os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
module.store = get_store(init_config)
app = serve.load_app()
if not hsearch:
try:
HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
except ValueError:
pass
def app_fn():
return app
module.app_fn = app_fn
def make_fake_space(store, name):
"""
Call the spaces api to create a space.
"""
<|code_end|>
. Use current file imports:
import os
import sys
import shutil
import httplib2
import Cookie
import tiddlywebplugins.tiddlyspace.store
import tiddlywebplugins.mysql3
import tiddlywebplugins.sqlalchemy3
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.config import config
from tiddlyweb.store import HOOKS
from tiddlywebplugins.utils import get_store
from tiddlywebplugins.imaker import spawn
from tiddlywebplugins.tiddlyspace import instance as instance_module
from tiddlywebplugins.tiddlyspace.config import config as init_config
from tiddlywebplugins.tiddlyspace.spaces import make_space
from tiddlyweb.web import serve
from tiddlywebplugins.whoosher import _tiddler_change_handler
and context (classes, functions, or code) from other files:
# Path: tiddlywebplugins/tiddlyspace/instance.py
#
# Path: tiddlywebplugins/tiddlyspace/config.py
# PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
# TIDDLYWIKI_BETA = resource_filename(PACKAGE_NAME, 'resources/beta.html')
# TIDDLYWIKI_EXTERNAL_BETA = resource_filename(PACKAGE_NAME,
# 'resources/external_beta.html')
# TIDDLYWIKI_EXTERNAL = resource_filename(PACKAGE_NAME,
# 'resources/external.html')
#
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def make_space(space_name, store, member):
# """
# The details of creating the bags and recipes that make up a space.
# """
# space = Space(space_name)
#
# for bag_name in space.list_bags():
# bag = Bag(bag_name)
# bag.policy = _make_policy(member)
# if Space.bag_is_public(bag_name):
# bag.policy.read = []
# store.put(bag)
#
# info_tiddler = Tiddler('SiteInfo', space.public_bag())
# info_tiddler.text = 'Space %s' % space_name
# info_tiddler.modifier = store.environ.get('tiddlyweb.usersign',
# {}).get('name', 'GUEST')
# store.put(info_tiddler)
#
# # Duplicate GettingStarted into public bag.
# getting_started_tiddler = Tiddler(GETTING_STARTED_TIDDLER['title'],
# GETTING_STARTED_TIDDLER['bag'])
# try:
# getting_started_tiddler = store.get(getting_started_tiddler)
# getting_started_tiddler.bag = space.public_bag()
# store.put(getting_started_tiddler)
# except StoreError:
# pass
#
# public_recipe = Recipe(space.public_recipe())
# public_recipe.set_recipe(space.public_recipe_list())
# private_recipe = Recipe(space.private_recipe())
# private_recipe.set_recipe(space.private_recipe_list())
# private_recipe.policy = _make_policy(member)
# public_recipe.policy = _make_policy(member)
# public_recipe.policy.read = []
# store.put(public_recipe)
# store.put(private_recipe)
. Output only the next line. | make_space(name, store, name) |
Given the code snippet: <|code_start|> raise InvalidTiddlerError('secondary cookie not present')
if cookie_secret != sha('%s%s' % (usersign, secret)).hexdigest():
raise InvalidTiddlerError('secondary cookie invalid')
if usersign != tiddler.title:
raise InvalidTiddlerError('secondary cookie mismatch')
store = environ['tiddlyweb.store']
# XXX this is a potentially expensive operation but let's not
# early optimize
if tiddler.title in (user.usersign for user in store.list_users()):
raise InvalidTiddlerError('username exists')
tiddler.text = ''
tiddler.tags = []
tiddler.fields = {}
tiddler.fields['mapped_user'] = environ['tiddlyweb.usersign']['name']
return tiddler
def validate_mapspace(tiddler, environ):
"""
If a tiddler is put to the MAPSPACE bag clear
out the tiddler and set fields['mapped_space']
to the current space.
Elsewhere in the space the mapped_space can map
a alien domain to space.
"""
if tiddler.bag == 'MAPSPACE':
<|code_end|>
, generate the next line using the imports in this file:
import Cookie
from tiddlyweb.util import sha
from tiddlyweb.web.validator import TIDDLER_VALIDATORS, InvalidTiddlerError
from tiddlywebplugins.tiddlyspace.web import (determine_host,
determine_space, determine_space_recipe)
and context (functions, classes, or occasionally code) from other files:
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
# """
# Extract the current HTTP host from the environment.
# Return that plus the server_host from config. This is
# used to help calculate what space we are in when HTTP
# requests are made.
# """
# server_host = environ['tiddlyweb.config']['server_host']
# port = int(server_host['port'])
# if port == 80 or port == 443:
# host_url = server_host['host']
# else:
# host_url = '%s:%s' % (server_host['host'], port)
#
# http_host = environ.get('HTTP_HOST', host_url)
# if ':' in http_host:
# for port in [':80', ':443']:
# if http_host.endswith(port):
# http_host = http_host.replace(port, '')
# break
# return http_host, host_url
#
# def determine_space(environ, http_host):
# """
# Calculate the space associated with a subdomain.
# """
# server_host = environ['tiddlyweb.config']['server_host']['host']
# if '.%s' % server_host in http_host:
# return http_host.rsplit('.', server_host.count('.') + 1)[0]
# else:
# if ':' in http_host:
# http_host = http_host.split(':', 1)[0]
# store = environ['tiddlyweb.store']
# tiddler = Tiddler(http_host, 'MAPSPACE')
# try:
# tiddler = store.get(tiddler)
# return tiddler.fields['mapped_space']
# except (KeyError, StoreError):
# pass
# return None
#
# def determine_space_recipe(environ, space_name):
# """
# Given a space name, check if the current user is a member of that
# named space. If so, use the private recipe.
# """
# store = environ['tiddlyweb.store']
# usersign = environ['tiddlyweb.usersign']
# try:
# space = Space(space_name)
# recipe = Recipe(space.public_recipe())
# recipe = store.get(recipe)
# except (ValueError, StoreError), exc:
# raise HTTP404('Space for %s does not exist: %s' % (space_name, exc))
#
# try:
# recipe.policy.allows(usersign, 'manage')
# space_type = 'private'
# except PermissionsError:
# space_type = 'public'
#
# recipe_name_method = getattr(space, '%s_recipe' % space_type)
# recipe_name = recipe_name_method()
# return recipe_name
. Output only the next line. | current_space = determine_space(environ, determine_host(environ)[0]) |
Given snippet: <|code_start|> raise InvalidTiddlerError('secondary cookie not present')
if cookie_secret != sha('%s%s' % (usersign, secret)).hexdigest():
raise InvalidTiddlerError('secondary cookie invalid')
if usersign != tiddler.title:
raise InvalidTiddlerError('secondary cookie mismatch')
store = environ['tiddlyweb.store']
# XXX this is a potentially expensive operation but let's not
# early optimize
if tiddler.title in (user.usersign for user in store.list_users()):
raise InvalidTiddlerError('username exists')
tiddler.text = ''
tiddler.tags = []
tiddler.fields = {}
tiddler.fields['mapped_user'] = environ['tiddlyweb.usersign']['name']
return tiddler
def validate_mapspace(tiddler, environ):
"""
If a tiddler is put to the MAPSPACE bag clear
out the tiddler and set fields['mapped_space']
to the current space.
Elsewhere in the space the mapped_space can map
a alien domain to space.
"""
if tiddler.bag == 'MAPSPACE':
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import Cookie
from tiddlyweb.util import sha
from tiddlyweb.web.validator import TIDDLER_VALIDATORS, InvalidTiddlerError
from tiddlywebplugins.tiddlyspace.web import (determine_host,
determine_space, determine_space_recipe)
and context:
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
# """
# Extract the current HTTP host from the environment.
# Return that plus the server_host from config. This is
# used to help calculate what space we are in when HTTP
# requests are made.
# """
# server_host = environ['tiddlyweb.config']['server_host']
# port = int(server_host['port'])
# if port == 80 or port == 443:
# host_url = server_host['host']
# else:
# host_url = '%s:%s' % (server_host['host'], port)
#
# http_host = environ.get('HTTP_HOST', host_url)
# if ':' in http_host:
# for port in [':80', ':443']:
# if http_host.endswith(port):
# http_host = http_host.replace(port, '')
# break
# return http_host, host_url
#
# def determine_space(environ, http_host):
# """
# Calculate the space associated with a subdomain.
# """
# server_host = environ['tiddlyweb.config']['server_host']['host']
# if '.%s' % server_host in http_host:
# return http_host.rsplit('.', server_host.count('.') + 1)[0]
# else:
# if ':' in http_host:
# http_host = http_host.split(':', 1)[0]
# store = environ['tiddlyweb.store']
# tiddler = Tiddler(http_host, 'MAPSPACE')
# try:
# tiddler = store.get(tiddler)
# return tiddler.fields['mapped_space']
# except (KeyError, StoreError):
# pass
# return None
#
# def determine_space_recipe(environ, space_name):
# """
# Given a space name, check if the current user is a member of that
# named space. If so, use the private recipe.
# """
# store = environ['tiddlyweb.store']
# usersign = environ['tiddlyweb.usersign']
# try:
# space = Space(space_name)
# recipe = Recipe(space.public_recipe())
# recipe = store.get(recipe)
# except (ValueError, StoreError), exc:
# raise HTTP404('Space for %s does not exist: %s' % (space_name, exc))
#
# try:
# recipe.policy.allows(usersign, 'manage')
# space_type = 'private'
# except PermissionsError:
# space_type = 'public'
#
# recipe_name_method = getattr(space, '%s_recipe' % space_type)
# recipe_name = recipe_name_method()
# return recipe_name
which might include code, classes, or functions. Output only the next line. | current_space = determine_space(environ, determine_host(environ)[0]) |
Given the following code snippet before the placeholder: <|code_start|>
if cookie_secret != sha('%s%s' % (usersign, secret)).hexdigest():
raise InvalidTiddlerError('secondary cookie invalid')
if usersign != tiddler.title:
raise InvalidTiddlerError('secondary cookie mismatch')
store = environ['tiddlyweb.store']
# XXX this is a potentially expensive operation but let's not
# early optimize
if tiddler.title in (user.usersign for user in store.list_users()):
raise InvalidTiddlerError('username exists')
tiddler.text = ''
tiddler.tags = []
tiddler.fields = {}
tiddler.fields['mapped_user'] = environ['tiddlyweb.usersign']['name']
return tiddler
def validate_mapspace(tiddler, environ):
"""
If a tiddler is put to the MAPSPACE bag clear
out the tiddler and set fields['mapped_space']
to the current space.
Elsewhere in the space the mapped_space can map
a alien domain to space.
"""
if tiddler.bag == 'MAPSPACE':
current_space = determine_space(environ, determine_host(environ)[0])
<|code_end|>
, predict the next line using imports from the current file:
import Cookie
from tiddlyweb.util import sha
from tiddlyweb.web.validator import TIDDLER_VALIDATORS, InvalidTiddlerError
from tiddlywebplugins.tiddlyspace.web import (determine_host,
determine_space, determine_space_recipe)
and context including class names, function names, and sometimes code from other files:
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
# """
# Extract the current HTTP host from the environment.
# Return that plus the server_host from config. This is
# used to help calculate what space we are in when HTTP
# requests are made.
# """
# server_host = environ['tiddlyweb.config']['server_host']
# port = int(server_host['port'])
# if port == 80 or port == 443:
# host_url = server_host['host']
# else:
# host_url = '%s:%s' % (server_host['host'], port)
#
# http_host = environ.get('HTTP_HOST', host_url)
# if ':' in http_host:
# for port in [':80', ':443']:
# if http_host.endswith(port):
# http_host = http_host.replace(port, '')
# break
# return http_host, host_url
#
# def determine_space(environ, http_host):
# """
# Calculate the space associated with a subdomain.
# """
# server_host = environ['tiddlyweb.config']['server_host']['host']
# if '.%s' % server_host in http_host:
# return http_host.rsplit('.', server_host.count('.') + 1)[0]
# else:
# if ':' in http_host:
# http_host = http_host.split(':', 1)[0]
# store = environ['tiddlyweb.store']
# tiddler = Tiddler(http_host, 'MAPSPACE')
# try:
# tiddler = store.get(tiddler)
# return tiddler.fields['mapped_space']
# except (KeyError, StoreError):
# pass
# return None
#
# def determine_space_recipe(environ, space_name):
# """
# Given a space name, check if the current user is a member of that
# named space. If so, use the private recipe.
# """
# store = environ['tiddlyweb.store']
# usersign = environ['tiddlyweb.usersign']
# try:
# space = Space(space_name)
# recipe = Recipe(space.public_recipe())
# recipe = store.get(recipe)
# except (ValueError, StoreError), exc:
# raise HTTP404('Space for %s does not exist: %s' % (space_name, exc))
#
# try:
# recipe.policy.allows(usersign, 'manage')
# space_type = 'private'
# except PermissionsError:
# space_type = 'public'
#
# recipe_name_method = getattr(space, '%s_recipe' % space_type)
# recipe_name = recipe_name_method()
# return recipe_name
. Output only the next line. | recipe_name = determine_space_recipe(environ, current_space) |
Given snippet: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('bar.example.com', 8080, app_fn)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from base64 import b64encode
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.user import User
import wsgi_intercept
import httplib2
import simplejson
and context:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
which might include code, classes, or functions. Output only the next line. | make_fake_space(module.store, 'cdent') |
Predict the next line after this snippet: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('thing.0.0.0.0', 8080, app_fn)
<|code_end|>
using the current file's imports:
import pytest
import wsgi_intercept
import httplib2
import simplejson
from test.fixtures import make_test_env, make_fake_space, get_auth
from wsgi_intercept import httplib2_intercept
from tiddlywebplugins.templates import rfc3339, format_modified
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.web.util import encode_name
and any relevant context from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | make_fake_space(store, 'thing') |
Based on the snippet: <|code_start|>"""
Initialize tiddlyspace as a tiddlyweb plugin.
"""
def init_plugin(config):
# Only load and run dispatcher if we are specifically configured
# to use it.
if config.get('use_dispatcher', False):
establish_commands(config)
<|code_end|>
, predict the immediate next line with the help of imports:
from tiddlyweb.util import merge_config
from tiddlywebplugins.utils import remove_handler
from tiddlywebplugins.tiddlyspace.commands import establish_commands
from tiddlywebplugins.tiddlyspace.config import config as space_config
from tiddlywebplugins.tiddlyspace.www import establish_www
from werkzeug.contrib.profiler import ProfilerMiddleware
import tiddlywebplugins.whoosher
import tiddlywebwiki
import tiddlywebplugins.logout
import tiddlywebplugins.virtualhosting # calling init not required
import tiddlywebplugins.magicuser
import tiddlywebplugins.socialusers
import tiddlywebplugins.mselect
import tiddlywebplugins.oom
import tiddlywebplugins.cookiedomain
import tiddlywebplugins.tiddlyspace.validator
import tiddlywebplugins.prettyerror
import tiddlywebplugins.hashmaker
import tiddlywebplugins.form
import tiddlywebplugins.reflector
import tiddlywebplugins.privateer
import tiddlywebplugins.relativetime
import tiddlywebplugins.jsonp
import tiddlywebplugins.dispatcher
import tiddlywebplugins.dispatcher.listener
and context (classes, functions, sometimes code) from other files:
# Path: tiddlywebplugins/tiddlyspace/config.py
# PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
# TIDDLYWIKI_BETA = resource_filename(PACKAGE_NAME, 'resources/beta.html')
# TIDDLYWIKI_EXTERNAL_BETA = resource_filename(PACKAGE_NAME,
# 'resources/external_beta.html')
# TIDDLYWIKI_EXTERNAL = resource_filename(PACKAGE_NAME,
# 'resources/external.html')
#
# Path: tiddlywebplugins/tiddlyspace/www.py
# def establish_www(config):
# """
# Set up the routes and WSGI Middleware used by TiddlySpace.
# """
# replace_handler(config['selector'], '/', dict(GET=home))
# config['selector'].add('/_safe', GET=safe_mode, POST=safe_mode)
# add_spaces_routes(config['selector'])
# add_profile_routes(config['selector'])
# config['selector'].add('/users/{username}/identities',
# GET=get_identities)
# config['selector'].add('/tiddlers[.{format}]', GET=get_space_tiddlers)
# config['selector'].add('/{tiddler_name:segment}', GET=friendly_uri)
#
# if ControlView not in config['server_request_filters']:
# config['server_request_filters'].insert(
# config['server_request_filters'].
# index(Negotiate) + 1, ControlView)
#
# if DropPrivs not in config['server_request_filters']:
# config['server_request_filters'].insert(
# config['server_request_filters'].
# index(ControlView) + 1, DropPrivs)
#
# if CSRFProtector not in config['server_request_filters']:
# config['server_request_filters'].append(CSRFProtector)
#
# if ServerSettings not in config['server_request_filters']:
# config['server_request_filters'].insert(
# config['server_request_filters'].
# index(ControlView), ServerSettings)
#
# if AllowOrigin not in config['server_response_filters']:
# config['server_response_filters'].insert(
# config['server_response_filters'].
# index(PrettyHTTPExceptor) + 1, AllowOrigin)
. Output only the next line. | merge_config(config, space_config) |
Continue the code snippet: <|code_start|> tiddlywebwiki.init(config)
tiddlywebplugins.logout.init(config)
tiddlywebplugins.magicuser.init(config)
tiddlywebplugins.socialusers.init(config)
tiddlywebplugins.mselect.init(config)
tiddlywebplugins.oom.init(config)
tiddlywebplugins.cookiedomain.init(config)
tiddlywebplugins.prettyerror.init(config)
tiddlywebplugins.hashmaker.init(config)
tiddlywebplugins.form.init(config)
tiddlywebplugins.reflector.init(config)
tiddlywebplugins.privateer.init(config)
tiddlywebplugins.jsonp.init(config)
if config.get('use_dispatcher', False):
tiddlywebplugins.dispatcher.init(config)
tiddlywebplugins.dispatcher.listener.init(config)
# reset config _again_ to deal with any adjustments from the
# above init calls
merge_config(config, space_config)
# When tiddlyspace.frontpage_installed is True, don't update
# the frontpage_public bag, thus not overwriting what's there.
if config.get('tiddlyspace.frontpage_installed', False):
config['pkgstore.skip_bags'] = ['frontpage_public']
if 'selector' in config: # system plugin
# remove friendlywiki
remove_handler(config['selector'], '/{recipe_name:segment}')
<|code_end|>
. Use current file imports:
from tiddlyweb.util import merge_config
from tiddlywebplugins.utils import remove_handler
from tiddlywebplugins.tiddlyspace.commands import establish_commands
from tiddlywebplugins.tiddlyspace.config import config as space_config
from tiddlywebplugins.tiddlyspace.www import establish_www
from werkzeug.contrib.profiler import ProfilerMiddleware
import tiddlywebplugins.whoosher
import tiddlywebwiki
import tiddlywebplugins.logout
import tiddlywebplugins.virtualhosting # calling init not required
import tiddlywebplugins.magicuser
import tiddlywebplugins.socialusers
import tiddlywebplugins.mselect
import tiddlywebplugins.oom
import tiddlywebplugins.cookiedomain
import tiddlywebplugins.tiddlyspace.validator
import tiddlywebplugins.prettyerror
import tiddlywebplugins.hashmaker
import tiddlywebplugins.form
import tiddlywebplugins.reflector
import tiddlywebplugins.privateer
import tiddlywebplugins.relativetime
import tiddlywebplugins.jsonp
import tiddlywebplugins.dispatcher
import tiddlywebplugins.dispatcher.listener
and context (classes, functions, or code) from other files:
# Path: tiddlywebplugins/tiddlyspace/config.py
# PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace'
# TIDDLYWIKI_BETA = resource_filename(PACKAGE_NAME, 'resources/beta.html')
# TIDDLYWIKI_EXTERNAL_BETA = resource_filename(PACKAGE_NAME,
# 'resources/external_beta.html')
# TIDDLYWIKI_EXTERNAL = resource_filename(PACKAGE_NAME,
# 'resources/external.html')
#
# Path: tiddlywebplugins/tiddlyspace/www.py
# def establish_www(config):
# """
# Set up the routes and WSGI Middleware used by TiddlySpace.
# """
# replace_handler(config['selector'], '/', dict(GET=home))
# config['selector'].add('/_safe', GET=safe_mode, POST=safe_mode)
# add_spaces_routes(config['selector'])
# add_profile_routes(config['selector'])
# config['selector'].add('/users/{username}/identities',
# GET=get_identities)
# config['selector'].add('/tiddlers[.{format}]', GET=get_space_tiddlers)
# config['selector'].add('/{tiddler_name:segment}', GET=friendly_uri)
#
# if ControlView not in config['server_request_filters']:
# config['server_request_filters'].insert(
# config['server_request_filters'].
# index(Negotiate) + 1, ControlView)
#
# if DropPrivs not in config['server_request_filters']:
# config['server_request_filters'].insert(
# config['server_request_filters'].
# index(ControlView) + 1, DropPrivs)
#
# if CSRFProtector not in config['server_request_filters']:
# config['server_request_filters'].append(CSRFProtector)
#
# if ServerSettings not in config['server_request_filters']:
# config['server_request_filters'].insert(
# config['server_request_filters'].
# index(ControlView), ServerSettings)
#
# if AllowOrigin not in config['server_response_filters']:
# config['server_response_filters'].insert(
# config['server_response_filters'].
# index(PrettyHTTPExceptor) + 1, AllowOrigin)
. Output only the next line. | establish_www(config) |
Continue the code snippet: <|code_start|>"""
Test so-called "friendly" uris: links to tiddlers
in the current space from the root.
"""
def setup_module(module):
<|code_end|>
. Use current file imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
import wsgi_intercept
import httplib2
import simplejson
and context (classes, functions, or code) from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
. Output only the next line. | make_test_env(module) |
Predict the next line after this snippet: <|code_start|>"""
Test so-called "friendly" uris: links to tiddlers
in the current space from the root.
"""
def setup_module(module):
make_test_env(module)
# we have to have a function that returns the callable,
# Selector just _is_ the callable
<|code_end|>
using the current file's imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
import wsgi_intercept
import httplib2
import simplejson
and any relevant context from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
. Output only the next line. | make_fake_space(module.store, 'cdent') |
Based on the snippet: <|code_start|>"""
Test so-called "friendly" uris: links to tiddlers
in the current space from the root.
"""
def setup_module(module):
<|code_end|>
, predict the immediate next line with the help of imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
import wsgi_intercept
import httplib2
and context (classes, functions, sometimes code) from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
. Output only the next line. | make_test_env(module) |
Given snippet: <|code_start|>"""
Test so-called "friendly" uris: links to tiddlers
in the current space from the root.
"""
def setup_module(module):
make_test_env(module)
# we have to have a function that returns the callable,
# Selector just _is_ the callable
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
import wsgi_intercept
import httplib2
and context:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
which might include code, classes, or functions. Output only the next line. | make_fake_space(module.store, 'cdent') |
Given snippet: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('thing.0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('foo.0.0.0.0', 8080, app_fn)
user = User('thingone')
user.set_password('how')
store.put(user)
user = User('thingtwo')
user.set_password('how')
store.put(user)
module.http = httplib2.Http()
def test_create_spaces():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from test.fixtures import make_test_env, make_fake_space, get_auth
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from tiddlywebplugins.tiddlyspace.spaces import change_space_member
import wsgi_intercept
import httplib2
import simplejson
and context:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
#
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def change_space_member(store, space_name, add=None, remove=None,
# current_user=None):
# """
# The guts of adding a member to space.
# """
# try:
# space = Space(space_name)
# except ValueError, exc:
# raise HTTP404('Space %s invalid: %s' % (space_name, exc))
# private_bag = store.get(Bag(space.private_bag()))
#
# if current_user:
# private_bag.policy.allows(current_user, 'manage')
#
# if remove and len(private_bag.policy.manage) == 1:
# raise HTTP403('must not remove the last member from a space')
#
# # This will throw NoUserError (to be handled by the caller)
# # if the user does not exist.
# if add:
# store.get(User(add))
#
# bags = [store.get(Bag(bag)) for bag in space.list_bags()]
# recipes = [store.get(Recipe(bag)) for bag in space.list_recipes()]
# for entity in bags + recipes:
# new_policy = _update_policy(entity.policy, add=add, subtract=remove)
# entity.policy = new_policy
# store.put(entity)
which might include code, classes, or functions. Output only the next line. | cookie = get_auth('thingone', 'how') |
Using the snippet: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('thing.0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('other.0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('foo.0.0.0.0', 8080, app_fn)
def test_home_page_exist():
http = httplib2.Http()
response, content = http.request('http://0.0.0.0:8080/', method='GET')
assert response['status'] == '200'
assert 'Sign up' in content
def test_space_not_exist():
http = httplib2.Http()
response, content = http.request('http://thing.0.0.0.0:8080/', method='GET')
assert response['status'] == '404'
def test_space_does_exist():
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import wsgi_intercept
import httplib2
import simplejson
from test.fixtures import make_test_env, make_fake_space, get_auth
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
and context (class names, function names, or code) available:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | make_fake_space(store, 'thing') |
Given the code snippet: <|code_start|> headers={'Accept': 'application/json'},
method='GET')
assert response['status'] == '200', content
info = simplejson.loads(content)
assert len(info) == 2
def test_space_not_expose_subscription_recipes():
make_fake_space(store, 'foo')
make_fake_space(store, 'bar')
make_fake_space(store, 'baz')
# add subscription (manual as this is currently insufficiently encapsulated)
public_recipe = store.get(Recipe('foo_public'))
private_recipe = store.get(Recipe('foo_private'))
public_recipe_list = public_recipe.get_recipe()
private_recipe_list = private_recipe.get_recipe()
public_recipe_list.insert(-1, ('bar_public', ''))
private_recipe_list.insert(-2, ('bar_public', ''))
public_recipe.set_recipe(public_recipe_list)
private_recipe.set_recipe(private_recipe_list)
store.put(public_recipe)
store.put(private_recipe)
http = httplib2.Http()
user = User('foo')
user.set_password('foobar')
store.put(user)
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import wsgi_intercept
import httplib2
import simplejson
from test.fixtures import make_test_env, make_fake_space, get_auth
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
and context (functions, classes, or occasionally code) from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | user_cookie = get_auth('foo', 'foobar') |
Predict the next line after this snippet: <|code_start|>"""
Test creation of tiddlers in the MAPUSER bag.
The name of the tiddler is the external auth usersign.
The PUT tiddler is empty. A validator sets
fields['mapped_user'] to the current usersign.name.
Note: This does not test the way in which the MAPUSER
information is used by the extractor. Just the proper
creation of the tiddlers.
"""
AUTH_COOKIE = None
def setup_module(module):
<|code_end|>
using the current file's imports:
import wsgi_intercept
import httplib2
import Cookie
import simplejson
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.user import User
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.web.util import make_cookie
from test.fixtures import make_test_env
from tiddlyweb.config import config
and any relevant context from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
. Output only the next line. | make_test_env(module) |
Predict the next line after this snippet: <|code_start|>"""
Test that space_uri generates the correct URI for a space.
This _does_not_ check for a correct space when an alien_domain
is involved, because we don't have support for that yet.
"""
def testspace_uri():
environ = {}
environ['tiddlyweb.config'] = {}
environ['tiddlyweb.config']['server_host'] = {
'host': 'example.com',
'scheme': 'http',
'port': '8080',
}
server_host = environ['tiddlyweb.config']['server_host']
space_name = 'howdy'
<|code_end|>
using the current file's imports:
from tiddlywebplugins.tiddlyspace.spaces import space_uri
and any relevant context from other files:
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def space_uri(environ, space_name):
# """
# Determine the uri of a space based on its name.
# """
# host = environ['tiddlyweb.config']['server_host']['host']
# port = environ['tiddlyweb.config']['server_host']['port']
# scheme = environ['tiddlyweb.config']['server_host']['scheme']
# if not _alien_domain(environ, space_name):
# if port is not '443' and port is not '80':
# uri = '%s://%s.%s:%s/' % (scheme,
# urllib.quote(space_name.encode('utf-8')),
# host, port)
# else:
# uri = '%s://%s.%s/' % (scheme,
# urllib.quote(space_name.encode('utf-8')),
# host)
# else:
# if space_name == 'frontpage':
# if port is not '443' and port is not '80':
# uri = '%s://%s:%s/' % (scheme, host, port)
# else:
# uri = '%s://%s/' % (scheme, host)
# else:
# uri = '%s://%s/' % (scheme, space_name)
# return uri
. Output only the next line. | assert space_uri(environ, space_name) == 'http://howdy.example.com:8080/' |
Given snippet: <|code_start|>"""
Test the search interface.
"""
def setup_module(module):
make_test_env(module, hsearch=True)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('fnd.0.0.0.0', 8080, app_fn)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.user import User
from tiddlyweb.model.tiddler import Tiddler
import wsgi_intercept
import httplib2
import simplejson
and context:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
which might include code, classes, or functions. Output only the next line. | make_fake_space(module.store, 'cdent') |
Predict the next line for this snippet: <|code_start|>"""
Test safe mode which allows a member to recover a space
which has gone pear shaped as a result of the wrong or
dangerous plugins.
"""
AUTH_COOKIE = None
def setup_module(module):
<|code_end|>
with the help of current file imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.user import User
from tiddlyweb.model.tiddler import Tiddler
import wsgi_intercept
import httplib2
import simplejson
import Cookie
and context from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
, which may contain function names, class names, or code. Output only the next line. | make_test_env(module) |
Based on the snippet: <|code_start|>"""
Test safe mode which allows a member to recover a space
which has gone pear shaped as a result of the wrong or
dangerous plugins.
"""
AUTH_COOKIE = None
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
<|code_end|>
, predict the immediate next line with the help of imports:
from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.user import User
from tiddlyweb.model.tiddler import Tiddler
import wsgi_intercept
import httplib2
import simplejson
import Cookie
and context (classes, functions, sometimes code) from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
. Output only the next line. | make_fake_space(module.store, 'cdent') |
Here is a snippet: <|code_start|>"""
Watch out for presentation bugs with bags that are not
considered valid.
"""
ENVIRON = {
'tiddlyweb.config': {
'server_host': {
'host': 'tiddlyspace.com',
'port': '80',
}
},
'HTTP_HOST': 'tapas.tiddlyspace.com',
'wsgi.url_scheme': 'http'
}
def test_space_bag():
tiddler = Tiddler('monkey', 'tapas_public')
<|code_end|>
. Write the next line using the current file imports:
from tiddlywebplugins.tiddlyspace.fixups import web_tiddler_url
from tiddlyweb.model.tiddler import Tiddler
and context from other files:
# Path: tiddlywebplugins/tiddlyspace/fixups.py
# def web_tiddler_url(environ, tiddler, container='bags', full=True,
# friendly=False):
# """
# Override default tiddler_url to be space+host aware.
#
# If the bag or recipe of the tiddler is of a space, switch to
# that space's host for the duration of uri creation.
#
# Do this all the time, so that we get the right URIs even
# when working around ControlView.
#
# If the bag does not fit in a space, then make is URI be at
# the server_host domain. If/when auxbags are made to work this
# will need to be reviewed.
# """
# saved_host = environ.get('HTTP_HOST', '')
# try:
# if container == 'recipes':
# space_name = Space.name_from_recipe(tiddler.recipe)
# else:
# space_name = Space.name_from_bag(tiddler.bag)
# space_name = space_name + '.'
# except ValueError:
# space_name = ''
#
# host = environ['tiddlyweb.config']['server_host']['host']
# port = environ['tiddlyweb.config']['server_host']['port']
# if port is '443' or port is '80':
# port = ''
# else:
# port = ':%s' % port
# environ['HTTP_HOST'] = '%s%s%s' % (space_name.encode('utf-8'),
# host, port)
#
# if friendly and space_name:
# url = '%s/%s' % (tiddlyweb.web.util.server_base_url(environ),
# tiddlyweb.web.util.encode_name(tiddler.title))
# else:
# url = original_tiddler_url(environ, tiddler, container, full)
# if saved_host:
# environ['HTTP_HOST'] = saved_host
# elif 'HTTP_HOST' in environ:
# del environ['HTTP_HOST']
# return url
, which may include functions, classes, or code. Output only the next line. | uri = web_tiddler_url(ENVIRON, tiddler) |
Next line prediction: <|code_start|>"""
Run through the socialusers API testing what's there.
Read the TESTS variable as document of
the capabilities of the API.
If you run this test file by itself, instead
of as a test it will produce a list of test
requests and some associated information.
"""
base_url = 'http://0.0.0.0:8080'
TESTS = {}
def setup_module(module):
global TESTS
<|code_end|>
. Use current file imports:
(import os
import wsgi_intercept
import httplib2
import yaml
from test.fixtures import make_test_env
from wsgi_intercept import httplib2_intercept)
and context including class names, function names, or small code snippets from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
. Output only the next line. | make_test_env(module) |
Given the following code snippet before the placeholder: <|code_start|> assert bag.policy.accept == ['NONE']
assert bag.policy.manage == ['cdent', 'fnd']
assert bag.policy.write == ['cdent', 'fnd']
assert bag.policy.create == ['cdent', 'fnd']
assert bag.policy.delete == ['cdent', 'fnd']
# authed user not in space may not add people
cookie = get_auth('psd', 'cat')
response, content = http.request('http://0.0.0.0:8080/spaces/extra/members/psd',
headers={'Cookie': 'tiddlyweb_user="%s"' % cookie},
method='PUT',
)
assert response['status'] == '403'
cookie = get_auth('fnd', 'bird')
response, content = http.request('http://extra.0.0.0.0:8080/spaces/extra/members/psd',
headers={'Cookie': 'tiddlyweb_user="%s"' % cookie},
method='PUT',
)
assert response['status'] == '204'
cookie = get_auth('fnd', 'bird')
response, content = http.request('http://extra.0.0.0.0:8080/spaces/extra/members/mary',
headers={'Cookie': 'tiddlyweb_user="%s"' % cookie},
method='PUT',
)
assert response['status'] == '409'
def test_update_policy_nonstandard():
<|code_end|>
, predict the next line using imports from the current file:
import simplejson
import httplib2
import wsgi_intercept
import py.test
from wsgi_intercept import httplib2_intercept
from httpexceptor import HTTP409
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from tiddlywebplugins.tiddlyspace.spaces import _update_policy, _make_policy
from test.fixtures import make_test_env, make_fake_space, get_auth
from tiddlyweb.config import config
and context including class names, function names, and sometimes code from other files:
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def _update_policy(policy, add=None, subtract=None):
# """
# Update the policy adding or subtracting the user named in
# add or subtract.
# """
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# constraint_values = getattr(policy, constraint)
# if add and add not in constraint_values:
# if constraint == 'read' and constraint_values == []:
# pass
# else:
# if 'ANY' in constraint_values or 'NONE' in constraint_values:
# raise HTTP409('Policy contains ANY or NONE.')
# constraint_values.append(add)
# if subtract and subtract in constraint_values:
# constraint_values.remove(subtract)
# return policy
#
# def _make_policy(member):
# """
# Make a new private policy with the named member.
# """
# policy = Policy()
# policy.owner = member
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# setattr(policy, constraint, [member])
# policy.accept = ['NONE']
# return policy
#
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | policy = _make_policy('jon') |
Continue the code snippet: <|code_start|>"""
Test and flesh a /spaces handler-space.
GET /spaces: list all spaces
GET /spaces/{space_name}: 204 if exist
GET /spaces/{space_name}/members: list all members
PUT /spaces/{space_name}: create a space
PUT /spaces/{space_name}/members/{member_name}: add a member
DELETE /spaces/{space_name}/members/{member_name}: remove a member
POST /spaces/{space_name}: Handle subscription, the data package is
JSON as {"subscriptions": ["space1", "space2", "space3"]}
"""
SYSTEM_SPACES = ['system-plugins', 'system-info', 'system-images',
'system-theme', 'system-applications']
SYSTEM_URLS = ['http://system-plugins.0.0.0.0:8080/',
'http://system-info.0.0.0.0:8080/', 'http://system-applications.0.0.0.0:8080/',
'http://system-images.0.0.0.0:8080/', 'http://system-theme.0.0.0.0:8080/']
def setup_module(module):
<|code_end|>
. Use current file imports:
import simplejson
import httplib2
import wsgi_intercept
import py.test
from wsgi_intercept import httplib2_intercept
from httpexceptor import HTTP409
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from tiddlywebplugins.tiddlyspace.spaces import _update_policy, _make_policy
from test.fixtures import make_test_env, make_fake_space, get_auth
from tiddlyweb.config import config
and context (classes, functions, or code) from other files:
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def _update_policy(policy, add=None, subtract=None):
# """
# Update the policy adding or subtracting the user named in
# add or subtract.
# """
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# constraint_values = getattr(policy, constraint)
# if add and add not in constraint_values:
# if constraint == 'read' and constraint_values == []:
# pass
# else:
# if 'ANY' in constraint_values or 'NONE' in constraint_values:
# raise HTTP409('Policy contains ANY or NONE.')
# constraint_values.append(add)
# if subtract and subtract in constraint_values:
# constraint_values.remove(subtract)
# return policy
#
# def _make_policy(member):
# """
# Make a new private policy with the named member.
# """
# policy = Policy()
# policy.owner = member
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# setattr(policy, constraint, [member])
# policy.accept = ['NONE']
# return policy
#
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | make_test_env(module) |
Given the code snippet: <|code_start|>
GET /spaces: list all spaces
GET /spaces/{space_name}: 204 if exist
GET /spaces/{space_name}/members: list all members
PUT /spaces/{space_name}: create a space
PUT /spaces/{space_name}/members/{member_name}: add a member
DELETE /spaces/{space_name}/members/{member_name}: remove a member
POST /spaces/{space_name}: Handle subscription, the data package is
JSON as {"subscriptions": ["space1", "space2", "space3"]}
"""
SYSTEM_SPACES = ['system-plugins', 'system-info', 'system-images',
'system-theme', 'system-applications']
SYSTEM_URLS = ['http://system-plugins.0.0.0.0:8080/',
'http://system-info.0.0.0.0:8080/', 'http://system-applications.0.0.0.0:8080/',
'http://system-images.0.0.0.0:8080/', 'http://system-theme.0.0.0.0:8080/']
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
config['blacklisted_spaces'] = ['scrappy']
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('extra.0.0.0.0', 8080, app_fn)
<|code_end|>
, generate the next line using the imports in this file:
import simplejson
import httplib2
import wsgi_intercept
import py.test
from wsgi_intercept import httplib2_intercept
from httpexceptor import HTTP409
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from tiddlywebplugins.tiddlyspace.spaces import _update_policy, _make_policy
from test.fixtures import make_test_env, make_fake_space, get_auth
from tiddlyweb.config import config
and context (functions, classes, or occasionally code) from other files:
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def _update_policy(policy, add=None, subtract=None):
# """
# Update the policy adding or subtracting the user named in
# add or subtract.
# """
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# constraint_values = getattr(policy, constraint)
# if add and add not in constraint_values:
# if constraint == 'read' and constraint_values == []:
# pass
# else:
# if 'ANY' in constraint_values or 'NONE' in constraint_values:
# raise HTTP409('Policy contains ANY or NONE.')
# constraint_values.append(add)
# if subtract and subtract in constraint_values:
# constraint_values.remove(subtract)
# return policy
#
# def _make_policy(member):
# """
# Make a new private policy with the named member.
# """
# policy = Policy()
# policy.owner = member
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# setattr(policy, constraint, [member])
# policy.accept = ['NONE']
# return policy
#
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | make_fake_space(module.store, 'cdent') |
Using the snippet: <|code_start|> make_fake_space(store, 'fnd')
response, content = http.request('http://0.0.0.0:8080/spaces',
method='GET')
assert response['status'] == '200'
info = simplejson.loads(content)
uris = [uri for _, uri in [item.values() for item in info]]
assert 'http://cdent.0.0.0.0:8080/' in uris
assert 'http://fnd.0.0.0.0:8080/' in uris
def test_space_exist():
http = httplib2.Http()
response, content = http.request('http://0.0.0.0:8080/spaces/cdent',
method='GET')
assert response['status'] == '204'
assert content == ''
http = httplib2.Http()
response, content = http.request('http://0.0.0.0:8080/spaces/nancy',
method='GET')
assert response['status'] == '404'
assert 'There is nothing at this address.' in content
def test_space_members():
http = httplib2.Http()
response, content = http.request('http://0.0.0.0:8080/spaces/cdent/members',
method='GET')
assert response['status'] == '401'
<|code_end|>
, determine the next line of code. You have imports:
import simplejson
import httplib2
import wsgi_intercept
import py.test
from wsgi_intercept import httplib2_intercept
from httpexceptor import HTTP409
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from tiddlywebplugins.tiddlyspace.spaces import _update_policy, _make_policy
from test.fixtures import make_test_env, make_fake_space, get_auth
from tiddlyweb.config import config
and context (class names, function names, or code) available:
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def _update_policy(policy, add=None, subtract=None):
# """
# Update the policy adding or subtracting the user named in
# add or subtract.
# """
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# constraint_values = getattr(policy, constraint)
# if add and add not in constraint_values:
# if constraint == 'read' and constraint_values == []:
# pass
# else:
# if 'ANY' in constraint_values or 'NONE' in constraint_values:
# raise HTTP409('Policy contains ANY or NONE.')
# constraint_values.append(add)
# if subtract and subtract in constraint_values:
# constraint_values.remove(subtract)
# return policy
#
# def _make_policy(member):
# """
# Make a new private policy with the named member.
# """
# policy = Policy()
# policy.owner = member
# for constraint in ('read', 'write', 'create', 'delete', 'manage'):
# setattr(policy, constraint, [member])
# policy.accept = ['NONE']
# return policy
#
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | cookie = get_auth('cdent', 'cow') |
Given the code snippet: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('thing.0.0.0.0', 8080, app_fn)
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import wsgi_intercept
import httplib2
import simplejson
from test.fixtures import make_test_env, make_fake_space, get_auth
from wsgi_intercept import httplib2_intercept
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.web.util import encode_name
and context (functions, classes, or occasionally code) from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | make_fake_space(store, 'thing') |
Next line prediction: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
module.http = httplib2.Http()
<|code_end|>
. Use current file imports:
(from test.fixtures import make_test_env, make_fake_space
from wsgi_intercept import httplib2_intercept
from tiddlywebplugins.utils import get_store
from tiddlyweb.config import config
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.user import User
import wsgi_intercept
import httplib2
import simplejson)
and context including class names, function names, or small code snippets from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def make_fake_space(store, name):
# """
# Call the spaces api to create a space.
# """
# make_space(name, store, name)
. Output only the next line. | make_fake_space(module.store, 'cdent') |
Predict the next line after this snippet: <|code_start|>"""
Test user creation, especially with regard
to validating names. This is important in the
tiddlyspace setting (as opposed to
tiddlywebplugins.socialusers which uses handles
user creation) because usernames are more constrained
there than they are in generic TiddlyWeb. The
constraints are:
* the usernames must be valid hostnames
* the usernames must not conflict with the
names of existing spaces and users
socialusers checks to see if a user exists after
it has validated the username. TiddlySpace needs
to override socialusers:_validate_user with its
own routines. These routines should check the above
constraints.
"""
def setup_module(module):
<|code_end|>
using the current file's imports:
import simplejson
import httplib2
import wsgi_intercept
from wsgi_intercept import httplib2_intercept
from test.fixtures import make_test_env, get_auth
and any relevant context from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | make_test_env(module) |
Predict the next line after this snippet: <|code_start|>
def setup_module(module):
make_test_env(module)
httplib2_intercept.install()
wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
module.http = httplib2.Http()
def test_register_user():
data = {'username': 'cdent', 'password': 'cowpig'}
body = simplejson.dumps(data)
response, content = http.request('http://0.0.0.0:8080/users',
method='POST',
headers={'Content-Type': 'application/json'},
body=body)
assert response['status'] == '201'
response, content = http.request('http://0.0.0.0:8080/users',
method='POST',
headers={'Content-Type': 'application/json'},
body=body)
assert response['status'] == '409'
assert 'exists' in content
<|code_end|>
using the current file's imports:
import simplejson
import httplib2
import wsgi_intercept
from wsgi_intercept import httplib2_intercept
from test.fixtures import make_test_env, get_auth
and any relevant context from other files:
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
# """
# If hsearch is False, don't bother updating the whoosh index
# for this test instance. We do this by removing the store HOOK
# used by whoosh.
# """
# global SESSION_COUNT
#
# # bump up a level if we're already in the test instance
# if os.getcwd().endswith('test_instance'):
# os.chdir('..')
#
# try:
# shutil.rmtree('test_instance')
# except:
# pass
#
# os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
# if SESSION_COUNT > 1:
# del sys.modules['tiddlywebplugins.tiddlyspace.store']
# del sys.modules['tiddlywebplugins.mysql3']
# del sys.modules['tiddlywebplugins.sqlalchemy3']
# import tiddlywebplugins.tiddlyspace.store
# import tiddlywebplugins.mysql3
# import tiddlywebplugins.sqlalchemy3
# tiddlywebplugins.mysql3.Session.remove()
# clear_hooks(HOOKS)
# SESSION_COUNT += 1
# db_config = init_config['server_store'][1]['db_config']
# db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
# init_config['server_store'][1]['db_config'] = db_config
# init_config['log_level'] = 'DEBUG'
#
# if sys.path[0] != os.getcwd():
# sys.path.insert(0, os.getcwd())
# spawn('test_instance', init_config, instance_module)
# os.chdir('test_instance')
# os.symlink('../tiddlywebplugins/templates', 'templates')
# os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
#
# from tiddlyweb.web import serve
# module.store = get_store(init_config)
#
# app = serve.load_app()
#
# if not hsearch:
# from tiddlywebplugins.whoosher import _tiddler_change_handler
# try:
# HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
# HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
# except ValueError:
# pass
#
# def app_fn():
# return app
# module.app_fn = app_fn
#
# def get_auth(username, password):
# http = httplib2.Http()
# response, _ = http.request(
# 'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
# body='user=%s&password=%s' % (username, password),
# method='POST',
# headers={'Content-Type': 'application/x-www-form-urlencoded'})
# assert response.previous['status'] == '303'
#
# user_cookie = response.previous['set-cookie']
# cookie = Cookie.SimpleCookie()
# cookie.load(user_cookie)
# return cookie['tiddlyweb_user'].value
. Output only the next line. | cookie = get_auth('cdent', 'cowpig') |
Next line prediction: <|code_start|>"""
Start at the infrastructure for OStatus, including webfinger,
user profiles, etc.
"""
LOGGER = logging.getLogger(__name__)
def add_profile_routes(selector):
"""
Add the necessary routes for profiles and webfinger.
"""
selector.add('/.well-known/host-meta', GET=host_meta)
selector.add('/webfinger', GET=webfinger)
selector.add('/profiles/{username}[.{format}]', GET=profile)
def profile(environ, start_response):
"""
Choose between an atom or html profile.
"""
<|code_end|>
. Use current file imports:
(import logging
import urllib
import urllib2
from httpexceptor import HTTP404, HTTP400, HTTP415
from tiddlyweb.control import readable_tiddlers_by_bag
from tiddlyweb.store import StoreError, NoUserError
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.user import User
from tiddlyweb.wikitext import render_wikitext
from tiddlyweb.web.handler.search import get as search
from tiddlyweb.web.util import (server_host_url, encode_name,
get_serialize_type, tiddler_url, get_route_value)
from tiddlywebplugins.utils import get_store
from tiddlywebplugins.tiddlyspace.spaces import space_uri
from tiddlywebplugins.tiddlyspace.web import determine_host
from tiddlywebplugins.tiddlyspace.template import send_template
from tiddlywebplugins.dispatcher.listener import Listener as BaseListener)
and context including class names, function names, or small code snippets from other files:
# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def space_uri(environ, space_name):
# """
# Determine the uri of a space based on its name.
# """
# host = environ['tiddlyweb.config']['server_host']['host']
# port = environ['tiddlyweb.config']['server_host']['port']
# scheme = environ['tiddlyweb.config']['server_host']['scheme']
# if not _alien_domain(environ, space_name):
# if port is not '443' and port is not '80':
# uri = '%s://%s.%s:%s/' % (scheme,
# urllib.quote(space_name.encode('utf-8')),
# host, port)
# else:
# uri = '%s://%s.%s/' % (scheme,
# urllib.quote(space_name.encode('utf-8')),
# host)
# else:
# if space_name == 'frontpage':
# if port is not '443' and port is not '80':
# uri = '%s://%s:%s/' % (scheme, host, port)
# else:
# uri = '%s://%s/' % (scheme, host)
# else:
# uri = '%s://%s/' % (scheme, space_name)
# return uri
#
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
# """
# Extract the current HTTP host from the environment.
# Return that plus the server_host from config. This is
# used to help calculate what space we are in when HTTP
# requests are made.
# """
# server_host = environ['tiddlyweb.config']['server_host']
# port = int(server_host['port'])
# if port == 80 or port == 443:
# host_url = server_host['host']
# else:
# host_url = '%s:%s' % (server_host['host'], port)
#
# http_host = environ.get('HTTP_HOST', host_url)
# if ':' in http_host:
# for port in [':80', ':443']:
# if http_host.endswith(port):
# http_host = http_host.replace(port, '')
# break
# return http_host, host_url
#
# Path: tiddlywebplugins/tiddlyspace/template.py
# def send_template(environ, template_name, template_data=None):
# """
# Set some defaults for a template and send the output.
# """
# default_css_tiddler = '/bags/common/tiddlers/profile.css'
# if template_data is None:
# template_data = {}
# html_template_prefix = environ['tiddlyweb.space_settings']['htmltemplate']
# if html_template_prefix:
# default_css_tiddler = ('/bags/common/tiddlers/%s.css' %
# html_template_prefix)
# html_template_prefix += '/'
# try:
# name = html_template_prefix + template_name
# template = get_template(environ, name)
# except TemplateNotFound:
# template = get_template(environ, template_name)
# else:
# template = get_template(environ, template_name)
#
# store = environ['tiddlyweb.store']
#
# linked_resources = {
# 'HtmlCss': [],
# 'HtmlJavascript': []}
#
# if not html_template_prefix or template_name in CUSTOMIZABLES:
# linked_resources['HtmlCss'] = [default_css_tiddler]
# # Load CSS and JavaScript overrides.
# current_space = determine_space(environ, determine_host(environ)[0])
# if current_space:
# recipe_name = determine_space_recipe(environ, current_space)
# try:
# recipe = store.get(Recipe(recipe_name))
# for title in linked_resources:
# try:
# tiddler = Tiddler(title)
# bag = control.determine_bag_from_recipe(recipe,
# tiddler, environ)
# tiddler.bag = bag.name
# try:
# tiddler = store.get(tiddler)
# if 'Javascript' in title:
# url_content = tiddler.text.strip()
# if url_content:
# urls = url_content.split('\n')
# linked_resources[title] = urls
# else:
# url = '/bags/%s/tiddlers/%s' % (encode_name(
# tiddler.bag), title)
# linked_resources[title] = [url]
# except StoreError:
# continue
# except StoreError:
# pass
# except StoreError:
# pass
#
# template_defaults = {
# 'original_server_host': original_server_host_url(environ),
# 'css': linked_resources['HtmlCss'],
# 'js': linked_resources['HtmlJavascript'],
# 'server_host': server_base_url(environ),
# }
# template_defaults.update(template_data)
# return template.generate(template_defaults)
. Output only the next line. | http_host, host_url = determine_host(environ) |
Predict the next line for this snippet: <|code_start|>
def deactivate(modeladmin, request, queryset):
queryset.update(is_active=True)
deactivate.short_description = "Deactivate selected users"
class ProfileAdmin(UserAdmin):
add_form = ProfileCreationForm
date_hierarchy = 'date_joined'
list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups', 'date_joined')
list_display = ('username', 'display_name', 'first_name', 'last_name', 'email', 'is_active', 'is_staff')
search_fields = ('username', 'first_name', 'last_name', 'email', 'display_name')
actions = [deactivate, ]
def get_form(self, request, obj=None, **kwargs):
"""
Use special form during user creation
"""
defaults = {}
if obj is None:
defaults['form'] = self.add_form
defaults.update(kwargs)
return super(ProfileAdmin, self).get_form(request, obj, **defaults)
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Profile
from .forms import ProfileCreationForm
and context from other files:
# Path: tango_user/models.py
# class Profile(AbstractUser):
# """
# Subclasses AbstractUser to provide site-specific user fields.
# """
# display_name = models.CharField(
# max_length=200,
# blank=True,
# null=True,
# help_text="""
# If you would prefer a different screen name, enter it here.
# Spaces are allowed. Note: your username will not change.
# """
# )
# street_address = models.CharField(
# max_length=255,
# blank=True,
# help_text="Will never be shown publicly on the site.")
# city = models.CharField(max_length=200, blank=True)
# state = models.CharField(max_length=200, blank=True)
# country = models.CharField(max_length=200, blank=True)
# zipcode = models.CharField(
# 'ZIP/Postal Code',
# max_length=10,
# blank=True,
# help_text="Will never be shown publicly on the site."
# )
# interests = models.CharField(max_length=200, blank=True)
# occupation = models.CharField(max_length=200, blank=True)
# birthday = models.DateField(blank=True, null=True)
# homepage = models.URLField('Your web site', blank=True)
# bio = models.TextField(help_text='Tell us a bit about yourself.', blank=True, null=True)
# bio_formatted = models.TextField(blank=True, editable=False)
# signature = models.CharField(
# max_length=255,
# blank=True,
# help_text="""
# You can have a short signature line on the posts and comments.
# Members who choose to view signatures can see it. HTML is not allowed.
# """
# )
# geocode = models.CharField(max_length=200, null=True, blank=True)
# avatar = models.ImageField(blank=True, null=True, upload_to=set_img_path)
# if 'fretboard' in settings.INSTALLED_APPS:
# post_count = models.IntegerField(default="0", editable=False)
#
# #preferences
# display_on_map = models.BooleanField(default=True)
# open_links = models.BooleanField(
# "Open links in new window",
# default=False,
# help_text="Check if you would like links to automatically open in a new window."
# )
# show_signatures = models.BooleanField(
# default=False,
# help_text="Check if you would like to see signatures attached to forum posts."
# )
# theme = models.CharField(max_length=100, blank=True, choices=THEME_CHOICES)
#
# class Meta:
# ordering = ('display_name',)
#
# def __unicode__(self):
# return self.username
#
# def save(self, *args, **kwargs):
# needs_geocode = False
# if self.id is None: # For new user, only set a few things:
# self.display_name = self.get_display_name()
# needs_geocode = True
# else:
# old_self = self.__class__.objects.get(id = self.id)
# if old_self.city != self.city or old_self.state != self.state or self.geocode is None:
# needs_geocode = True
# if old_self.display_name != self.display_name or old_self.first_name != self.first_name or old_self.last_name != self.last_name:
# self.display_name = self.get_display_name() # check if display name has changed
# if old_self.avatar and old_self.avatar != self.avatar:
# os.remove(old_self.avatar.path)
# if self.city and self.state and needs_geocode:
# geocode = get_geocode(self.city, self.state, street_address=self.street_address, zipcode=self.zip)
# if geocode and geocode != '620':
# self.geocode = ', '.join(geocode)
# if self.signature:
# self.signature = strip_tags(self.signature)
# if self.bio:
# self.bio_formatted = sanetize_text(self.bio)
#
# super(Profile, self).save(*args, **kwargs)
#
# # fix this for current URL -- use permalink
# def get_absolute_url(self):
# return reverse('view_profile', args=[self.username])
#
# def get_display_name(self):
# """
# Determined display screen name based on the first of
# display_name, full name, or username.
# """
# if self.display_name:
# return self.display_name
# elif self.first_name and self.last_name:
# return '{0} {1}'.format(self.first_name, self.last_name)
# else:
# return self.username
#
# Path: tango_user/forms.py
# class ProfileCreationForm(UserCreationForm):
#
# class Meta:
# model = Profile
# fields = ("username",)
, which may contain function names, class names, or code. Output only the next line. | admin.site.register(Profile, ProfileAdmin) |
Given the code snippet: <|code_start|>
def deactivate(modeladmin, request, queryset):
queryset.update(is_active=True)
deactivate.short_description = "Deactivate selected users"
class ProfileAdmin(UserAdmin):
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Profile
from .forms import ProfileCreationForm
and context (functions, classes, or occasionally code) from other files:
# Path: tango_user/models.py
# class Profile(AbstractUser):
# """
# Subclasses AbstractUser to provide site-specific user fields.
# """
# display_name = models.CharField(
# max_length=200,
# blank=True,
# null=True,
# help_text="""
# If you would prefer a different screen name, enter it here.
# Spaces are allowed. Note: your username will not change.
# """
# )
# street_address = models.CharField(
# max_length=255,
# blank=True,
# help_text="Will never be shown publicly on the site.")
# city = models.CharField(max_length=200, blank=True)
# state = models.CharField(max_length=200, blank=True)
# country = models.CharField(max_length=200, blank=True)
# zipcode = models.CharField(
# 'ZIP/Postal Code',
# max_length=10,
# blank=True,
# help_text="Will never be shown publicly on the site."
# )
# interests = models.CharField(max_length=200, blank=True)
# occupation = models.CharField(max_length=200, blank=True)
# birthday = models.DateField(blank=True, null=True)
# homepage = models.URLField('Your web site', blank=True)
# bio = models.TextField(help_text='Tell us a bit about yourself.', blank=True, null=True)
# bio_formatted = models.TextField(blank=True, editable=False)
# signature = models.CharField(
# max_length=255,
# blank=True,
# help_text="""
# You can have a short signature line on the posts and comments.
# Members who choose to view signatures can see it. HTML is not allowed.
# """
# )
# geocode = models.CharField(max_length=200, null=True, blank=True)
# avatar = models.ImageField(blank=True, null=True, upload_to=set_img_path)
# if 'fretboard' in settings.INSTALLED_APPS:
# post_count = models.IntegerField(default="0", editable=False)
#
# #preferences
# display_on_map = models.BooleanField(default=True)
# open_links = models.BooleanField(
# "Open links in new window",
# default=False,
# help_text="Check if you would like links to automatically open in a new window."
# )
# show_signatures = models.BooleanField(
# default=False,
# help_text="Check if you would like to see signatures attached to forum posts."
# )
# theme = models.CharField(max_length=100, blank=True, choices=THEME_CHOICES)
#
# class Meta:
# ordering = ('display_name',)
#
# def __unicode__(self):
# return self.username
#
# def save(self, *args, **kwargs):
# needs_geocode = False
# if self.id is None: # For new user, only set a few things:
# self.display_name = self.get_display_name()
# needs_geocode = True
# else:
# old_self = self.__class__.objects.get(id = self.id)
# if old_self.city != self.city or old_self.state != self.state or self.geocode is None:
# needs_geocode = True
# if old_self.display_name != self.display_name or old_self.first_name != self.first_name or old_self.last_name != self.last_name:
# self.display_name = self.get_display_name() # check if display name has changed
# if old_self.avatar and old_self.avatar != self.avatar:
# os.remove(old_self.avatar.path)
# if self.city and self.state and needs_geocode:
# geocode = get_geocode(self.city, self.state, street_address=self.street_address, zipcode=self.zip)
# if geocode and geocode != '620':
# self.geocode = ', '.join(geocode)
# if self.signature:
# self.signature = strip_tags(self.signature)
# if self.bio:
# self.bio_formatted = sanetize_text(self.bio)
#
# super(Profile, self).save(*args, **kwargs)
#
# # fix this for current URL -- use permalink
# def get_absolute_url(self):
# return reverse('view_profile', args=[self.username])
#
# def get_display_name(self):
# """
# Determined display screen name based on the first of
# display_name, full name, or username.
# """
# if self.display_name:
# return self.display_name
# elif self.first_name and self.last_name:
# return '{0} {1}'.format(self.first_name, self.last_name)
# else:
# return self.username
#
# Path: tango_user/forms.py
# class ProfileCreationForm(UserCreationForm):
#
# class Meta:
# model = Profile
# fields = ("username",)
. Output only the next line. | add_form = ProfileCreationForm |
Next line prediction: <|code_start|>
class PublicProfileForm(forms.ModelForm):
"""
Allows for profile and settings updates.
Note that template checks for "Open board links" label.
Anything below that will be in a 'settings' fieldset.
"""
class Meta:
<|code_end|>
. Use current file imports:
(from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Profile)
and context including class names, function names, or small code snippets from other files:
# Path: tango_user/models.py
# class Profile(AbstractUser):
# """
# Subclasses AbstractUser to provide site-specific user fields.
# """
# display_name = models.CharField(
# max_length=200,
# blank=True,
# null=True,
# help_text="""
# If you would prefer a different screen name, enter it here.
# Spaces are allowed. Note: your username will not change.
# """
# )
# street_address = models.CharField(
# max_length=255,
# blank=True,
# help_text="Will never be shown publicly on the site.")
# city = models.CharField(max_length=200, blank=True)
# state = models.CharField(max_length=200, blank=True)
# country = models.CharField(max_length=200, blank=True)
# zipcode = models.CharField(
# 'ZIP/Postal Code',
# max_length=10,
# blank=True,
# help_text="Will never be shown publicly on the site."
# )
# interests = models.CharField(max_length=200, blank=True)
# occupation = models.CharField(max_length=200, blank=True)
# birthday = models.DateField(blank=True, null=True)
# homepage = models.URLField('Your web site', blank=True)
# bio = models.TextField(help_text='Tell us a bit about yourself.', blank=True, null=True)
# bio_formatted = models.TextField(blank=True, editable=False)
# signature = models.CharField(
# max_length=255,
# blank=True,
# help_text="""
# You can have a short signature line on the posts and comments.
# Members who choose to view signatures can see it. HTML is not allowed.
# """
# )
# geocode = models.CharField(max_length=200, null=True, blank=True)
# avatar = models.ImageField(blank=True, null=True, upload_to=set_img_path)
# if 'fretboard' in settings.INSTALLED_APPS:
# post_count = models.IntegerField(default="0", editable=False)
#
# #preferences
# display_on_map = models.BooleanField(default=True)
# open_links = models.BooleanField(
# "Open links in new window",
# default=False,
# help_text="Check if you would like links to automatically open in a new window."
# )
# show_signatures = models.BooleanField(
# default=False,
# help_text="Check if you would like to see signatures attached to forum posts."
# )
# theme = models.CharField(max_length=100, blank=True, choices=THEME_CHOICES)
#
# class Meta:
# ordering = ('display_name',)
#
# def __unicode__(self):
# return self.username
#
# def save(self, *args, **kwargs):
# needs_geocode = False
# if self.id is None: # For new user, only set a few things:
# self.display_name = self.get_display_name()
# needs_geocode = True
# else:
# old_self = self.__class__.objects.get(id = self.id)
# if old_self.city != self.city or old_self.state != self.state or self.geocode is None:
# needs_geocode = True
# if old_self.display_name != self.display_name or old_self.first_name != self.first_name or old_self.last_name != self.last_name:
# self.display_name = self.get_display_name() # check if display name has changed
# if old_self.avatar and old_self.avatar != self.avatar:
# os.remove(old_self.avatar.path)
# if self.city and self.state and needs_geocode:
# geocode = get_geocode(self.city, self.state, street_address=self.street_address, zipcode=self.zip)
# if geocode and geocode != '620':
# self.geocode = ', '.join(geocode)
# if self.signature:
# self.signature = strip_tags(self.signature)
# if self.bio:
# self.bio_formatted = sanetize_text(self.bio)
#
# super(Profile, self).save(*args, **kwargs)
#
# # fix this for current URL -- use permalink
# def get_absolute_url(self):
# return reverse('view_profile', args=[self.username])
#
# def get_display_name(self):
# """
# Determined display screen name based on the first of
# display_name, full name, or username.
# """
# if self.display_name:
# return self.display_name
# elif self.first_name and self.last_name:
# return '{0} {1}'.format(self.first_name, self.last_name)
# else:
# return self.username
. Output only the next line. | model = Profile |
Predict the next line for this snippet: <|code_start|>
register = template.Library()
@register.simple_tag()
def get_video_list(count=5):
"""
Returns recent videos limited to count.
Usage: "{% get_video_list as video_list %}"
"""
<|code_end|>
with the help of current file imports:
from django import template
from video.models import Video
and context from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
, which may contain function names, class names, or code. Output only the next line. | return Video.published.all()[:count] |
Continue the code snippet: <|code_start|>
paginate_by = getattr(settings, "PAGINATE_BY", 25)
class VideoList(ListView):
"""
Returns a list of all videos.
"""
template_name = 'video/video_list.html'
paginate_by = paginate_by
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.views.generic import ListView, DetailView
from video.models import Video, VideoGallery
and context (classes, functions, or code) from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
. Output only the next line. | model = Video |
Using the snippet: <|code_start|>
paginate_by = getattr(settings, "PAGINATE_BY", 25)
class VideoList(ListView):
"""
Returns a list of all videos.
"""
template_name = 'video/video_list.html'
paginate_by = paginate_by
model = Video
video_list = VideoList.as_view()
class VideoDetail(DetailView):
"""
Returns a video detail
"""
template_name = 'video/video_detail.html'
model = Video
video_detail = VideoDetail.as_view()
class VideoGalleryList(ListView):
"""
Returns a list of all video Galleries.
"""
template_name = 'video/gallery_list.html'
paginate_by = paginate_by
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.views.generic import ListView, DetailView
from video.models import Video, VideoGallery
and context (class names, function names, or code) available:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
. Output only the next line. | model = VideoGallery |
Given snippet: <|code_start|>
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
blank=True,
null=True
)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
objects = VideoManager()
pub_objects = PublishedVideoManager()
def __str__(self):
return '{}: {}'.format(self.source, self.title)
def get_absolute_url(self):
return reverse('video_detail', args=(self.slug,))
def save(self, *args, **kwargs):
if self.title and not self.slug:
self.slug = slugify(self.title)
if not self.embed_src:
if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context:
# Path: video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlsplit(video.url)
# query = parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
#
# # api docs
# # http://gdata.youtube.com/feeds/api/videos/hNRHHRjep3E
# # https://www.googleapis.com/youtube/v3/videos?id=hNRHHRjep3E&part=snippet,contentDetails,statistics
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = untangle.parse(video_data)
#
# video.title = xml.title
# video.slug = slugify(video.title)
# video.summary = xml.content
# #video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# #video_data = urlopen(api_url).read()
# xml = untangle.parse(api_url)
# xmlvideo = xml.videos.video
# video.title = xmlvideo.title.cdata
# video.slug = slugify(video.title)
# video.summary = xmlvideo.description.cdata
# video.thumb_url = xmlvideo.thumbnail_large.cdata
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
#
# Path: video/managers.py
# class VideoManager(models.Manager):
# """
# If RESTRICT_CONTENT_TO_SITE is True in settings,
# will limit video to current site.
#
# Usage is simply video.objects.all()
# """
# def get_queryset(self):
# videos = super(VideoManager, self).get_queryset()
# if RESTRICT_CONTENT_TO_SITE:
# videos.filter(sites__id__exact=settings.SITE_ID)
# return videos
#
# class PublishedVideoManager(VideoManager):
# """
# Extends VideoManager to only return videos
# - That are published
# - and have a created date greater than or equal to now.
#
# Usage is gallery.published.all()
# """
# def get_queryset(self):
# videos = super(PublishedVideoManager, self).get_queryset()
# videos.filter(published=True, created__lte=now)
# return videos
which might include code, classes, or functions. Output only the next line. | self = get_youtube_data(self) |
Given the following code snippet before the placeholder: <|code_start|> on_delete=models.CASCADE,
blank=True,
null=True
)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
objects = VideoManager()
pub_objects = PublishedVideoManager()
def __str__(self):
return '{}: {}'.format(self.source, self.title)
def get_absolute_url(self):
return reverse('video_detail', args=(self.slug,))
def save(self, *args, **kwargs):
if self.title and not self.slug:
self.slug = slugify(self.title)
if not self.embed_src:
if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
self = get_youtube_data(self)
if 'vimeo.com/' in self.url:
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context including class names, function names, and sometimes code from other files:
# Path: video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlsplit(video.url)
# query = parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
#
# # api docs
# # http://gdata.youtube.com/feeds/api/videos/hNRHHRjep3E
# # https://www.googleapis.com/youtube/v3/videos?id=hNRHHRjep3E&part=snippet,contentDetails,statistics
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = untangle.parse(video_data)
#
# video.title = xml.title
# video.slug = slugify(video.title)
# video.summary = xml.content
# #video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# #video_data = urlopen(api_url).read()
# xml = untangle.parse(api_url)
# xmlvideo = xml.videos.video
# video.title = xmlvideo.title.cdata
# video.slug = slugify(video.title)
# video.summary = xmlvideo.description.cdata
# video.thumb_url = xmlvideo.thumbnail_large.cdata
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
#
# Path: video/managers.py
# class VideoManager(models.Manager):
# """
# If RESTRICT_CONTENT_TO_SITE is True in settings,
# will limit video to current site.
#
# Usage is simply video.objects.all()
# """
# def get_queryset(self):
# videos = super(VideoManager, self).get_queryset()
# if RESTRICT_CONTENT_TO_SITE:
# videos.filter(sites__id__exact=settings.SITE_ID)
# return videos
#
# class PublishedVideoManager(VideoManager):
# """
# Extends VideoManager to only return videos
# - That are published
# - and have a created date greater than or equal to now.
#
# Usage is gallery.published.all()
# """
# def get_queryset(self):
# videos = super(PublishedVideoManager, self).get_queryset()
# videos.filter(published=True, created__lte=now)
# return videos
. Output only the next line. | self = get_vimeo_data(self) |
Predict the next line for this snippet: <|code_start|> )
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
objects = VideoManager()
pub_objects = PublishedVideoManager()
def __str__(self):
return '{}: {}'.format(self.source, self.title)
def get_absolute_url(self):
return reverse('video_detail', args=(self.slug,))
def save(self, *args, **kwargs):
if self.title and not self.slug:
self.slug = slugify(self.title)
if not self.embed_src:
if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
self = get_youtube_data(self)
if 'vimeo.com/' in self.url:
self = get_vimeo_data(self)
if 'ustream.tv/' in self.url:
<|code_end|>
with the help of current file imports:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context from other files:
# Path: video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlsplit(video.url)
# query = parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
#
# # api docs
# # http://gdata.youtube.com/feeds/api/videos/hNRHHRjep3E
# # https://www.googleapis.com/youtube/v3/videos?id=hNRHHRjep3E&part=snippet,contentDetails,statistics
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = untangle.parse(video_data)
#
# video.title = xml.title
# video.slug = slugify(video.title)
# video.summary = xml.content
# #video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# #video_data = urlopen(api_url).read()
# xml = untangle.parse(api_url)
# xmlvideo = xml.videos.video
# video.title = xmlvideo.title.cdata
# video.slug = slugify(video.title)
# video.summary = xmlvideo.description.cdata
# video.thumb_url = xmlvideo.thumbnail_large.cdata
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
#
# Path: video/managers.py
# class VideoManager(models.Manager):
# """
# If RESTRICT_CONTENT_TO_SITE is True in settings,
# will limit video to current site.
#
# Usage is simply video.objects.all()
# """
# def get_queryset(self):
# videos = super(VideoManager, self).get_queryset()
# if RESTRICT_CONTENT_TO_SITE:
# videos.filter(sites__id__exact=settings.SITE_ID)
# return videos
#
# class PublishedVideoManager(VideoManager):
# """
# Extends VideoManager to only return videos
# - That are published
# - and have a created date greater than or equal to now.
#
# Usage is gallery.published.all()
# """
# def get_queryset(self):
# videos = super(PublishedVideoManager, self).get_queryset()
# videos.filter(published=True, created__lte=now)
# return videos
, which may contain function names, class names, or code. Output only the next line. | self = get_ustream_data(self) |
Continue the code snippet: <|code_start|> help_text=""""
Acceptable sources are Youtube, Vimeo and Ustream.
Please give the link URL, not the embed code.
"""
)
hide_info = models.BooleanField(
"Hide title and description",
default=False,
help_text="""
If checked, the video title and description will not be shown.
Left unchecked, the video will attempt to display the title and description
from the video source.
"""
)
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
blank=True,
null=True
)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
<|code_end|>
. Use current file imports:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context (classes, functions, or code) from other files:
# Path: video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlsplit(video.url)
# query = parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
#
# # api docs
# # http://gdata.youtube.com/feeds/api/videos/hNRHHRjep3E
# # https://www.googleapis.com/youtube/v3/videos?id=hNRHHRjep3E&part=snippet,contentDetails,statistics
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = untangle.parse(video_data)
#
# video.title = xml.title
# video.slug = slugify(video.title)
# video.summary = xml.content
# #video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# #video_data = urlopen(api_url).read()
# xml = untangle.parse(api_url)
# xmlvideo = xml.videos.video
# video.title = xmlvideo.title.cdata
# video.slug = slugify(video.title)
# video.summary = xmlvideo.description.cdata
# video.thumb_url = xmlvideo.thumbnail_large.cdata
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
#
# Path: video/managers.py
# class VideoManager(models.Manager):
# """
# If RESTRICT_CONTENT_TO_SITE is True in settings,
# will limit video to current site.
#
# Usage is simply video.objects.all()
# """
# def get_queryset(self):
# videos = super(VideoManager, self).get_queryset()
# if RESTRICT_CONTENT_TO_SITE:
# videos.filter(sites__id__exact=settings.SITE_ID)
# return videos
#
# class PublishedVideoManager(VideoManager):
# """
# Extends VideoManager to only return videos
# - That are published
# - and have a created date greater than or equal to now.
#
# Usage is gallery.published.all()
# """
# def get_queryset(self):
# videos = super(PublishedVideoManager, self).get_queryset()
# videos.filter(published=True, created__lte=now)
# return videos
. Output only the next line. | objects = VideoManager() |
Continue the code snippet: <|code_start|> Acceptable sources are Youtube, Vimeo and Ustream.
Please give the link URL, not the embed code.
"""
)
hide_info = models.BooleanField(
"Hide title and description",
default=False,
help_text="""
If checked, the video title and description will not be shown.
Left unchecked, the video will attempt to display the title and description
from the video source.
"""
)
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
blank=True,
null=True
)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
objects = VideoManager()
<|code_end|>
. Use current file imports:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context (classes, functions, or code) from other files:
# Path: video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlsplit(video.url)
# query = parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
#
# # api docs
# # http://gdata.youtube.com/feeds/api/videos/hNRHHRjep3E
# # https://www.googleapis.com/youtube/v3/videos?id=hNRHHRjep3E&part=snippet,contentDetails,statistics
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = untangle.parse(video_data)
#
# video.title = xml.title
# video.slug = slugify(video.title)
# video.summary = xml.content
# #video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# #video_data = urlopen(api_url).read()
# xml = untangle.parse(api_url)
# xmlvideo = xml.videos.video
# video.title = xmlvideo.title.cdata
# video.slug = slugify(video.title)
# video.summary = xmlvideo.description.cdata
# video.thumb_url = xmlvideo.thumbnail_large.cdata
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
#
# Path: video/managers.py
# class VideoManager(models.Manager):
# """
# If RESTRICT_CONTENT_TO_SITE is True in settings,
# will limit video to current site.
#
# Usage is simply video.objects.all()
# """
# def get_queryset(self):
# videos = super(VideoManager, self).get_queryset()
# if RESTRICT_CONTENT_TO_SITE:
# videos.filter(sites__id__exact=settings.SITE_ID)
# return videos
#
# class PublishedVideoManager(VideoManager):
# """
# Extends VideoManager to only return videos
# - That are published
# - and have a created date greater than or equal to now.
#
# Usage is gallery.published.all()
# """
# def get_queryset(self):
# videos = super(PublishedVideoManager, self).get_queryset()
# videos.filter(published=True, created__lte=now)
# return videos
. Output only the next line. | pub_objects = PublishedVideoManager() |
Given snippet: <|code_start|>
UserModel = get_user_model()
past_year = datetime.datetime.now() - datetime.timedelta(days=365)
class MemberList(ListView):
"""
Renders either default user list (paginated) or search results.
To-do: split search to separate view, make pagination work better.
"""
queryset = UserModel.objects.filter(is_active=1, last_login__gte=past_year).order_by('display_name').values()
template_name = "users/user_list.html"
paginate_by = 100
def get_context_data(self, **kwargs):
context = super(MemberList, self).get_context_data(**kwargs)
if 'display_name' in self.request.GET or 'state' in self.request.GET:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import json
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic import ListView
from django.views.generic.edit import UpdateView
from .filters import ProfileFilter
from .forms import PublicProfileForm, ProfileSettingsForm
and context:
# Path: tango_user/filters.py
# class ProfileFilter(django_filters.FilterSet):
# display_name = django_filters.CharFilter(lookup_expr='icontains')
#
# class Meta:
# model = get_user_model()
# fields = ['display_name']
#
# Path: tango_user/forms.py
# class PublicProfileForm(forms.ModelForm):
# """
# Allows for profile and settings updates.
# Note that template checks for "Open board links" label.
# Anything below that will be in a 'settings' fieldset.
# """
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'street_address',
# 'city',
# 'state',
# 'country',
# 'zipcode',
# 'occupation',
# 'interests',
# 'birthday',
# 'homepage',
# 'bio',
# 'avatar',
# 'signature',
# )
#
# class ProfileSettingsForm(forms.ModelForm):
# """
# Allows for modifying profile settings
# """
# class Meta:
# model = Profile
# fields = (
# 'display_on_map',
# 'show_signatures',
# 'theme'
# )
which might include code, classes, or functions. Output only the next line. | filter = ProfileFilter(self.request.GET, queryset=self.queryset)
|
Given snippet: <|code_start|>
UserModel = get_user_model()
past_year = datetime.datetime.now() - datetime.timedelta(days=365)
class MemberList(ListView):
"""
Renders either default user list (paginated) or search results.
To-do: split search to separate view, make pagination work better.
"""
queryset = UserModel.objects.filter(is_active=1, last_login__gte=past_year).order_by('display_name').values()
template_name = "users/user_list.html"
paginate_by = 100
def get_context_data(self, **kwargs):
context = super(MemberList, self).get_context_data(**kwargs)
if 'display_name' in self.request.GET or 'state' in self.request.GET:
filter = ProfileFilter(self.request.GET, queryset=self.queryset)
else:
filter = ProfileFilter()
context['filter'] = filter
return context
member_index = MemberList.as_view()
class EditProfile(UpdateView):
model = UserModel
template_name = "users/user_edit_form.html"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import json
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic import ListView
from django.views.generic.edit import UpdateView
from .filters import ProfileFilter
from .forms import PublicProfileForm, ProfileSettingsForm
and context:
# Path: tango_user/filters.py
# class ProfileFilter(django_filters.FilterSet):
# display_name = django_filters.CharFilter(lookup_expr='icontains')
#
# class Meta:
# model = get_user_model()
# fields = ['display_name']
#
# Path: tango_user/forms.py
# class PublicProfileForm(forms.ModelForm):
# """
# Allows for profile and settings updates.
# Note that template checks for "Open board links" label.
# Anything below that will be in a 'settings' fieldset.
# """
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'street_address',
# 'city',
# 'state',
# 'country',
# 'zipcode',
# 'occupation',
# 'interests',
# 'birthday',
# 'homepage',
# 'bio',
# 'avatar',
# 'signature',
# )
#
# class ProfileSettingsForm(forms.ModelForm):
# """
# Allows for modifying profile settings
# """
# class Meta:
# model = Profile
# fields = (
# 'display_on_map',
# 'show_signatures',
# 'theme'
# )
which might include code, classes, or functions. Output only the next line. | form_class = PublicProfileForm
|
Predict the next line for this snippet: <|code_start|> """
queryset = UserModel.objects.filter(is_active=1, last_login__gte=past_year).order_by('display_name').values()
template_name = "users/user_list.html"
paginate_by = 100
def get_context_data(self, **kwargs):
context = super(MemberList, self).get_context_data(**kwargs)
if 'display_name' in self.request.GET or 'state' in self.request.GET:
filter = ProfileFilter(self.request.GET, queryset=self.queryset)
else:
filter = ProfileFilter()
context['filter'] = filter
return context
member_index = MemberList.as_view()
class EditProfile(UpdateView):
model = UserModel
template_name = "users/user_edit_form.html"
form_class = PublicProfileForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(EditProfile, self).dispatch(*args, **kwargs)
def get_object(self, queryset=None):
return self.request.user
def get_context_data(self, **kwargs):
context = super(EditProfile, self).get_context_data(**kwargs)
<|code_end|>
with the help of current file imports:
import datetime
import json
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic import ListView
from django.views.generic.edit import UpdateView
from .filters import ProfileFilter
from .forms import PublicProfileForm, ProfileSettingsForm
and context from other files:
# Path: tango_user/filters.py
# class ProfileFilter(django_filters.FilterSet):
# display_name = django_filters.CharFilter(lookup_expr='icontains')
#
# class Meta:
# model = get_user_model()
# fields = ['display_name']
#
# Path: tango_user/forms.py
# class PublicProfileForm(forms.ModelForm):
# """
# Allows for profile and settings updates.
# Note that template checks for "Open board links" label.
# Anything below that will be in a 'settings' fieldset.
# """
# class Meta:
# model = Profile
# fields = (
# 'display_name',
# 'street_address',
# 'city',
# 'state',
# 'country',
# 'zipcode',
# 'occupation',
# 'interests',
# 'birthday',
# 'homepage',
# 'bio',
# 'avatar',
# 'signature',
# )
#
# class ProfileSettingsForm(forms.ModelForm):
# """
# Allows for modifying profile settings
# """
# class Meta:
# model = Profile
# fields = (
# 'display_on_map',
# 'show_signatures',
# 'theme'
# )
, which may contain function names, class names, or code. Output only the next line. | context['settings_form'] = ProfileSettingsForm(instance=self.get_object())
|
Predict the next line after this snippet: <|code_start|>
class TestVideo(TestCase):
@unittest.skip("need to resolve API")
def test_youtube_video(self):
"""
Test that newly saved youtube videos
are correctly capturing values from youtube.
"""
url = 'https://www.youtube.com/watch?v=c-wXZ5-Yxuc'
<|code_end|>
using the current file's imports:
import unittest
from django.template import Template, Context
from django.test import TestCase
from django.urls import reverse
from video.models import Video, VideoGallery
from .forms import VideoForm
and any relevant context from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
#
# Path: video/forms.py
# class VideoForm(forms.ModelForm):
# class Meta:
# model = Video
# fields = ['title', 'summary', 'url', 'video_at_top', 'hide_info',]
#
# def __init__(self, *args, **kwargs):
# super(VideoForm, self).__init__(*args, **kwargs)
# self.fields['title'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['title'].required = False
# self.fields['summary'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['summary'].required = False
. Output only the next line. | test_video = Video(url=url) |
Given the following code snippet before the placeholder: <|code_start|> video_dict = test_video.__dict__
self.assertIn('title', video_dict)
self.assertIn('slug', video_dict)
self.assertIn('summary', video_dict)
self.assertIn('thumb_url', video_dict)
response = self.client.get(reverse('video_detail', args=[test_video.slug, ]))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed('video_detail.html')
self.assertIn('object', response.context)
object = response.context['object']
self.assertIsInstance(object, Video)
def test_recent_video_tag(self):
out = Template(
"{% load video_tags %}"
"{% get_video_list as video_list %}"
"{% for video in video_list %}"
"{{ video.title }},"
"{% endfor %}"
).render(Context())
self.assertEqual(out, '')
def test_video_form(self):
fields = VideoForm().fields
self.assertFalse(fields['title'].required)
self.assertFalse(fields['summary'].required)
def test_video_gallery_detail(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from django.template import Template, Context
from django.test import TestCase
from django.urls import reverse
from video.models import Video, VideoGallery
from .forms import VideoForm
and context including class names, function names, and sometimes code from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
#
# Path: video/forms.py
# class VideoForm(forms.ModelForm):
# class Meta:
# model = Video
# fields = ['title', 'summary', 'url', 'video_at_top', 'hide_info',]
#
# def __init__(self, *args, **kwargs):
# super(VideoForm, self).__init__(*args, **kwargs)
# self.fields['title'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['title'].required = False
# self.fields['summary'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['summary'].required = False
. Output only the next line. | gallery = VideoGallery.objects.create(title= 'test gallery', slug='test-gallery') |
Based on the snippet: <|code_start|> test_video.save()
self.assertIsInstance(test_video, Video)
self.assertEqual(test_video.source, 'vimeo')
self.assertTrue('Tango' in test_video.title)
video_dict = test_video.__dict__
self.assertIn('title', video_dict)
self.assertIn('slug', video_dict)
self.assertIn('summary', video_dict)
self.assertIn('thumb_url', video_dict)
response = self.client.get(reverse('video_detail', args=[test_video.slug, ]))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed('video_detail.html')
self.assertIn('object', response.context)
object = response.context['object']
self.assertIsInstance(object, Video)
def test_recent_video_tag(self):
out = Template(
"{% load video_tags %}"
"{% get_video_list as video_list %}"
"{% for video in video_list %}"
"{{ video.title }},"
"{% endfor %}"
).render(Context())
self.assertEqual(out, '')
def test_video_form(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from django.template import Template, Context
from django.test import TestCase
from django.urls import reverse
from video.models import Video, VideoGallery
from .forms import VideoForm
and context (classes, functions, sometimes code) from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
#
# Path: video/forms.py
# class VideoForm(forms.ModelForm):
# class Meta:
# model = Video
# fields = ['title', 'summary', 'url', 'video_at_top', 'hide_info',]
#
# def __init__(self, *args, **kwargs):
# super(VideoForm, self).__init__(*args, **kwargs)
# self.fields['title'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['title'].required = False
# self.fields['summary'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['summary'].required = False
. Output only the next line. | fields = VideoForm().fields |
Given snippet: <|code_start|>
class VideoInline(GenericTabularInline):
"""
Consistent inlined video for other content admin.
"""
model = Video
max_num = 2
extra = 1
fields = ('url', 'video_at_top', 'hide_info')
class VideoGalleryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
filter_horizontal = ['video_collection']
class VideoAdmin(admin.ModelAdmin):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from .forms import VideoForm
from video.models import Video, VideoGallery
and context:
# Path: video/forms.py
# class VideoForm(forms.ModelForm):
# class Meta:
# model = Video
# fields = ['title', 'summary', 'url', 'video_at_top', 'hide_info',]
#
# def __init__(self, *args, **kwargs):
# super(VideoForm, self).__init__(*args, **kwargs)
# self.fields['title'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['title'].required = False
# self.fields['summary'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['summary'].required = False
#
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
which might include code, classes, or functions. Output only the next line. | form = VideoForm |
Next line prediction: <|code_start|> """
Consistent inlined video for other content admin.
"""
model = Video
max_num = 2
extra = 1
fields = ('url', 'video_at_top', 'hide_info')
class VideoGalleryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
filter_horizontal = ['video_collection']
class VideoAdmin(admin.ModelAdmin):
form = VideoForm
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'source')
fieldsets = (
('', {'fields': ('url', 'title', 'summary',)}),
('Admin fields', {
'description': 'These should be filled in for you, but you can edit them.',
'fields': ('slug', ),
'classes': ['collapse']
}),
)
admin.site.register(Video, VideoAdmin)
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from .forms import VideoForm
from video.models import Video, VideoGallery)
and context including class names, function names, or small code snippets from other files:
# Path: video/forms.py
# class VideoForm(forms.ModelForm):
# class Meta:
# model = Video
# fields = ['title', 'summary', 'url', 'video_at_top', 'hide_info',]
#
# def __init__(self, *args, **kwargs):
# super(VideoForm, self).__init__(*args, **kwargs)
# self.fields['title'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['title'].required = False
# self.fields['summary'].help_text = "We'll attempt to fill this in from the video service."
# self.fields['summary'].required = False
#
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
. Output only the next line. | admin.site.register(VideoGallery, VideoGalleryAdmin) |
Continue the code snippet: <|code_start|>
urlpatterns = [
path('', member_index, name="community_index"),
path('edit-profile/', edit_profile, name="edit_profile"),
<|code_end|>
. Use current file imports:
from django.urls import path
from .views import member_index, edit_profile, edit_settings, view_profile
and context (classes, functions, or code) from other files:
# Path: tango_user/views.py
# class MemberList(ListView):
# class EditProfile(UpdateView):
# class EditProfileSettings(EditProfile):
# def get_context_data(self, **kwargs):
# def dispatch(self, *args, **kwargs):
# def get_object(self, queryset=None):
# def get_context_data(self, **kwargs):
# def get_context_data(self, **kwargs):
# def form_valid(self, form, *args, **kwargs):
# def view_profile(request, slug='', pk=''):
. Output only the next line. | path('edit-settings/', edit_settings, name="edit_settings"), |
Using the snippet: <|code_start|>
urlpatterns = [
path('', member_index, name="community_index"),
path('edit-profile/', edit_profile, name="edit_profile"),
path('edit-settings/', edit_settings, name="edit_settings"),
<|code_end|>
, determine the next line of code. You have imports:
from django.urls import path
from .views import member_index, edit_profile, edit_settings, view_profile
and context (class names, function names, or code) available:
# Path: tango_user/views.py
# class MemberList(ListView):
# class EditProfile(UpdateView):
# class EditProfileSettings(EditProfile):
# def get_context_data(self, **kwargs):
# def dispatch(self, *args, **kwargs):
# def get_object(self, queryset=None):
# def get_context_data(self, **kwargs):
# def get_context_data(self, **kwargs):
# def form_valid(self, form, *args, **kwargs):
# def view_profile(request, slug='', pk=''):
. Output only the next line. | path('<int:pk>/', view_profile, name="view_profile_by_id"), |
Next line prediction: <|code_start|>
urlpatterns = [
path('', video_list, name="video_list"),
path('galleries/', video_gallery_list, name="video_gallery_list"),
<|code_end|>
. Use current file imports:
(from django.urls import path
from .views import video_list, video_gallery_list, video_detail, video_gallery_detail)
and context including class names, function names, or small code snippets from other files:
# Path: video/views.py
# class VideoList(ListView):
# class VideoDetail(DetailView):
# class VideoGalleryList(ListView):
# class VideoGalleryDetail(DetailView):
# def get_context_data(self, **kwargs):
. Output only the next line. | path('<slug:slug>/', video_detail, name='video_detail'), |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = [
path('', video_list, name="video_list"),
path('galleries/', video_gallery_list, name="video_gallery_list"),
path('<slug:slug>/', video_detail, name='video_detail'),
<|code_end|>
, predict the next line using imports from the current file:
from django.urls import path
from .views import video_list, video_gallery_list, video_detail, video_gallery_detail
and context including class names, function names, and sometimes code from other files:
# Path: video/views.py
# class VideoList(ListView):
# class VideoDetail(DetailView):
# class VideoGalleryList(ListView):
# class VideoGalleryDetail(DetailView):
# def get_context_data(self, **kwargs):
. Output only the next line. | path('gallery/<slug:slug>/', video_gallery_detail, name='video_gallery_detail'), |
Next line prediction: <|code_start|>
class TestVideo(TestCase):
def test_youtube_video(self):
"""
Test that newly saved youtube videos
are correctly capturing values from youtube.
"""
url = 'https://www.youtube.com/watch?v=c-wXZ5-Yxuc'
<|code_end|>
. Use current file imports:
(from django.template import Template, Context
from django.test import TestCase
from django.urls import reverse
from video.models import Video, VideoGallery
from .forms import VideoForm)
and context including class names, function names, or small code snippets from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
. Output only the next line. | test_video = Video(url=url) |
Next line prediction: <|code_start|> video_dict = test_video.__dict__
self.assertIn('title', video_dict)
self.assertIn('slug', video_dict)
self.assertIn('summary', video_dict)
self.assertIn('thumb_url', video_dict)
response = self.client.get(reverse('video_detail', args=[test_video.slug, ]))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed('video_detail.html')
self.assertIn('object', response.context)
object = response.context['object']
self.assertIsInstance(object, Video)
def test_recent_video_tag(self):
out = Template(
"{% load video_tags %}"
"{% get_video_list as video_list %}"
"{% for video in video_list %}"
"{{ video.title }},"
"{% endfor %}"
).render(Context())
self.assertEqual(out, '')
def test_video_form(self):
fields = VideoForm().fields
self.assertFalse(fields['title'].required)
self.assertFalse(fields['summary'].required)
def test_video_gallery_detail(self):
<|code_end|>
. Use current file imports:
(from django.template import Template, Context
from django.test import TestCase
from django.urls import reverse
from video.models import Video, VideoGallery
from .forms import VideoForm)
and context including class names, function names, or small code snippets from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
#
# class VideoGallery(models.Model):
# title = models.CharField(max_length=200)
# slug = models.SlugField(
# max_length=200,
# help_text="Used for URLs. Will auto-fill, but can be edited with caution."
# )
# gallery_credit = models.CharField(max_length=200, blank=True)
# summary = models.TextField(blank=True)
# featured = models.BooleanField(default=False)
# created = models.DateTimeField(auto_now_add=True)
# published = models.BooleanField(default=True)
# video_collection = models.ManyToManyField(Video)
#
# class Meta:
# verbose_name_plural = "video galleries"
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('video_gallery_detail', args=(self.slug,))
. Output only the next line. | gallery = VideoGallery.objects.create(title= 'test gallery', slug='test-gallery') |
Given the code snippet: <|code_start|> content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
blank=True,
null=True
)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
objects = VideoManager()
published = PublishedVideoManager()
def __unicode__(self):
return '{}: {}'.format(self.source, self.title)
@models.permalink
def get_absolute_url(self):
return ('video_detail', [self.slug])
def save(self, *args, **kwargs):
if self.title and not self.slug:
self.slug = slugify(self.title)
if not self.embed_src:
if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context (functions, classes, or occasionally code) from other files:
# Path: build/lib/video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlparse.urlsplit(video.url)
# query = urlparse.parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
# #http://gdata.youtube.com/feeds/api/videos/Agdvt9M3NJA
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = xmltramp.parse(video_data)
#
# video.title = unicode(xml.title)
# video.slug = slugify(video.title)
# video.summary = unicode(xml.content)
# video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = xmltramp.parse(video_data)
# video.title = unicode(xml.video.title)
# video.slug = slugify(video.title)
# video.summary = unicode(xml.video.description)
# video.thumb_url = unicode(xml.video.thumbnail_large)
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
. Output only the next line. | self = get_youtube_data(self) |
Based on the snippet: <|code_start|> blank=True,
null=True
)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
objects = VideoManager()
published = PublishedVideoManager()
def __unicode__(self):
return '{}: {}'.format(self.source, self.title)
@models.permalink
def get_absolute_url(self):
return ('video_detail', [self.slug])
def save(self, *args, **kwargs):
if self.title and not self.slug:
self.slug = slugify(self.title)
if not self.embed_src:
if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
self = get_youtube_data(self)
if 'vimeo.com/' in self.url:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context (classes, functions, sometimes code) from other files:
# Path: build/lib/video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlparse.urlsplit(video.url)
# query = urlparse.parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
# #http://gdata.youtube.com/feeds/api/videos/Agdvt9M3NJA
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = xmltramp.parse(video_data)
#
# video.title = unicode(xml.title)
# video.slug = slugify(video.title)
# video.summary = unicode(xml.content)
# video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = xmltramp.parse(video_data)
# video.title = unicode(xml.video.title)
# video.slug = slugify(video.title)
# video.summary = unicode(xml.video.description)
# video.thumb_url = unicode(xml.video.thumbnail_large)
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
. Output only the next line. | self = get_vimeo_data(self) |
Based on the snippet: <|code_start|> object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey()
key = models.CharField(max_length=20, blank=True, editable=False)
source = models.CharField(max_length=20, blank=True, editable=False)
embed_src = models.CharField(max_length=200, blank=True, editable=False)
thumb_url = models.CharField(max_length=200, blank=True, editable=False)
# Managers
objects = VideoManager()
published = PublishedVideoManager()
def __unicode__(self):
return '{}: {}'.format(self.source, self.title)
@models.permalink
def get_absolute_url(self):
return ('video_detail', [self.slug])
def save(self, *args, **kwargs):
if self.title and not self.slug:
self.slug = slugify(self.title)
if not self.embed_src:
if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
self = get_youtube_data(self)
if 'vimeo.com/' in self.url:
self = get_vimeo_data(self)
if 'ustream.tv/' in self.url:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.template.defaultfilters import slugify
from .helpers import get_youtube_data, get_vimeo_data, get_ustream_data
from .managers import VideoManager, PublishedVideoManager
from tango_shared.models import BaseContentModel
and context (classes, functions, sometimes code) from other files:
# Path: build/lib/video/helpers.py
# def get_youtube_data(video):
# """
# Helper to extract video and thumbnail from youtube
# """
# video.source = 'youtube'
# if 'youtube.com/watch' in video.url:
# parsed = urlparse.urlsplit(video.url)
# query = urlparse.parse_qs(parsed.query)
# try:
# video.key = query.get('v')[0]
# except IndexError:
# video.key = None
# else:
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.youtube.com/embed/'
# #http://gdata.youtube.com/feeds/api/videos/Agdvt9M3NJA
# api_url = 'http://gdata.youtube.com/feeds/api/videos/{}'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = xmltramp.parse(video_data)
#
# video.title = unicode(xml.title)
# video.slug = slugify(video.title)
# video.summary = unicode(xml.content)
# video.thumb_url = xml[xml_media.group][xml_media.thumbnail:][1]('url')
# return video
#
# def get_vimeo_data(video):
# """
# Helper to extract video and thumbnail from vimeo.
# """
# #http://vimeo.com/67325705 -- Tumbleweed Tango
# video.source = 'vimeo'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://player.vimeo.com/video/'
#
# api_url = 'http://vimeo.com/api/v2/video/{}.xml'.format(video.key)
# video_data = urlopen(api_url).read()
# xml = xmltramp.parse(video_data)
# video.title = unicode(xml.video.title)
# video.slug = slugify(video.title)
# video.summary = unicode(xml.video.description)
# video.thumb_url = unicode(xml.video.thumbnail_large)
# return video
#
# def get_ustream_data(video):
# """
# Helper to extract video and thumbnail from ustream.
# """
#
# video.source = 'ustream'
# video.key = video.url.rsplit('/', 1)[1]
# video.embed_src = 'http://www.ustream.tv/embed/'
# if 'recorded' in video.url:
# video.embed_src += '/recorded/'
# video.title = "Ustream video"
# video.slug = 'ustream-{}'.format(video.key)
# return video
. Output only the next line. | self = get_ustream_data(self) |
Predict the next line for this snippet: <|code_start|>
register = template.Library()
@register.simple_tag()
def get_video_list(count=5):
"""
Returns recent videos limited to count.
Usage: "{% get_video_list as video_list %}"
"""
<|code_end|>
with the help of current file imports:
from django import template
from video.models import Video
and context from other files:
# Path: video/models.py
# class Video(BaseContentModel):
# video_at_top = models.BooleanField(
# "Put video at top",
# default=False,
# help_text="""
# If checked, the video will appear preceding the body
# of any related content instead of following.
# """
# )
# url = models.CharField(
# max_length=200,
# blank=True,
# help_text=""""
# Acceptable sources are Youtube, Vimeo and Ustream.
# Please give the link URL, not the embed code.
# """
# )
# hide_info = models.BooleanField(
# "Hide title and description",
# default=False,
# help_text="""
# If checked, the video title and description will not be shown.
# Left unchecked, the video will attempt to display the title and description
# from the video source.
# """
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# blank=True,
# null=True
# )
# object_id = models.PositiveIntegerField(blank=True, null=True)
# content_object = GenericForeignKey()
#
# key = models.CharField(max_length=20, blank=True, editable=False)
# source = models.CharField(max_length=20, blank=True, editable=False)
# embed_src = models.CharField(max_length=200, blank=True, editable=False)
# thumb_url = models.CharField(max_length=200, blank=True, editable=False)
#
# # Managers
# objects = VideoManager()
# pub_objects = PublishedVideoManager()
#
# def __str__(self):
# return '{}: {}'.format(self.source, self.title)
#
# def get_absolute_url(self):
# return reverse('video_detail', args=(self.slug,))
#
# def save(self, *args, **kwargs):
# if self.title and not self.slug:
# self.slug = slugify(self.title)
# if not self.embed_src:
# if 'youtube.com/watch' in self.url or 'youtu.be/' in self.url:
# self = get_youtube_data(self)
#
# if 'vimeo.com/' in self.url:
# self = get_vimeo_data(self)
#
# if 'ustream.tv/' in self.url:
# self = get_ustream_data(self)
#
# if self.key and self.embed_src:
# self.embed_src = """
# <iframe src="{}{}" height="360" width="100%%"></iframe>
# """.format(self.embed_src, self.key)
# super(Video, self).save()
#
# def get_image(self):
# return self.thumb_url
, which may contain function names, class names, or code. Output only the next line. | return Video.pub_objects.all()[:count] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.