Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> with pytest.raises(LocalProtocolError): validate(my_re, b"0.") groups = validate(my_re, b"0.1") assert groups == {"group1": b"0", "group2": b"1"} # successful partial matches are an error - must match whole string with pytest.raises(Loc...
class S(Sentinel, metaclass=Sentinel):
Given the code snippet: <|code_start|> except LocalProtocolError as e: assert str(e) == "foo" assert e.error_status_hint == 400 try: raise LocalProtocolError("foo", error_status_hint=418) except LocalProtocolError as e: assert str(e) == "foo" assert e.error_status_hin...
validate(my_re, b"0.")
Predict the next line for this snippet: <|code_start|># "a proxy MUST NOT change the order of these field values when forwarding a # message" # (and there are several headers where the order indicates a preference) # # Multiple occurences of the same header: # "A sender MUST NOT generate multiple header fields with the...
_field_name_re = re.compile(field_name.encode("ascii"))
Given snippet: <|code_start|># message" # (and there are several headers where the order indicates a preference) # # Multiple occurences of the same header: # "A sender MUST NOT generate multiple header fields with the same field name # in a message unless either the entire field value for that header field is # define...
_field_value_re = re.compile(field_value.encode("ascii"))
Predict the next line for this snippet: <|code_start|> @overload def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: ... @overload def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: ... @overload def normalize_and_validate( headers: Union[...
name = bytesify(name)
Based on the snippet: <|code_start|>@overload def normalize_and_validate( headers: Union[Headers, HeaderTypes], _parsed: bool = False ) -> Headers: ... def normalize_and_validate( headers: Union[Headers, HeaderTypes], _parsed: bool = False ) -> Headers: new_headers = [] seen_content_length = None ...
raise LocalProtocolError("conflicting Content-Length headers")
Given the following code snippet before the placeholder: <|code_start|>@overload def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: ... @overload def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: ... @overload def normalize_and_validate( ...
validate(_field_name_re, name, "Illegal header name {!r}", name)
Given the following code snippet before the placeholder: <|code_start|> # The agents - the brain and the ball net = NEAT.NeuralNetwork() genome.BuildPhenotype(net) agent = NN_agent(space, net) ball = Ball(space) tstep = 0 bd = 1000000 while tstep < max_timesteps: tstep += 1 ...
cv2.imshow("current best", Draw(net))
Given the following code snippet before the placeholder: <|code_start|> if event.type == QUIT: exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: exit() elif event.type == KEYDOWN and event.key == K_f: fast_mode = not fast_mode...
cv2.imshow("current best", Draw(net))
Next line prediction: <|code_start|>from __future__ import absolute_import DEFAULT_CONF_NAME = "ricloud.ini" def get_config(config_name=DEFAULT_CONF_NAME): <|code_end|> . Use current file imports: (import os from ricloud.compat import RawConfigParser) and context including class names, function names, or small ...
config = RawConfigParser()
Given the code snippet: <|code_start|> def log_info(message, *args, **kwargs): logger.info(message, *args, **kwargs) def generate_timestamp(): return int(time.time()) def _encode(data): """Adapted from Django source: https://github.com/django/django/blob/master/django/core/serializers/json.py ""...
return compat.to_str(data)
Using the snippet: <|code_start|> @pytest.fixture def nested_obj(): return ResourceFixture( "abcd1234", **{"nested": {"id": "abcd123", "resource": "test_resource"}} ) class TestResource(object): def test_ok(self, resource_obj): assert resource_obj.id == "abcd1234" assert resource_o...
return List(
Next line prediction: <|code_start|>from __future__ import absolute_import, unicode_literals DEFAULT_ALGORITHM = hashlib.sha256 def hmac_sign(message, key, algorithm=None): """Get a hmac signature of a message using the give key.""" algorithm = algorithm or DEFAULT_ALGORITHM return hmac.new( <|code_e...
compat.want_bytes(key), compat.want_bytes(message), digestmod=algorithm
Continue the code snippet: <|code_start|>def hmac_verify(digest, message, key, algorithm=None): """Check a hmac signature is valid for a given message and key.""" algorithm = algorithm or DEFAULT_ALGORITHM return hmac.compare_digest(hmac_sign(message, key), digest) class Signature: """Helper for hand...
signature = compat.want_text(encode_b64(self.signature))
Next line prediction: <|code_start|> class InvalidSignature(SignatureError): """Signature did not match the expected signature given the payload and secret.""" class InvalidSignatureTimestamp(SignatureError): """Timestamp too old, not accepting signature as relevant.""" def __init__(self, ...
signature = decode_b64(compat.want_bytes(signature))
Given snippet: <|code_start|> self.timestamp = timestamp _header_format = "t={timestamp},s={signature}" def to_header(self): """Dump the signature to a header format.""" signature = compat.want_text(encode_b64(self.signature)) return Signature._header_format.format( ...
timestamp = compat.want_text(generate_timestamp())
Next line prediction: <|code_start|> help="Automatically sets up a webhook config for this URL.", ) @click.option( "--only", default=None, help="Comma separated list. Only echo events with these slugs.", ) @click.option( "--exclude", default=None, help="Comma separated list. Exclude events wi...
url = utils.join_url(webhook_url, "webhooks")
Given snippet: <|code_start|>from __future__ import absolute_import def get_or_create_user(user_identifier): info("Getting user...") <|code_end|> , continue by predicting the next line. Consider current file imports: import click import ricloud from ricloud import conf from ricloud import storage from riclou...
user_identifier = user_identifier or conf.get("samples", "user_identifier")
Here is a snippet: <|code_start|> if is_json and cascade: file_ids = parse_file_ids_from_result_data(download) if limit: file_ids = file_ids[:limit] payload = {"files": file_ids} cascade_poll = create_poll( payload, session=poll[...
storage.download_result(result["url"], to_filename=to_filename)
Using the snippet: <|code_start|> if is_json: result_data[result["identifier"]] = download else: files[result["identifier"]] = download if is_json and cascade: file_ids = parse_file_ids_from_result_data(download) if limit: file_ids...
to_filename = utils.escape(result["identifier"])
Given the following code snippet before the placeholder: <|code_start|> user_identifier = user_identifier or conf.get("samples", "user_identifier") user = ricloud.User.create(identifier=user_identifier) success("User {} retrieved.".format(user.id)) return user def retrieve_session(session_id): in...
warn(
Given snippet: <|code_start|>from __future__ import absolute_import def get_or_create_user(user_identifier): info("Getting user...") user_identifier = user_identifier or conf.get("samples", "user_identifier") user = ricloud.User.create(identifier=user_identifier) <|code_end|> , continue by predictin...
success("User {} retrieved.".format(user.id))
Here is a snippet: <|code_start|>def get_or_create_user(user_identifier): info("Getting user...") user_identifier = user_identifier or conf.get("samples", "user_identifier") user = ricloud.User.create(identifier=user_identifier) success("User {} retrieved.".format(user.id)) return user def retr...
await_response(sub)
Predict the next line after this snippet: <|code_start|> def __repr__(self): return "RequestError(status={s.status}, content='{s.content}')".format(s=self) def __str__(self): return "status:{s.status}, content:{s.content}".format(s=self) class RequestError(RicloudError): """Error response...
format_str += ", params:{params}".format(params=encode_json(self.params))
Based on the snippet: <|code_start|>from __future__ import absolute_import class RicloudError(Exception): def __init__(self, status, content): self.status = status self.content = content def __repr__(self): return "RequestError(status={s.status}, content='{s.content}')".format(s=self...
data = decode_json(content)
Next line prediction: <|code_start|> app = Flask(__name__) @app.route("/webhooks/<uuid:event_id>", methods=["post"]) def webhooks(event_id): if not request.is_json: abort(400) webhook_secret = app.config.get("WEBHOOK_SECRET") webhook_delta = app.config.get("WEBHOOK_DELTA") if webhook_secret ...
signature = Signature.from_header(request.headers["Ricloud-Signature"])
Using the snippet: <|code_start|> return "OK" def verify_request(request, secret, delta=600): signature = Signature.from_header(request.headers["Ricloud-Signature"]) try: signature.verify(request.data, secret, delta=delta) except Signature.SignatureError as exc: print("Event signature...
print("Event received:", encode_json(data, indent=2))
Given the code snippet: <|code_start|>from __future__ import absolute_import class TestHelp(object): def test_ok(self): runner = CliRunner() <|code_end|> , generate the next line using the imports in this file: from click.testing import CliRunner from ricloud.cli import cli and context (functions, cla...
result = runner.invoke(cli, ["--help"])
Given snippet: <|code_start|>from __future__ import absolute_import USER_IDENTIFIER = "testing@reincubate.com" SOURCE_IDENTIFIER = "john.appleseed@reincubate.com" @pytest.mark.integration class TestIntegration(object): def test_ok(self): user = ricloud.User.create(identifier=USER_IDENTIFIER) ...
await_response(session)
Here is a snippet: <|code_start|> if name in self.__dict__: return super(ABResource, self).__delattr__(name) del self.attrs[name] def __eq__(self, other): ignore = ["resource"] attrs_self = {key: value for key, value in self.items() if key not in ignore} attrs_ot...
if isinstance(value, Mapping) and not isinstance(value, ABResource):
Given the code snippet: <|code_start|> class Resource(ABResource): RESOURCE = "" RESOURCE_PATH = "" def __init__(self, *args, **attrs): if args: attrs["id"] = args[0] super(Resource, self).__init__(**attrs) @classmethod def resource_url(cls, resource_path=None): ...
class ABList(MutableSequence, ABResource):
Continue the code snippet: <|code_start|>from __future__ import absolute_import, unicode_literals class ABResource(MutableMapping): request_handler = RequestHandler() def __init__(self, **attrs): attrs = self.parse_attrs(attrs) # Need to setup using object method to avoid circular deps on ...
name=self.__class__.__name__, attrs=pretty_print(self.attrs),
Given the code snippet: <|code_start|> if ABResource._resources is None: ABResource._resources = dict(ABResource.get_resources()) return ABResource._resources.get(resource_type) @classmethod def parse_value(cls, value): if isinstance(value, Mapping) and not isinstance(value, ...
return join_url(ricloud.url, resource_path)
Using the snippet: <|code_start|> class PostgresPartitioningStrategy: """Base class for implementing a partitioning strategy for a partitioned table.""" @abstractmethod def to_create( self, <|code_end|> , determine the next line of code. You have imports: from abc import abstractmethod from ...
) -> Generator[PostgresPartition, None, None]:
Next line prediction: <|code_start|> ) return model def define_fake_materialized_view_model( fields=None, view_options={}, meta_options={}, model_base=PostgresMaterializedViewModel, ): """Defines a fake materialized view model.""" model = define_fake_model( fields=fields, ...
model_base=PostgresPartitionedModel,
Here is a snippet: <|code_start|> } if fields: attributes.update(fields) model = type(name, (model_base,), attributes) apps.app_configs[attributes["app_label"]].models[name] = model return model def define_fake_view_model( fields=None, view_options={}, meta_options={}, model_base=Pos...
model_base=PostgresMaterializedViewModel,
Here is a snippet: <|code_start|> def define_fake_model( fields=None, model_base=PostgresModel, meta_options={}, **attributes ): """Defines a fake model (but does not create it in the database).""" name = str(uuid.uuid4()).replace("-", "")[:8].title() attributes = { "app_label": meta_optio...
fields=None, view_options={}, meta_options={}, model_base=PostgresViewModel
Predict the next line for this snippet: <|code_start|> class PostgresModel(models.Model): """Base class for for taking advantage of PostgreSQL specific features.""" class Meta: abstract = True base_manager_name = "objects" <|code_end|> with the help of current file imports: from django.db ...
objects = PostgresManager()
Predict the next line for this snippet: <|code_start|> class HStoreRequiredSchemaEditorSideEffect: sql_hstore_required_create = ( "ALTER TABLE {table} " "ADD CONSTRAINT {name} " "CHECK (({field}->'{key}') " "IS NOT NULL)" ) sql_hstore_required_rename = ( "ALTER TABL...
if not isinstance(field, HStoreField):
Predict the next line after this snippet: <|code_start|> def test_hstore_unique_migration_create_drop_model(): """Tests whether indexes are properly created and dropped when creating and dropping a model.""" uniqueness = ["beer", "cookies"] test = migrations.create_drop_model( <|code_end|> using ...
HStoreField(uniqueness=uniqueness), ["CREATE UNIQUE", "DROP INDEX"]
Based on the snippet: <|code_start|> together".""" test = migrations.alter_field( HStoreField(uniqueness=[("beer1", "beer2")]), HStoreField(uniqueness=[]), ["CREATE UNIQUE", "DROP INDEX"], ) with test as calls: assert len(calls.get("CREATE UNIQUE", [])) == 0 asse...
model = get_fake_model({"title": HStoreField(uniqueness=["en"])})
Using the snippet: <|code_start|> @pytest.fixture def model(): """Test models, where the first model has a foreign key relationship to the second.""" <|code_end|> , determine the next line of code. You have imports: import django import pytest from django.db import models from psqlextra.fields import HSto...
return get_fake_model({"title": HStoreField()})
Here is a snippet: <|code_start|> @pytest.fixture def model(): """Test models, where the first model has a foreign key relationship to the second.""" <|code_end|> . Write the next line using the current file imports: import django import pytest from django.db import models from psqlextra.fields import HSt...
return get_fake_model({"title": HStoreField()})
Next line prediction: <|code_start|> @pytest.fixture(scope="function", autouse=True) def database_access(db): """Automatically enable database access for all tests.""" # enable the hstore extension on our database because # our tests rely on it... with connection.schema_editor() as schema_editor: ...
with define_fake_app() as fake_app:
Given the following code snippet before the placeholder: <|code_start|> class PostgresCreateMaterializedViewModel(CreateModel): """Creates the model as a native PostgreSQL 11.x materialzed view.""" serialization_expand_args = [ "fields", "options", "managers", "view_options", ...
PostgresMaterializedViewModelState(
Given the code snippet: <|code_start|> ): """Initializes a new instance of :see:PostgresPartitionedModelState. Arguments: partitioning_options: Dictionary of options for partitioning. See: PostgresPartitionedModelMeta for a list. """ supe...
model: PostgresPartitionedModel,
Predict the next line after this snippet: <|code_start|> class PostgresListPartitionState(PostgresPartitionState): """Represents the state of a list partition for a :see:PostgresPartitionedModel during a migration.""" def __init__(self, app_label: str, model_name: str, name: str, values): super()....
class PostgresPartitionedModelState(PostgresModelState):
Using the snippet: <|code_start|> class PostgresCreatePartitionedModel(CreateModel): """Creates the model as a native PostgreSQL 11.x partitioned table.""" serialization_expand_args = [ "fields", "options", "managers", "partitioning_options", ] def __init__( s...
PostgresPartitionedModelState(
Continue the code snippet: <|code_start|> @pytest.mark.parametrize("conflict_action", ConflictAction.all()) def test_on_conflict(conflict_action): """Tests whether simple inserts work correctly.""" model = get_fake_model( { <|code_end|> . Use current file imports: import django import pytest from ...
"title": HStoreField(uniqueness=["key1"]),
Next line prediction: <|code_start|> sql_with_params = cls._view_query_as_sql_with_params( new_class, view_query ) view_meta = PostgresViewOptions(query=sql_with_params) new_class.add_to_class("_view_meta", view_meta) return new_class @staticmethod def _view_...
if not is_query_set(view_query) and not view_query:
Given snippet: <|code_start|> return new_class @staticmethod def _view_query_as_sql_with_params( model: Model, view_query: ViewQuery ) -> Optional[SQLWithParams]: """Gets the query associated with the view as a raw SQL query with bind parameters. The query can be spe...
or is_sql(view_query)
Predict the next line for this snippet: <|code_start|> new_class.add_to_class("_view_meta", view_meta) return new_class @staticmethod def _view_query_as_sql_with_params( model: Model, view_query: ViewQuery ) -> Optional[SQLWithParams]: """Gets the query associated with the vi...
or is_sql_with_params(view_query)
Predict the next line after this snippet: <|code_start|> return None is_valid_view_query = ( is_query_set(view_query) or is_sql_with_params(view_query) or is_sql(view_query) ) if not is_valid_view_query: raise ImproperlyConfigured( ...
class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta):
Based on the snippet: <|code_start|> ViewQueryValue = Union[QuerySet, SQLWithParams, SQL] ViewQuery = Optional[Union[ViewQueryValue, Callable[[], ViewQueryValue]]] class PostgresViewModelMeta(ModelBase): """Custom meta class for :see:PostgresView and :see:PostgresMaterializedView. This meta class extr...
view_meta = PostgresViewOptions(query=sql_with_params)
Given snippet: <|code_start|> def test_hstore_field_deconstruct(): """Tests whether the :see:HStoreField's deconstruct() method works properly.""" original_kwargs = dict(uniqueness=["beer", "other"], required=[]) <|code_end|> , continue by predicting the next line. Consider current file imports: import ...
_, _, _, new_kwargs = HStoreField(**original_kwargs).deconstruct()
Given the code snippet: <|code_start|> ROW_COUNT = 10000 @pytest.mark.benchmark() def test_upsert_bulk_naive(benchmark): model = get_fake_model( {"field": models.CharField(max_length=255, unique=True)} ) rows = [] random_values = [] for i in range(0, ROW_COUNT): random_value =...
model.objects.on_conflict(["field"], ConflictAction.UPDATE).insert(
Given the following code snippet before the placeholder: <|code_start|> ROW_COUNT = 10000 @pytest.mark.benchmark() def test_upsert_bulk_naive(benchmark): <|code_end|> , predict the next line using imports from the current file: import uuid import pytest from django.db import models from psqlextra.query import Co...
model = get_fake_model(
Predict the next line after this snippet: <|code_start|> class HStoreUniqueSchemaEditorSideEffect: sql_hstore_unique_create = ( "CREATE UNIQUE INDEX IF NOT EXISTS " "{name} ON {table} " "({columns})" ) sql_hstore_unique_rename = ( "ALTER INDEX " "{old_name} " "RENAME TO " "{new_name}" ...
if not isinstance(field, HStoreField):
Next line prediction: <|code_start|> class PostgresMaterializedViewModelState(PostgresViewModelState): """Represents the state of a :see:PostgresMaterializedViewModel in the migrations.""" @classmethod <|code_end|> . Use current file imports: (from typing import Type from psqlextra.models import Postgr...
def _get_base_model_class(self) -> Type[PostgresMaterializedViewModel]:
Next line prediction: <|code_start|> def partition_by_current_time( model: PostgresPartitionedModel, count: int, years: Optional[int] = None, months: Optional[int] = None, weeks: Optional[int] = None, days: Optional[int] = None, max_age: Optional[relativedelta] = None, <|code_end|> . Use...
) -> PostgresPartitioningConfig:
Using the snippet: <|code_start|> class PostgresAddListPartition(PostgresPartitionOperation): """Adds a new list partition to a :see:PartitionedPostgresModel.""" def __init__(self, model_name, name, values): """Initializes new instance of :see:AddListPartition. Arguments: model_n...
PostgresListPartitionState(
Here is a snippet: <|code_start|> PartitionList = List[Tuple[PostgresPartitionedModel, List[PostgresPartition]]] class PostgresPartitioningManager: """Helps managing partitions by automatically creating new partitions and deleting old ones according to the configuration.""" <|code_end|> . Write the next l...
def __init__(self, configs: List[PostgresPartitioningConfig]) -> None:
Given snippet: <|code_start|> PartitionList = List[Tuple[PostgresPartitionedModel, List[PostgresPartition]]] class PostgresPartitioningManager: """Helps managing partitions by automatically creating new partitions and deleting old ones according to the configuration.""" def __init__(self, configs: Lis...
) -> PostgresPartitioningPlan:
Given snippet: <|code_start|> parser.add_argument( "app_label", type=str, help="Label of the app the materialized view model is in.", ) parser.add_argument( "model_name", type=str, help="Name of the materialized view model t...
if not issubclass(model, PostgresMaterializedViewModel):
Here is a snippet: <|code_start|> def test_hstore_required_migration_create_drop_model(): """Tests whether constraints are properly created and dropped when creating and dropping a model.""" required = ["beer", "cookies"] test = migrations.create_drop_model( <|code_end|> . Write the next line usin...
HStoreField(required=required), ["ADD CONSTRAINT", "DROP CONSTRAINT"]
Given snippet: <|code_start|> test = migrations.alter_field( HStoreField(required=["beer"]), HStoreField(required=[]), ["ADD CONSTRAINT", "DROP CONSTRAINT"], ) with test as calls: assert len(calls.get("ADD CONSTRAINT", [])) == 0 assert len(calls.get("DROP CONSTRAINT"...
model = get_fake_model({"title": HStoreField(required=["en"])})
Next line prediction: <|code_start|> unit. With monthly partitioning, partitions start on the 1st and with weekly partitioning, partitions start on monday. """ def __init__( self, size: PostgresTimePartitionSize, count: int, max_age: Optional[relativedelta] = None, ) ...
def to_create(self) -> Generator[PostgresTimePartition, None, None]:
Given snippet: <|code_start|> class PostgresCurrentTimePartitioningStrategy( PostgresRangePartitioningStrategy ): """Implments a time based partitioning strategy where each partition contains values for a specific time period. All buckets will be equal in size and start at the start of the unit....
size: PostgresTimePartitionSize,
Next line prediction: <|code_start|> class PostgresPartitionedModelMeta(ModelBase): """Custom meta class for :see:PostgresPartitionedModel. This meta class extracts attributes from the inner `PartitioningMeta` class and copies it onto a `_partitioning_meta` attribute. This is similar to how Django's...
default_method = PostgresPartitioningMethod.RANGE
Given snippet: <|code_start|> class PostgresPartitionedModelMeta(ModelBase): """Custom meta class for :see:PostgresPartitionedModel. This meta class extracts attributes from the inner `PartitioningMeta` class and copies it onto a `_partitioning_meta` attribute. This is similar to how Django's `_meta`...
PostgresModel, metaclass=PostgresPartitionedModelMeta
Predict the next line for this snippet: <|code_start|> class PostgresPartitionedModelMeta(ModelBase): """Custom meta class for :see:PostgresPartitionedModel. This meta class extracts attributes from the inner `PartitioningMeta` class and copies it onto a `_partitioning_meta` attribute. This is simil...
patitioning_meta = PostgresPartitionedModelOptions(
Given snippet: <|code_start|> def test_partitioned_model_abstract(): """Tests whether :see:PostgresPartitionedModel is abstract.""" assert PostgresPartitionedModel._meta.abstract def test_partitioning_model_options_meta(): """Tests whether the `_partitioning_meta` attribute is available on the clas...
assert model._partitioning_meta.method == PostgresPartitioningMethod.RANGE
Based on the snippet: <|code_start|> def test_partitioned_model_abstract(): """Tests whether :see:PostgresPartitionedModel is abstract.""" assert PostgresPartitionedModel._meta.abstract def test_partitioning_model_options_meta(): """Tests whether the `_partitioning_meta` attribute is available on the ...
model = define_fake_partitioned_model()
Next line prediction: <|code_start|> def test_on_conflict_nothing(): """Tests whether simple insert NOTHING works correctly.""" model = get_fake_model( { <|code_end|> . Use current file imports: (import pytest from django.db import models from psqlextra.fields import HStoreField from psqlextra.que...
"title": HStoreField(uniqueness=["key1"]),
Next line prediction: <|code_start|> def test_on_conflict_nothing(): """Tests whether simple insert NOTHING works correctly.""" model = get_fake_model( { "title": HStoreField(uniqueness=["key1"]), "cookies": models.CharField(max_length=255, null=True), } ) #...
[("title", "key1")], ConflictAction.NOTHING
Using the snippet: <|code_start|>class PostgresTimePartition(PostgresRangePartition): """Time-based range table partition. :see:PostgresTimePartitioningStrategy for more info. """ _unit_name_format = { PostgresTimePartitionUnit.YEARS: "%Y", PostgresTimePartitionUnit.MONTHS: "%Y_%b", ...
raise PostgresPartitioningError("Unknown size/unit")
Next line prediction: <|code_start|> class PostgresTimePartition(PostgresRangePartition): """Time-based range table partition. :see:PostgresTimePartitioningStrategy for more info. """ _unit_name_format = { PostgresTimePartitionUnit.YEARS: "%Y", PostgresTimePartitionUnit.MONTHS: "%Y_%...
self, size: PostgresTimePartitionSize, start_datetime: datetime
Predict the next line for this snippet: <|code_start|> class PostgresTimePartition(PostgresRangePartition): """Time-based range table partition. :see:PostgresTimePartitioningStrategy for more info. """ _unit_name_format = { <|code_end|> with the help of current file imports: from datetime import d...
PostgresTimePartitionUnit.YEARS: "%Y",
Using the snippet: <|code_start|> if dry: return if not yes: print("Do you want to proceed? (y/N) ") if not self._ask_for_confirmation(): print("Operation aborted.") return plan.apply(using=using) print("Operations app...
raise PostgresPartitioningError(
Given the code snippet: <|code_start|> class PostgresViewModelState(PostgresModelState): """Represents the state of a :see:PostgresViewModel in the migrations.""" def __init__(self, *args, view_options={}, **kwargs): """Initializes a new instance of :see:PostgresViewModelState. Arguments: ...
cls, model: PostgresViewModel, model_state: "PostgresViewModelState"
Continue the code snippet: <|code_start|> class PostgresPartitioningConfig: """Configuration for partitioning a specific model according to the specified strategy.""" def __init__( self, <|code_end|> . Use current file imports: from psqlextra.models import PostgresPartitionedModel from .strategy...
model: PostgresPartitionedModel,
Continue the code snippet: <|code_start|> class PostgresPartitioningConfig: """Configuration for partitioning a specific model according to the specified strategy.""" def __init__( self, model: PostgresPartitionedModel, <|code_end|> . Use current file imports: from psqlextra.models impor...
strategy: PostgresPartitioningStrategy,
Based on the snippet: <|code_start|> def test_on_conflict_update(): """Tests whether simple upserts works correctly.""" model = get_fake_model( { <|code_end|> , predict the immediate next line with the help of imports: import pytest from django.db import models from psqlextra.fields import HStoreF...
"title": HStoreField(uniqueness=["key1"]),
Based on the snippet: <|code_start|> def test_on_conflict_update(): """Tests whether simple upserts works correctly.""" model = get_fake_model( { "title": HStoreField(uniqueness=["key1"]), "cookies": models.CharField(max_length=255, null=True), } ) obj1 = mo...
[("title", "key1")], ConflictAction.UPDATE
Given the code snippet: <|code_start|> """Tests whether inserts works when the primary key is explicitly specified.""" model = get_fake_model( { "name": models.CharField(max_length=255, primary_key=True), "cookies": models.CharField(max_length=255, null=True), } )...
pk = model.objects.on_conflict([("pk")], ConflictAction.NOTHING).insert(
Given the following code snippet before the placeholder: <|code_start|> random_value = str(uuid.uuid4())[:8] model.objects.create(field=random_value) def _traditional_insert(model, random_value): """Performs a concurrency safe insert the traditional way.""" try: with transactio...
["field"], ConflictAction.NOTHING
Next line prediction: <|code_start|> def test_manager_context(): """Tests whether the :see:postgres_manager context manager can be used to get access to :see:PostgresManager on a model that does not use it directly or inherits from :see:PostgresModel.""" model = get_fake_model( {"myfield": m...
with postgres_manager(model) as manager:
Given snippet: <|code_start|> def test_manager_context(): """Tests whether the :see:postgres_manager context manager can be used to get access to :see:PostgresManager on a model that does not use it directly or inherits from :see:PostgresModel.""" <|code_end|> , continue by predicting the next line. Con...
model = get_fake_model(
Given the code snippet: <|code_start|> @pytest.mark.parametrize( "model_base", [PostgresViewModel, PostgresMaterializedViewModel] ) def test_view_model_meta_query_set(model_base): """Tests whether you can set a :see:QuerySet to be used as the underlying query for a view.""" <|code_end|> , generate the ...
model = define_fake_model({"name": models.TextField()})
Using the snippet: <|code_start|> @pytest.mark.parametrize( "model_base", [PostgresViewModel, PostgresMaterializedViewModel] ) def test_view_model_meta_query_set(model_base): """Tests whether you can set a :see:QuerySet to be used as the underlying query for a view.""" model = define_fake_model({"n...
view_model = define_fake_view_model(
Next line prediction: <|code_start|> class PostgresTimePartitionUnit(enum.Enum): YEARS = "years" MONTHS = "months" WEEKS = "weeks" DAYS = "days" class PostgresTimePartitionSize: """Size of a time-based range partition table.""" unit: PostgresTimePartitionUnit value: int def __ini...
raise PostgresPartitioningError("Partition cannot be 0 in size.")
Here is a snippet: <|code_start|> class PostgresCreateViewModel(CreateModel): """Creates the model as a native PostgreSQL 11.x view.""" serialization_expand_args = [ "fields", "options", "managers", "view_options", ] def __init__( self, name, f...
PostgresViewModelState(
Here is a snippet: <|code_start|> def test_unique_index_migrations(): index = UniqueIndex(fields=["name", "other_name"], name="index1") ops = [ CreateModel( name="mymodel", fields=[ ("name", models.TextField()), ("other_name", models.TextField(...
apply_migration(ops)
Here is a snippet: <|code_start|> def test_unique_index_migrations(): index = UniqueIndex(fields=["name", "other_name"], name="index1") ops = [ CreateModel( name="mymodel", fields=[ ("name", models.TextField()), ("other_name", models.TextField(...
with filtered_schema_editor("CREATE UNIQUE INDEX") as calls:
Predict the next line after this snippet: <|code_start|> def _assert_autodetector(changes, expected): """Asserts whether the results of the auto detector are as expected.""" assert "tests" in changes assert len("tests") > 0 operations = changes["tests"][0].operations for i, expected_operation in...
"tests", "Model1", [("title", HStoreField())]
Predict the next line after this snippet: <|code_start|> class PostgresPartitionedModelOptions: """Container for :see:PostgresPartitionedModel options. This is where attributes copied from the model's `PartitioningMeta` are held. """ <|code_end|> using the current file's imports: from typing impor...
def __init__(self, method: PostgresPartitioningMethod, key: List[str]):
Next line prediction: <|code_start|> class PostgresPartitionedModelOptions: """Container for :see:PostgresPartitionedModel options. This is where attributes copied from the model's `PartitioningMeta` are held. """ def __init__(self, method: PostgresPartitioningMethod, key: List[str]): se...
def __init__(self, query: Optional[SQLWithParams]):
Continue the code snippet: <|code_start|> @contextmanager def postgres_patched_migrations(): """Patches migration related classes/functions to extend how Django generates and applies migrations. This adds support for automatically detecting changes in Postgres specific models. """ with patch...
with patched_autodetector():
Next line prediction: <|code_start|> @contextmanager def postgres_patched_migrations(): """Patches migration related classes/functions to extend how Django generates and applies migrations. This adds support for automatically detecting changes in Postgres specific models. """ <|code_end|> . Use ...
with patched_project_state():
Given the following code snippet before the placeholder: <|code_start|> @dataclass class PostgresModelPartitioningPlan: """Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model. """ <|code_end|> , predict the...
config: PostgresPartitioningConfig