Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Next line prediction: <|code_start|>// Set socket options void zsocket_set_ipv6 (void *zocket, int ipv6); void zsocket_set_immediate (void *zocket, int immediate); void zsocket_set_router_raw (void *zocket, int router_raw); void zsocket_set_ipv4only (void *zocket, int ipv4only); void zsocket_set_delay_attach_on_connect (void *zocket, int delay_attach_on_connect); void zsocket_set_router_mandatory (void *zocket, int router_mandatory); void zsocket_set_probe_router (void *zocket, int probe_router); void zsocket_set_req_relaxed (void *zocket, int req_relaxed); void zsocket_set_req_correlate (void *zocket, int req_correlate); void zsocket_set_conflate (void *zocket, int conflate); void zsocket_set_plain_server (void *zocket, int plain_server); void zsocket_set_plain_username (void *zocket, const char * plain_username); void zsocket_set_plain_password (void *zocket, const char * plain_password); void zsocket_set_curve_server (void *zocket, int curve_server); void zsocket_set_curve_publickey (void *zocket, const char * curve_publickey); void zsocket_set_curve_publickey_bin (void *zocket, const char *curve_publickey); void zsocket_set_curve_secretkey (void *zocket, const char * curve_secretkey); void zsocket_set_curve_secretkey_bin (void *zocket, const char *curve_secretkey); void zsocket_set_curve_serverkey (void *zocket, const char * curve_serverkey); void zsocket_set_curve_serverkey_bin (void *zocket, const char *curve_serverkey); void zsocket_set_zap_domain (void *zocket, const char * zap_domain); void zsocket_set_sndhwm (void *zocket, int sndhwm); void zsocket_set_rcvhwm (void *zocket, int rcvhwm); void zsocket_set_affinity (void *zocket, int affinity); void zsocket_set_subscribe (void *zocket, const char * subscribe); void zsocket_set_unsubscribe (void *zocket, const char * unsubscribe); void zsocket_set_identity (void *zocket, const char * identity); void zsocket_set_rate (void *zocket, int rate); void zsocket_set_recovery_ivl (void *zocket, int recovery_ivl); <|code_end|> . Use current file imports: (from pyczmq._cffi import C, ffi, cdef) and context including class names, function names, or small code snippets from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
void zsocket_set_sndbuf (void *zocket, int sndbuf);
Based on the snippet: <|code_start|> __doc__ = """ The zpoller class provides a minimalist interface to ZeroMQ's zmq_poll API, for the very common case of reading from a number of sockets. It does not provide polling for output, nor polling on file handles. If <|code_end|> , predict the immediate next line with the help of imports: from pyczmq._cffi import C, ffi, cdef, ptop and context (classes, functions, sometimes code) from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
you need either of these, use the zmq_poll API directly.
Given snippet: <|code_start|> __doc__ = """ The zmsg class provides methods to send and receive multipart messages across 0MQ sockets. This class provides a list-like container <|code_end|> , continue by predicting the next line. Consider current file imports: from pyczmq._cffi import C, ptop, cdef and context: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # # def ptop(typ, val): # ptop = ffi.new('%s*[1]' % typ) # ptop[0] = val # return ptop # # def cdef(decl, returns_string=False, nullable=False): # ffi.cdef(decl) # def wrap(f): # @wraps(f) # def inner_f(*args): # val = f(*args) # # if Z.zmq_errno(): # # raise Exception(os.strerror(Z.zmq_errno())) # if nullable and val == ffi.NULL: # return None # elif returns_string: # return ffi.string(val) # return val # # # this insanity inserts a formatted argspec string # # into the function's docstring, so that sphinx # # gets the right args instead of just the wrapper args # # # # Backward compatability with Python2.6 necessitates the use # # of indicies within the .format {} braces. # # # args, varargs, varkw, defaults = inspect.getargspec(f) # defaults = () if defaults is None else defaults # defaults = ["\"{0}\"".format(a) if type(a) == str else a for a in defaults] # l = ["{0}={1}".format(arg, defaults[(idx+1)*-1]) # if len(defaults)-1 >= idx else # arg for idx, arg in enumerate(reversed(list(args)))] # if varargs: # l.append('*' + varargs) # if varkw: # l.append('**' + varkw) # doc = "{0}({1})\n\nC: ``{2}``\n\n{3}".format(f.__name__, ', '.join(reversed(l)), decl, f.__doc__) # inner_f.__doc__ = doc # return inner_f # return wrap which might include code, classes, or functions. Output only the next line.
interface, with methods to work with the overall container. zmsg_t
Based on the snippet: <|code_start|> __doc__ = """ The zctx class wraps 0MQ contexts. It manages open sockets in the context and automatically closes these before terminating the context. It provides a simple way to set the linger timeout on sockets, and configure contexts for number of I/O threads. Sets-up signal (interrupt) handling for the process. The zctx class has these main features: - Tracks all open sockets and automatically closes them before calling zmq_term(). This avoids an infinite wait on open sockets. - Automatically configures sockets with a ZMQ_LINGER timeout you can define, and which defaults to zero. The default behavior of zctx is therefore like 0MQ/2.0, immediate termination with loss of any pending messages. You can set any linger timeout you like by calling the zctx_set_linger() method. - Moves the iothreads configuration to a separate method, so that default usage is 1 I/O thread. Lets you configure this value. Sets up signal (SIGINT and SIGTERM) handling so that blocking <|code_end|> , predict the immediate next line with the help of imports: from pyczmq._cffi import C, ffi, cdef, ptop and context (classes, functions, sometimes code) from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
calls such as zmq_recv() and zmq_poll() will return when the user
Using the snippet: <|code_start|> __doc__ = """ The zctx class wraps 0MQ contexts. It manages open sockets in the context and automatically closes these before terminating the context. It provides a simple way to set the linger timeout on <|code_end|> , determine the next line of code. You have imports: from pyczmq._cffi import C, ffi, cdef, ptop and context (class names, function names, or code) available: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
sockets, and configure contexts for number of I/O threads. Sets-up
Using the snippet: <|code_start|> __doc__ = """ The zctx class wraps 0MQ contexts. It manages open sockets in the context and automatically closes these before terminating the context. It provides a simple way to set the linger timeout on sockets, and configure contexts for number of I/O threads. Sets-up signal (interrupt) handling for the process. The zctx class has these main features: - Tracks all open sockets and automatically closes them before calling zmq_term(). This avoids an infinite wait on open sockets. - Automatically configures sockets with a ZMQ_LINGER timeout you can define, and which defaults to zero. The default behavior of zctx <|code_end|> , determine the next line of code. You have imports: from pyczmq._cffi import C, ffi, cdef, ptop and context (class names, function names, or code) available: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
is therefore like 0MQ/2.0, immediate termination with loss of any
Given the following code snippet before the placeholder: <|code_start|> __doc__ = """ The zctx class wraps 0MQ contexts. It manages open sockets in the context and automatically closes these before terminating the context. It provides a simple way to set the linger timeout on sockets, and configure contexts for number of I/O threads. Sets-up signal (interrupt) handling for the process. The zctx class has these main features: - Tracks all open sockets and automatically closes them before calling zmq_term(). This avoids an infinite wait on open sockets. - Automatically configures sockets with a ZMQ_LINGER timeout you can define, and which defaults to zero. The default behavior of zctx is therefore like 0MQ/2.0, immediate termination with loss of any pending messages. You can set any linger timeout you like by calling the zctx_set_linger() method. - Moves the iothreads configuration to a separate method, so that <|code_end|> , predict the next line using imports from the current file: from pyczmq._cffi import C, ffi, cdef, ptop and context including class names, function names, and sometimes code from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
default usage is 1 I/O thread. Lets you configure this value.
Here is a snippet: <|code_start|> __doc__ = """ The zbeacon class implements a peer-to-peer discovery service for local networks. A beacon can broadcast and/or capture service announcements using UDP messages on the local area network. This implementation uses IPv4 UDP broadcasts. You can define the format of your outgoing beacons, and set a filter that validates incoming beacons. Beacons are sent and received asynchronously in the background. The zbeacon API provides a incoming beacons on a ZeroMQ socket (the pipe) that you can configure, poll on, and receive <|code_end|> . Write the next line using the current file imports: from pyczmq._cffi import C, ffi, ptop, cdef and context from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): , which may include functions, classes, or code. Output only the next line.
messages on. Incoming beacons are always delivered as two frames: the
Given the following code snippet before the placeholder: <|code_start|> __doc__ = """ The zbeacon class implements a peer-to-peer discovery service for local networks. A beacon can broadcast and/or capture service announcements using UDP messages on the local area network. This <|code_end|> , predict the next line using imports from the current file: from pyczmq._cffi import C, ffi, ptop, cdef and context including class names, function names, and sometimes code from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
implementation uses IPv4 UDP broadcasts. You can define the format of
Here is a snippet: <|code_start|> __doc__ = """ The zbeacon class implements a peer-to-peer discovery service for local networks. A beacon can broadcast and/or capture service announcements using UDP messages on the local area network. This implementation uses IPv4 UDP broadcasts. You can define the format of your outgoing beacons, and set a filter that validates incoming beacons. Beacons are sent and received asynchronously in the background. The zbeacon API provides a incoming beacons on a ZeroMQ socket (the pipe) that you can configure, poll on, and receive <|code_end|> . Write the next line using the current file imports: from pyczmq._cffi import C, ffi, ptop, cdef and context from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): , which may include functions, classes, or code. Output only the next line.
messages on. Incoming beacons are always delivered as two frames: the
Given the following code snippet before the placeholder: <|code_start|> CURVE_ALLOW_ANY = "*" cdef('typedef struct _zauth_t zauth_t;') @cdef('void zauth_destroy (zauth_t **self_p);') <|code_end|> , predict the next line using imports from the current file: from pyczmq._cffi import C, ffi, cdef, ptop and context including class names, function names, and sometimes code from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
def destroy(auth):
Given the following code snippet before the placeholder: <|code_start|> __doc__ = """ The zstr class provides utility functions for sending and receiving strings across 0MQ sockets. It sends strings without a terminating null, and appends a null byte on received strings. This class is for <|code_end|> , predict the next line using imports from the current file: from pyczmq._cffi import C, ffi, cdef and context including class names, function names, and sometimes code from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
simple message sending.
Predict the next line for this snippet: <|code_start|>UNSUBSCRIBE = 7 RATE = 8 RECOVERY_IVL = 9 SNDBUF = 11 RCVBUF = 12 RCVMORE = 13 FD = 14 EVENTS = 15 TYPE = 16 LINGER = 17 RECONNECT_IVL = 18 BACKLOG = 19 RECONNECT_IVL_MAX = 21 MAXMSGSIZE = 22 SNDHWM = 23 RCVHWM = 24 MULTICAST_HOPS = 25 RCVTIMEO = 27 SNDTIMEO = 28 LAST_ENDPOINT = 32 ROUTER_MANDATORY = 33 TCP_KEEPALIVE = 34 TCP_KEEPALIVE_CNT = 35 TCP_KEEPALIVE_IDLE = 36 TCP_KEEPALIVE_INTVL = 37 TCP_ACCEPT_FILTER = 38 IMMEDIATE = 39 XPUB_VERBOSE = 40 ROUTER_RAW = 41 IPV6 = 42 <|code_end|> with the help of current file imports: from pyczmq._cffi import ffi, Z, cdef and context from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): , which may contain function names, class names, or code. Output only the next line.
MECHANISM = 43
Next line prediction: <|code_start|> IO_THREADS = 1 MAX_SOCKETS = 2 IO_THREADS_DFLT = 1 MAX_SOCKETS_DFLT = 1024 POLLIN = 1 POLLOUT = 2 POLLERR = 4 EVENT_CONNECTED = 1 EVENT_CONNECT_DELAYED = 2 EVENT_CONNECT_RETRIED = 4 EVENT_LISTENING = 8 EVENT_BIND_FAILED = 16 EVENT_ACCEPTED = 32 EVENT_ACCEPT_FAILED = 64 <|code_end|> . Use current file imports: (from pyczmq._cffi import ffi, Z, cdef) and context including class names, function names, or small code snippets from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
EVENT_CLOSED = 128
Continue the code snippet: <|code_start|> IO_THREADS = 1 MAX_SOCKETS = 2 IO_THREADS_DFLT = 1 MAX_SOCKETS_DFLT = 1024 POLLIN = 1 POLLOUT = 2 POLLERR = 4 EVENT_CONNECTED = 1 EVENT_CONNECT_DELAYED = 2 EVENT_CONNECT_RETRIED = 4 EVENT_LISTENING = 8 EVENT_BIND_FAILED = 16 EVENT_ACCEPTED = 32 EVENT_ACCEPT_FAILED = 64 EVENT_CLOSED = 128 <|code_end|> . Use current file imports: from pyczmq._cffi import ffi, Z, cdef and context (classes, functions, or code) from other files: # Path: pyczmq/_cffi.py # C = ffi.dlopen('czmq') # Z = ffi.dlopen('zmq') # def ptop(typ, val): # def cdef(decl, returns_string=False, nullable=False): # def wrap(f): # def inner_f(*args): . Output only the next line.
EVENT_CLOSE_FAILED = 256
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-recommendations-ai", ).version, ) except pkg_resources.DistributionNotFound: <|code_end|> . Use current file imports: (import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api import httpbody_pb2 # type: ignore from google.cloud.recommendationengine_v1beta1.types import import_ from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.cloud.recommendationengine_v1beta1.types import user_event_service from google.longrunning import operations_pb2 # type: ignore) and context including class names, function names, or small code snippets from other files: # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/user_event_service.py # class PurgeUserEventsRequest(proto.Message): # class PurgeUserEventsMetadata(proto.Message): # class PurgeUserEventsResponse(proto.Message): # class WriteUserEventRequest(proto.Message): # class CollectUserEventRequest(proto.Message): # class ListUserEventsRequest(proto.Message): # class ListUserEventsResponse(proto.Message): # def raw_page(self): . Output only the next line.
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-recommendations-ai", ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() <|code_end|> . Use current file imports: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api import httpbody_pb2 # type: ignore from google.cloud.recommendationengine_v1beta1.types import import_ from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.cloud.recommendationengine_v1beta1.types import user_event_service from google.longrunning import operations_pb2 # type: ignore and context (classes, functions, or code) from other files: # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/user_event_service.py # class PurgeUserEventsRequest(proto.Message): # class PurgeUserEventsMetadata(proto.Message): # class PurgeUserEventsResponse(proto.Message): # class WriteUserEventRequest(proto.Message): # class CollectUserEventRequest(proto.Message): # class ListUserEventsRequest(proto.Message): # class ListUserEventsResponse(proto.Message): # def raw_page(self): . Output only the next line.
class UserEventServiceTransport(abc.ABC):
Continue the code snippet: <|code_start|> class PurgeUserEventsRequest(proto.Message): r"""Request message for PurgeUserEvents method. Attributes: parent (str): Required. The resource name of the event_store under which the events are created. The format is ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` filter (str): Required. The filter string to specify the events to be deleted. Empty string filter is not allowed. This filter can also be used with ListUserEvents API to list events that will be deleted. The eligible fields for filtering are: - eventType - UserEvent.eventType field of type string. - eventTime - in ISO 8601 "zulu" format. - visitorId - field of type string. Specifying this will delete all events associated with a visitor. - userId - field of type string. Specifying this will delete all events associated with a user. Example 1: Deleting all events in a time range. ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` Example 2: Deleting specific eventType in time range. ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` Example 3: Deleting all events for a specific visitor ``visitorId = visitor1024`` The filtering fields are assumed to have an implicit AND. force (bool): Optional. The default value is false. <|code_end|> . Use current file imports: import proto # type: ignore from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.protobuf import timestamp_pb2 # type: ignore and context (classes, functions, or code) from other files: # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 . Output only the next line.
Override this flag to true to actually perform
Given the code snippet: <|code_start|> api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): <|code_end|> , generate the next line using the imports in this file: import os import mock import grpc import math import pytest import google.auth from grpc.experimental import aio from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceAsyncClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( transports, ) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import prediction_service from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.oauth2 import service_account from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore and context (functions, classes, or occasionally code) from other files: # Path: google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py # class PredictPager: # class PredictAsyncPager: # def __init__( # self, # method: Callable[..., prediction_service.PredictResponse], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # def pages(self) -> Iterator[prediction_service.PredictResponse]: # def __iter__(self) -> Iterator[prediction_service.PredictResponse.PredictionResult]: # def __repr__(self) -> str: # def __init__( # self, # method: Callable[..., Awaitable[prediction_service.PredictResponse]], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # async def pages(self) -> AsyncIterator[prediction_service.PredictResponse]: # def __aiter__( # self, # ) -> AsyncIterator[prediction_service.PredictResponse.PredictionResult]: # async def async_generator(): # def __repr__(self) -> str: # # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/prediction_service.py # class PredictRequest(proto.Message): # class PredictResponse(proto.Message): # class PredictionResult(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 . Output only the next line.
(
Here is a snippet: <|code_start|> with mock.patch.object(type(client.transport.predict), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( prediction_service.PredictResponse( results=[ prediction_service.PredictResponse.PredictionResult(), prediction_service.PredictResponse.PredictionResult(), prediction_service.PredictResponse.PredictionResult(), ], next_page_token="abc", ), prediction_service.PredictResponse(results=[], next_page_token="def",), prediction_service.PredictResponse( results=[prediction_service.PredictResponse.PredictionResult(),], next_page_token="ghi", ), prediction_service.PredictResponse( results=[ prediction_service.PredictResponse.PredictionResult(), prediction_service.PredictResponse.PredictionResult(), ], ), RuntimeError, ) pages = list(client.predict(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio <|code_end|> . Write the next line using the current file imports: import os import mock import grpc import math import pytest import google.auth from grpc.experimental import aio from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceAsyncClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( transports, ) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import prediction_service from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.oauth2 import service_account from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore and context from other files: # Path: google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py # class PredictPager: # class PredictAsyncPager: # def __init__( # self, # method: Callable[..., prediction_service.PredictResponse], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # def pages(self) -> Iterator[prediction_service.PredictResponse]: # def __iter__(self) -> Iterator[prediction_service.PredictResponse.PredictionResult]: # def __repr__(self) -> str: # def __init__( # self, # method: Callable[..., Awaitable[prediction_service.PredictResponse]], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # async def pages(self) -> AsyncIterator[prediction_service.PredictResponse]: # def __aiter__( # self, # ) -> AsyncIterator[prediction_service.PredictResponse.PredictionResult]: # async def async_generator(): # def __repr__(self) -> str: # # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/prediction_service.py # class PredictRequest(proto.Message): # class PredictResponse(proto.Message): # class PredictionResult(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 , which may include functions, classes, or code. Output only the next line.
async def test_predict_async_pager():
Here is a snippet: <|code_start|> grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, host="squid.clam.whelk", scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,grpc_helpers", [ ( PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc", grpc_helpers, ), ( PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async, ), ], ) def test_prediction_service_client_create_channel_credentials_file( <|code_end|> . Write the next line using the current file imports: import os import mock import grpc import math import pytest import google.auth from grpc.experimental import aio from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceAsyncClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( transports, ) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import prediction_service from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.oauth2 import service_account from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore and context from other files: # Path: google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py # class PredictPager: # class PredictAsyncPager: # def __init__( # self, # method: Callable[..., prediction_service.PredictResponse], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # def pages(self) -> Iterator[prediction_service.PredictResponse]: # def __iter__(self) -> Iterator[prediction_service.PredictResponse.PredictionResult]: # def __repr__(self) -> str: # def __init__( # self, # method: Callable[..., Awaitable[prediction_service.PredictResponse]], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # async def pages(self) -> AsyncIterator[prediction_service.PredictResponse]: # def __aiter__( # self, # ) -> AsyncIterator[prediction_service.PredictResponse.PredictionResult]: # async def async_generator(): # def __repr__(self) -> str: # # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/prediction_service.py # class PredictRequest(proto.Message): # class PredictResponse(proto.Message): # class PredictionResult(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 , which may include functions, classes, or code. Output only the next line.
client_class, transport_class, transport_name, grpc_helpers
Here is a snippet: <|code_start|>def test_prediction_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): with mock.patch.object( transport_class, "create_channel" ) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel mock_cred = mock.Mock() with pytest.warns(DeprecationWarning): transport = transport_class( host="squid.clam.whelk", credentials=mock_cred, api_mtls_endpoint="mtls.squid.clam.whelk", client_cert_source=None, ) grpc_create_channel.assert_called_once_with( "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ <|code_end|> . Write the next line using the current file imports: import os import mock import grpc import math import pytest import google.auth from grpc.experimental import aio from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceAsyncClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceClient, ) from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( transports, ) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import prediction_service from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.oauth2 import service_account from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore and context from other files: # Path: google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py # class PredictPager: # class PredictAsyncPager: # def __init__( # self, # method: Callable[..., prediction_service.PredictResponse], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # def pages(self) -> Iterator[prediction_service.PredictResponse]: # def __iter__(self) -> Iterator[prediction_service.PredictResponse.PredictionResult]: # def __repr__(self) -> str: # def __init__( # self, # method: Callable[..., Awaitable[prediction_service.PredictResponse]], # request: prediction_service.PredictRequest, # response: prediction_service.PredictResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # async def pages(self) -> AsyncIterator[prediction_service.PredictResponse]: # def __aiter__( # self, # ) -> AsyncIterator[prediction_service.PredictResponse.PredictionResult]: # async def async_generator(): # def __repr__(self) -> str: # # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/prediction_service.py # class PredictRequest(proto.Message): # class PredictResponse(proto.Message): # class PredictionResult(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 , which may include functions, classes, or code. Output only the next line.
("grpc.max_send_message_length", -1),
Using the snippet: <|code_start|>__protobuf__ = proto.module( package="google.cloud.recommendationengine.v1beta1", manifest={ "GcsSource", "CatalogInlineSource", "UserEventInlineSource", "ImportErrorsConfig", "ImportCatalogItemsRequest", "ImportUserEventsRequest", "InputConfig", "ImportMetadata", "ImportCatalogItemsResponse", "ImportUserEventsResponse", "UserEventImportSummary", }, ) class GcsSource(proto.Message): r"""Google Cloud Storage location for input content. format. Attributes: input_uris (Sequence[str]): Required. Google Cloud Storage URIs to input files. URI can be up to 2000 characters long. URIs can match the full object path (for example, ``gs://bucket/directory/object.json``) or a pattern matching one or more files, such as ````gs://bucket/directory/*.json````. A request can contain at most 100 files, and each file can <|code_end|> , determine the next line of code. You have imports: import proto # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import user_event from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore and context (class names, function names, or code) available: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 . Output only the next line.
be up to 2 GB. See `Importing catalog
Continue the code snippet: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __protobuf__ = proto.module( package="google.cloud.recommendationengine.v1beta1", manifest={ "GcsSource", "CatalogInlineSource", "UserEventInlineSource", "ImportErrorsConfig", "ImportCatalogItemsRequest", "ImportUserEventsRequest", "InputConfig", "ImportMetadata", "ImportCatalogItemsResponse", "ImportUserEventsResponse", "UserEventImportSummary", }, ) class GcsSource(proto.Message): r"""Google Cloud Storage location for input content. format. Attributes: <|code_end|> . Use current file imports: import proto # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import user_event from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore and context (classes, functions, or code) from other files: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 . Output only the next line.
input_uris (Sequence[str]):
Predict the next line for this snippet: <|code_start|> __protobuf__ = proto.module( package="google.cloud.recommendationengine.v1beta1", manifest={"CatalogItem", "ProductCatalogItem", "Image",}, ) class CatalogItem(proto.Message): r"""CatalogItem captures all metadata information of items to be recommended. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: id (str): Required. Catalog item identifier. UTF-8 encoded string with a length limit of 128 bytes. This id must be unique among all catalog items within the same catalog. It should also be used when logging user events in order for the user events to be joined with the Catalog. category_hierarchies (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem.CategoryHierarchy]): Required. Catalog item categories. This field is repeated for supporting one catalog item belonging to several parallel category hierarchies. For example, if a shoes product belongs to both ["Shoes & <|code_end|> with the help of current file imports: import proto # type: ignore from google.cloud.recommendationengine_v1beta1.types import common and context from other files: # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): , which may contain function names, class names, or code. Output only the next line.
Accessories" -> "Shoes"] and ["Sports & Fitness" ->
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( <|code_end|> . Use current file imports: (import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.recommendationengine_v1beta1.types import prediction_service) and context including class names, function names, or small code snippets from other files: # Path: google/cloud/recommendationengine_v1beta1/types/prediction_service.py # class PredictRequest(proto.Message): # class PredictResponse(proto.Message): # class PredictionResult(proto.Message): # def raw_page(self): . Output only the next line.
"google-cloud-recommendations-ai",
Given snippet: <|code_start|> event_type = proto.Field(proto.STRING, number=1,) user_info = proto.Field(proto.MESSAGE, number=2, message="UserInfo",) event_detail = proto.Field(proto.MESSAGE, number=3, message="EventDetail",) product_event_detail = proto.Field( proto.MESSAGE, number=4, message="ProductEventDetail", ) event_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) event_source = proto.Field(proto.ENUM, number=6, enum=EventSource,) class UserInfo(proto.Message): r"""Information of end users. Attributes: visitor_id (str): Required. A unique identifier for tracking visitors with a length limit of 128 bytes. For example, this could be implemented with a http cookie, which should be able to uniquely identify a visitor on a single device. This unique identifier should not change if the visitor log in/out of the website. Maximum length 128 bytes. Cannot be empty. user_id (str): Optional. Unique identifier for logged-in user with a length limit of 128 bytes. Required only for logged-in users. ip_address (str): Optional. IP address of the user. This could be either IPv4 <|code_end|> , continue by predicting the next line. Consider current file imports: import proto # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import common from google.protobuf import timestamp_pb2 # type: ignore and context: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): which might include code, classes, or functions. Output only the next line.
(e.g. 104.133.9.80) or IPv6 (e.g.
Based on the snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __protobuf__ = proto.module( package="google.cloud.recommendationengine.v1beta1", manifest={ "UserEvent", "UserInfo", "EventDetail", "ProductEventDetail", "PurchaseTransaction", "ProductDetail", }, ) class UserEvent(proto.Message): r"""UserEvent captures all metadata information recommendation engine needs to know about how end users interact with customers' website. Attributes: <|code_end|> , predict the immediate next line with the help of imports: import proto # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import common from google.protobuf import timestamp_pb2 # type: ignore and context (classes, functions, sometimes code) from other files: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): . Output only the next line.
event_type (str):
Continue the code snippet: <|code_start|> expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format( project=project, location=location, catalog=catalog, ) actual = CatalogServiceClient.catalog_path(project, location, catalog) assert expected == actual def test_parse_catalog_path(): expected = { "project": "octopus", "location": "oyster", "catalog": "nudibranch", } path = CatalogServiceClient.catalog_path(**expected) # Check that the path construction is reversible. actual = CatalogServiceClient.parse_catalog_path(path) assert expected == actual def test_common_billing_account_path(): billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) actual = CatalogServiceClient.common_billing_account_path(billing_account) assert expected == actual def test_parse_common_billing_account_path(): <|code_end|> . Use current file imports: import os import mock import grpc import math import pytest import google.auth from grpc.experimental import aio from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceAsyncClient, ) from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceClient, ) from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( transports, ) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import catalog_service from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import import_ from google.cloud.recommendationengine_v1beta1.types import user_event from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore and context (classes, functions, or code) from other files: # Path: google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py # class ListCatalogItemsPager: # class ListCatalogItemsAsyncPager: # def __init__( # self, # method: Callable[..., catalog_service.ListCatalogItemsResponse], # request: catalog_service.ListCatalogItemsRequest, # response: catalog_service.ListCatalogItemsResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # def pages(self) -> Iterator[catalog_service.ListCatalogItemsResponse]: # def __iter__(self) -> Iterator[catalog.CatalogItem]: # def __repr__(self) -> str: # def __init__( # self, # method: Callable[..., Awaitable[catalog_service.ListCatalogItemsResponse]], # request: catalog_service.ListCatalogItemsRequest, # response: catalog_service.ListCatalogItemsResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # async def pages(self) -> AsyncIterator[catalog_service.ListCatalogItemsResponse]: # def __aiter__(self) -> AsyncIterator[catalog.CatalogItem]: # async def async_generator(): # def __repr__(self) -> str: # # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/catalog_service.py # class CreateCatalogItemRequest(proto.Message): # class GetCatalogItemRequest(proto.Message): # class ListCatalogItemsRequest(proto.Message): # class ListCatalogItemsResponse(proto.Message): # class UpdateCatalogItemRequest(proto.Message): # class DeleteCatalogItemRequest(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 . Output only the next line.
expected = {
Here is a snippet: <|code_start|> type(client.transport.delete_catalog_item), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_catalog_item(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio async def test_delete_catalog_item_flattened_error_async(): client = CatalogServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.delete_catalog_item( catalog_service.DeleteCatalogItemRequest(), name="name_value", <|code_end|> . Write the next line using the current file imports: import os import mock import grpc import math import pytest import google.auth from grpc.experimental import aio from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceAsyncClient, ) from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceClient, ) from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( transports, ) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import catalog_service from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import import_ from google.cloud.recommendationengine_v1beta1.types import user_event from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore and context from other files: # Path: google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py # class ListCatalogItemsPager: # class ListCatalogItemsAsyncPager: # def __init__( # self, # method: Callable[..., catalog_service.ListCatalogItemsResponse], # request: catalog_service.ListCatalogItemsRequest, # response: catalog_service.ListCatalogItemsResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # def pages(self) -> Iterator[catalog_service.ListCatalogItemsResponse]: # def __iter__(self) -> Iterator[catalog.CatalogItem]: # def __repr__(self) -> str: # def __init__( # self, # method: Callable[..., Awaitable[catalog_service.ListCatalogItemsResponse]], # request: catalog_service.ListCatalogItemsRequest, # response: catalog_service.ListCatalogItemsResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # async def pages(self) -> AsyncIterator[catalog_service.ListCatalogItemsResponse]: # def __aiter__(self) -> AsyncIterator[catalog.CatalogItem]: # async def async_generator(): # def __repr__(self) -> str: # # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/catalog_service.py # class CreateCatalogItemRequest(proto.Message): # class GetCatalogItemRequest(proto.Message): # class ListCatalogItemsRequest(proto.Message): # class ListCatalogItemsResponse(proto.Message): # class UpdateCatalogItemRequest(proto.Message): # class DeleteCatalogItemRequest(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 , which may include functions, classes, or code. Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|> with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): with mock.patch.object( transport_class, "create_channel" ) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel mock_cred = mock.Mock() with pytest.warns(DeprecationWarning): transport = transport_class( host="squid.clam.whelk", credentials=mock_cred, api_mtls_endpoint="mtls.squid.clam.whelk", client_cert_source=None, ) grpc_create_channel.assert_called_once_with( "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), <|code_end|> , predict the next line using imports from the current file: import os import mock import grpc import math import pytest import google.auth from grpc.experimental import aio from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceAsyncClient, ) from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceClient, ) from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( transports, ) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import catalog_service from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import import_ from google.cloud.recommendationengine_v1beta1.types import user_event from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore and context including class names, function names, and sometimes code from other files: # Path: google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py # class ListCatalogItemsPager: # class ListCatalogItemsAsyncPager: # def __init__( # self, # method: Callable[..., catalog_service.ListCatalogItemsResponse], # request: catalog_service.ListCatalogItemsRequest, # response: catalog_service.ListCatalogItemsResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # def pages(self) -> Iterator[catalog_service.ListCatalogItemsResponse]: # def __iter__(self) -> Iterator[catalog.CatalogItem]: # def __repr__(self) -> str: # def __init__( # self, # method: Callable[..., Awaitable[catalog_service.ListCatalogItemsResponse]], # request: catalog_service.ListCatalogItemsRequest, # response: catalog_service.ListCatalogItemsResponse, # *, # metadata: Sequence[Tuple[str, str]] = () # ): # def __getattr__(self, name: str) -> Any: # async def pages(self) -> AsyncIterator[catalog_service.ListCatalogItemsResponse]: # def __aiter__(self) -> AsyncIterator[catalog.CatalogItem]: # async def async_generator(): # def __repr__(self) -> str: # # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/catalog_service.py # class CreateCatalogItemRequest(proto.Message): # class GetCatalogItemRequest(proto.Message): # class ListCatalogItemsRequest(proto.Message): # class ListCatalogItemsResponse(proto.Message): # class UpdateCatalogItemRequest(proto.Message): # class DeleteCatalogItemRequest(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/common.py # class FeatureMap(proto.Message): # class StringList(proto.Message): # class FloatList(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): # # Path: google/cloud/recommendationengine_v1beta1/types/user_event.py # class UserEvent(proto.Message): # class EventSource(proto.Enum): # class UserInfo(proto.Message): # class EventDetail(proto.Message): # class ProductEventDetail(proto.Message): # class PurchaseTransaction(proto.Message): # class ProductDetail(proto.Message): # EVENT_SOURCE_UNSPECIFIED = 0 # AUTOML = 1 # ECOMMERCE = 2 # BATCH_UPLOAD = 3 . Output only the next line.
],
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-recommendations-ai", ).version, ) except pkg_resources.DistributionNotFound: <|code_end|> using the current file's imports: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.recommendationengine_v1beta1.types import ( prediction_apikey_registry_service, ) from google.protobuf import empty_pb2 # type: ignore and any relevant context from other files: # Path: google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py # class PredictionApiKeyRegistration(proto.Message): # class CreatePredictionApiKeyRegistrationRequest(proto.Message): # class ListPredictionApiKeyRegistrationsRequest(proto.Message): # class ListPredictionApiKeyRegistrationsResponse(proto.Message): # class DeletePredictionApiKeyRegistrationRequest(proto.Message): # def raw_page(self): . Output only the next line.
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-recommendations-ai", ).version, <|code_end|> using the current file's imports: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import catalog_service from google.cloud.recommendationengine_v1beta1.types import import_ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore and any relevant context from other files: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/catalog_service.py # class CreateCatalogItemRequest(proto.Message): # class GetCatalogItemRequest(proto.Message): # class ListCatalogItemsRequest(proto.Message): # class ListCatalogItemsResponse(proto.Message): # class UpdateCatalogItemRequest(proto.Message): # class DeleteCatalogItemRequest(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): . Output only the next line.
)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-recommendations-ai", ).version, ) except pkg_resources.DistributionNotFound: <|code_end|> . Use current file imports: (import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import catalog_service from google.cloud.recommendationengine_v1beta1.types import import_ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore) and context including class names, function names, or small code snippets from other files: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/catalog_service.py # class CreateCatalogItemRequest(proto.Message): # class GetCatalogItemRequest(proto.Message): # class ListCatalogItemsRequest(proto.Message): # class ListCatalogItemsResponse(proto.Message): # class UpdateCatalogItemRequest(proto.Message): # class DeleteCatalogItemRequest(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): . Output only the next line.
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-recommendations-ai", ).version, ) except pkg_resources.DistributionNotFound: <|code_end|> , predict the immediate next line with the help of imports: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import catalog_service from google.cloud.recommendationengine_v1beta1.types import import_ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore and context (classes, functions, sometimes code) from other files: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 # # Path: google/cloud/recommendationengine_v1beta1/types/catalog_service.py # class CreateCatalogItemRequest(proto.Message): # class GetCatalogItemRequest(proto.Message): # class ListCatalogItemsRequest(proto.Message): # class ListCatalogItemsResponse(proto.Message): # class UpdateCatalogItemRequest(proto.Message): # class DeleteCatalogItemRequest(proto.Message): # def raw_page(self): # # Path: google/cloud/recommendationengine_v1beta1/types/import_.py # class GcsSource(proto.Message): # class CatalogInlineSource(proto.Message): # class UserEventInlineSource(proto.Message): # class ImportErrorsConfig(proto.Message): # class ImportCatalogItemsRequest(proto.Message): # class ImportUserEventsRequest(proto.Message): # class InputConfig(proto.Message): # class ImportMetadata(proto.Message): # class ImportCatalogItemsResponse(proto.Message): # class ImportUserEventsResponse(proto.Message): # class UserEventImportSummary(proto.Message): . Output only the next line.
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __protobuf__ = proto.module( package="google.cloud.recommendationengine.v1beta1", manifest={ "CreateCatalogItemRequest", "GetCatalogItemRequest", <|code_end|> using the current file's imports: import proto # type: ignore from google.cloud.recommendationengine_v1beta1.types import catalog from google.protobuf import field_mask_pb2 # type: ignore and any relevant context from other files: # Path: google/cloud/recommendationengine_v1beta1/types/catalog.py # class CatalogItem(proto.Message): # class CategoryHierarchy(proto.Message): # class ProductCatalogItem(proto.Message): # class StockState(proto.Enum): # class ExactPrice(proto.Message): # class PriceRange(proto.Message): # class Image(proto.Message): # STOCK_STATE_UNSPECIFIED = 0 # IN_STOCK = 0 # OUT_OF_STOCK = 1 # PREORDER = 2 # BACKORDER = 3 . Output only the next line.
"ListCatalogItemsRequest",
Here is a snippet: <|code_start|># # Copyright 2014-2017 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import LOGGER = logging.getLogger(__name__) LogTask = functools.partial(log_utils.LogTask, logger=LOGGER) <|code_end|> . Write the next line using the current file imports: import copy import functools import glob import json import logging import os import shutil import subprocess import time import uuid import warnings import pkg_resources import xmltodict import six import lago.build as build import lago.log_utils as log_utils import lago.paths as paths import lago.sdk_utils as sdk_utils import lago.subnet_lease as subnet_lease import lago.utils as utils import lago.virt as virt from textwrap import dedent from os.path import join from lago.plugins.output import YAMLOutFormatPlugin from six.moves.urllib import request as urllib from six.moves import urllib_parse as urlparse from lago.utils import LagoInitException, LagoException and context from other files: # Path: lago/plugins/output.py # class YAMLOutFormatPlugin(OutFormatPlugin): # def format(self, info_dict): # return yaml.safe_dump( # info_dict, default_flow_style=False, allow_unicode=True # ) # # Path: lago/utils.py # class LagoInitException(LagoException): # pass # # class LagoException(Exception): # pass , which may include functions, classes, or code. Output only the next line.
log_task = functools.partial(log_utils.log_task, logger=LOGGER)
Next line prediction: <|code_start|># # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import LOGGER = logging.getLogger(__name__) LogTask = functools.partial(log_utils.LogTask, logger=LOGGER) log_task = functools.partial(log_utils.log_task, logger=LOGGER) <|code_end|> . Use current file imports: (import copy import functools import glob import json import logging import os import shutil import subprocess import time import uuid import warnings import pkg_resources import xmltodict import six import lago.build as build import lago.log_utils as log_utils import lago.paths as paths import lago.sdk_utils as sdk_utils import lago.subnet_lease as subnet_lease import lago.utils as utils import lago.virt as virt from textwrap import dedent from os.path import join from lago.plugins.output import YAMLOutFormatPlugin from six.moves.urllib import request as urllib from six.moves import urllib_parse as urlparse from lago.utils import LagoInitException, LagoException) and context including class names, function names, or small code snippets from other files: # Path: lago/plugins/output.py # class YAMLOutFormatPlugin(OutFormatPlugin): # def format(self, info_dict): # return yaml.safe_dump( # info_dict, default_flow_style=False, allow_unicode=True # ) # # Path: lago/utils.py # class LagoInitException(LagoException): # pass # # class LagoException(Exception): # pass . Output only the next line.
def _create_ip(subnet, index):
Continue the code snippet: <|code_start|># # Copyright 2017 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import LOGGER = logging.getLogger(__name__) class GuestFSError(LagoException): pass <|code_end|> . Use current file imports: import os import guestfs import logging import time import contextlib from lago.plugins.vm import ExtractPathNoPathError from lago.utils import LagoException and context (classes, functions, or code) from other files: # Path: lago/plugins/vm.py # class ExtractPathNoPathError(VMError): # def __init__(self, err): # super().__init__('Failed to extract files: {}'.format(err)) # # Path: lago/utils.py # class LagoException(Exception): # pass . Output only the next line.
@contextlib.contextmanager
Predict the next line after this snippet: <|code_start|> @sdk_utils.expose class some_class(): pass assert hasattr(some_class, '_sdkmetaclass') def test_expose_class_functions(self): class some_class(object): @sdk_utils.expose def exposed(self, a, b, c): pass inst = some_class() assert hasattr(getattr(inst, 'exposed'), '_sdkmeta') def test_expose_class_mixed(self): @sdk_utils.expose class some_class(object): @sdk_utils.expose def exposed(self, a, b, c): pass def not_exposed(self, a, b, c): pass inst = some_class() assert hasattr(some_class, '_sdkmetaclass') assert hasattr(getattr(inst, 'exposed'), '_sdkmeta') <|code_end|> using the current file's imports: import pytest import types import six from lago import sdk_utils and any relevant context from other files: # Path: lago/sdk_utils.py # class SDKWrapper(wrapt.ObjectProxy): # class SDKMethod(object): # def __getattr__(self, name): # def __dir__(self): # def __init__(self, name): # def expose(func): # def wrapped(*args, **kwargs): # def getattr_sdk(attr, name): # def setup_sdk_logging(logfile=None, loglevel=logging.INFO): . Output only the next line.
assert hasattr(getattr(inst, 'not_exposed'), '_sdkmeta') is False
Given the following code snippet before the placeholder: <|code_start|> @pytest.fixture def event(): return Event() @pytest.fixture def p_wrapper(lockfile, event): duration = 60 event.clear() return ProcessWrapper(target=lock_path, args=(lockfile, duration, event)) def test_should_fail_to_lock_when_already_locked(lockfile, p_wrapper, event): with p_wrapper: assert event.wait(30), 'Timeout while waiting for child process' with pytest.raises(TimerException), LockFile(lockfile, timeout=1): pass def test_should_succeed_to_lock_a_stale_lock(lockfile, p_wrapper, event): p_wrapper.start() assert event.wait(30), 'Timeout while waiting for child process' p_wrapper.kill() # If the process is still running waitpid returns (0, 0) assert not any(p_wrapper.waitpid()), 'Failed to kill child process' with LockFile(lockfile, timeout=1): <|code_end|> , predict the next line using imports from the current file: import signal import pytest from multiprocessing import Process, Event from os import WNOHANG, kill, waitpid from time import sleep from lago.utils import LockFile, TimerException and context including class names, function names, and sometimes code from other files: # Path: lago/utils.py # class LockFile(object): # """ # Context manager that creates a file based lock, with optional # timeout in the acquire operation. # # This context manager should be used only from the main Thread. # # Args: # path(str): path to the dir to lock # timeout(int): timeout in seconds to wait while acquiring the lock # lock_cls(callable): A callable which returns a Lock object that # implements the acquire and release methods. # The default is Flock. # **kwargs(dict): Any other param to pass to the `lock_cls` instance. # # """ # # def __init__(self, path, timeout=None, lock_cls=None, **kwargs): # self.path = path # self.timeout = timeout or 0 # self._lock_cls = lock_cls or Flock # self.lock = self._lock_cls(path=path, **kwargs) # # def __enter__(self): # """ # Start the lock with timeout if needed in the acquire operation # # Raises: # TimerException: if the timeout is reached before acquiring the lock # """ # try: # with ExceptionTimer(timeout=self.timeout): # LOGGER.debug('Acquiring lock for {}'.format(self.path)) # self.lock.acquire() # LOGGER.debug('Holding the lock for {}'.format(self.path)) # except TimerException: # raise TimerException( # 'Unable to acquire lock for %s in %s secs', # self.path, # self.timeout, # ) # # def __exit__(self, *_): # LOGGER.debug('Trying to release lock for {}'.format(self.path)) # self.lock.release() # LOGGER.debug('Lock for {} was released'.format(self.path)) # # class TimerException(Exception): # """ # Exception to throw when a timeout is reached # """ # pass . Output only the next line.
pass
Here is a snippet: <|code_start|> self._p.daemon = daemon def __getattr__(self, name): return getattr(self._p, name) def kill(self, sig=None): sig = signal.SIGKILL if sig is None else sig kill(self.pid, sig) def waitpid(self): return waitpid(self.pid, WNOHANG) def __enter__(self): self.start() def __exit__(self, *args): self.kill() @pytest.fixture def lockfile(tmpdir): return str(tmpdir.join('test-lock')) @pytest.fixture def event(): return Event() @pytest.fixture <|code_end|> . Write the next line using the current file imports: import signal import pytest from multiprocessing import Process, Event from os import WNOHANG, kill, waitpid from time import sleep from lago.utils import LockFile, TimerException and context from other files: # Path: lago/utils.py # class LockFile(object): # """ # Context manager that creates a file based lock, with optional # timeout in the acquire operation. # # This context manager should be used only from the main Thread. # # Args: # path(str): path to the dir to lock # timeout(int): timeout in seconds to wait while acquiring the lock # lock_cls(callable): A callable which returns a Lock object that # implements the acquire and release methods. # The default is Flock. # **kwargs(dict): Any other param to pass to the `lock_cls` instance. # # """ # # def __init__(self, path, timeout=None, lock_cls=None, **kwargs): # self.path = path # self.timeout = timeout or 0 # self._lock_cls = lock_cls or Flock # self.lock = self._lock_cls(path=path, **kwargs) # # def __enter__(self): # """ # Start the lock with timeout if needed in the acquire operation # # Raises: # TimerException: if the timeout is reached before acquiring the lock # """ # try: # with ExceptionTimer(timeout=self.timeout): # LOGGER.debug('Acquiring lock for {}'.format(self.path)) # self.lock.acquire() # LOGGER.debug('Holding the lock for {}'.format(self.path)) # except TimerException: # raise TimerException( # 'Unable to acquire lock for %s in %s secs', # self.path, # self.timeout, # ) # # def __exit__(self, *_): # LOGGER.debug('Trying to release lock for {}'.format(self.path)) # self.lock.release() # LOGGER.debug('Lock for {} was released'.format(self.path)) # # class TimerException(Exception): # """ # Exception to throw when a timeout is reached # """ # pass , which may include functions, classes, or code. Output only the next line.
def p_wrapper(lockfile, event):
Predict the next line for this snippet: <|code_start|> assert result == os.path.abspath(str(tmpdir)) def test_curdir_has_prefix(self, tmpdir, local_prefix): result = prefix.Prefix.resolve_prefix_path(str(tmpdir)) assert result == os.path.abspath(str(local_prefix)) def test_parent_has_prefix(self, tmpdir, local_prefix): sub_dir = tmpdir.mkdir('subdir') result = prefix.Prefix.resolve_prefix_path(str(sub_dir)) assert result == os.path.abspath(str(local_prefix)) def test_many_parent_has_prefix(self, tmpdir, local_prefix): sub_dir = tmpdir.mkdir('subdir') subsub_dir = sub_dir.mkdir('subsubdir') result = prefix.Prefix.resolve_prefix_path(str(subsub_dir)) assert result == os.path.abspath(str(local_prefix)) class TestPrefixNetworkInitalization(object): @pytest.fixture() def default_mgmt(self): return {'management': True, 'dns_domain_name': 'lago.local'} @pytest.mark.parametrize( ('conf'), [ { 'nets': { 'net-1': {} } }, <|code_end|> with the help of current file imports: import os import pytest import lago from lago import prefix from lago.utils import LagoInitException and context from other files: # Path: lago/prefix.py # LOGGER = logging.getLogger(__name__) # VIRT_ENV_CLASS = virt.VirtEnv # CPU_RESOURCE = 3 # MEMORY_RESOURCE = 4 # DISK_RESOURCE = 17 # def _create_ip(subnet, index): # def _ip_in_subnet(subnet, ip): # def __init__(self, prefix): # def metadata(self): # def _save_metadata(self): # def save(self): # def _create_ssh_keys(self): # def initialize(self): # def cleanup(self): # def _init_net_specs(conf): # def _allocate_subnets(self, conf): # def _add_nic_to_mapping(self, net, dom, nic): # def _select_mgmt_networks(self, conf): # def _add_dns_records(self, conf, mgmts): # def _register_preallocated_ips(self, conf): # def _get_net(self, conf, dom_name, nic): # def _allocate_ips_to_nics(self, conf): # def _set_mtu_to_nics(self, conf): # def _config_net_topology(self, conf): # def _add_mgmt_to_domains(self, conf, mgmts): # def _validate_netconfig(self, conf): # def _create_disk( # self, # name, # spec, # template_repo=None, # template_store=None, # ): # def _handle_file_disk(self, disk_spec): # def _retrieve_disk_url(self, disk_url, disk_dst_path=None): # def _generate_disk_name(host_name, disk_name, disk_format): # def _generate_disk_path(self, disk_name): # def _handle_empty_disk(self, host_name, disk_spec): # def _run_qemu(qemu_cmd, disk_path): # def _handle_template( # self, # host_name, # template_spec, # template_store=None, # template_repo=None # ): # def _handle_qcow_template( # self, # disk_path, # template_spec, # template_store=None, # template_repo=None # ): # def resolve_parent(self, disk_path, template_store, template_repo): # def _create_link_to_parent(self, base, link_name): # def _handle_lago_template( # self, disk_path, template_spec, template_store, template_repo # ): # def _ova_to_spec(self, filename): # def _use_prototype(self, spec, prototypes): # def fetch_url(self, url): # def virt_conf_from_stream( # self, # conf_fd, # template_repo=None, # template_store=None, # do_bootstrap=True, # do_build=True, # ): # def _prepare_domains_images(self, conf, template_repo, template_store): # def _prepare_domain_image( # self, domain_spec, prototypes, template_repo, template_store # ): # def _handle_ova_image(self, domain_spec): # def _create_disks( # self, domain_name, disks_specs, template_repo, template_store # ): # def virt_conf( # self, # conf, # template_repo=None, # template_store=None, # do_bootstrap=True, # do_build=True # ): # def build(self, conf): # def export_vms( # self, # vms_names=None, # standalone=False, # export_dir='.', # compress=False, # init_file_name='LagoInitFile', # out_format=YAMLOutFormatPlugin(), # collect_only=False, # with_threads=True, # ): # def start(self, vm_names=None): # def stop(self, vm_names=None): # def shutdown(self, vm_names=None, reboot=False): # def create_snapshots(self, name): # def revert_snapshots(self, name): # def get_snapshots(self): # def _create_virt_env(self): # def virt_env(self): # def paths(self): # def paths(self, val): # def destroy(self): # def get_vms(self): # def get_nets(self): # def get_paths(self): # def resolve_prefix_path(cls, start_path=None): # def is_prefix(cls, path): # def collect_artifacts(self, output_dir, ignore_nopath): # def _collect_artifacts(vm): # def _get_scripts(self, host_metadata): # def _set_scripts(self, host_metadata, scripts): # def _copy_deploy_scripts_for_hosts(self, domains): # def _copy_delpoy_scripts(self, scripts): # def _deploy_host(self, host): # def deploy(self): # class Prefix(object): # class LagoDeployError(LagoException): # # Path: lago/utils.py # class LagoInitException(LagoException): # pass , which may contain function names, class names, or code. Output only the next line.
{
Based on the snippet: <|code_start|> def test_curdir_has_prefix(self, tmpdir, local_prefix): result = prefix.Prefix.resolve_prefix_path(str(tmpdir)) assert result == os.path.abspath(str(local_prefix)) def test_parent_has_prefix(self, tmpdir, local_prefix): sub_dir = tmpdir.mkdir('subdir') result = prefix.Prefix.resolve_prefix_path(str(sub_dir)) assert result == os.path.abspath(str(local_prefix)) def test_many_parent_has_prefix(self, tmpdir, local_prefix): sub_dir = tmpdir.mkdir('subdir') subsub_dir = sub_dir.mkdir('subsubdir') result = prefix.Prefix.resolve_prefix_path(str(subsub_dir)) assert result == os.path.abspath(str(local_prefix)) class TestPrefixNetworkInitalization(object): @pytest.fixture() def default_mgmt(self): return {'management': True, 'dns_domain_name': 'lago.local'} @pytest.mark.parametrize( ('conf'), [ { 'nets': { 'net-1': {} } }, { <|code_end|> , predict the immediate next line with the help of imports: import os import pytest import lago from lago import prefix from lago.utils import LagoInitException and context (classes, functions, sometimes code) from other files: # Path: lago/prefix.py # LOGGER = logging.getLogger(__name__) # VIRT_ENV_CLASS = virt.VirtEnv # CPU_RESOURCE = 3 # MEMORY_RESOURCE = 4 # DISK_RESOURCE = 17 # def _create_ip(subnet, index): # def _ip_in_subnet(subnet, ip): # def __init__(self, prefix): # def metadata(self): # def _save_metadata(self): # def save(self): # def _create_ssh_keys(self): # def initialize(self): # def cleanup(self): # def _init_net_specs(conf): # def _allocate_subnets(self, conf): # def _add_nic_to_mapping(self, net, dom, nic): # def _select_mgmt_networks(self, conf): # def _add_dns_records(self, conf, mgmts): # def _register_preallocated_ips(self, conf): # def _get_net(self, conf, dom_name, nic): # def _allocate_ips_to_nics(self, conf): # def _set_mtu_to_nics(self, conf): # def _config_net_topology(self, conf): # def _add_mgmt_to_domains(self, conf, mgmts): # def _validate_netconfig(self, conf): # def _create_disk( # self, # name, # spec, # template_repo=None, # template_store=None, # ): # def _handle_file_disk(self, disk_spec): # def _retrieve_disk_url(self, disk_url, disk_dst_path=None): # def _generate_disk_name(host_name, disk_name, disk_format): # def _generate_disk_path(self, disk_name): # def _handle_empty_disk(self, host_name, disk_spec): # def _run_qemu(qemu_cmd, disk_path): # def _handle_template( # self, # host_name, # template_spec, # template_store=None, # template_repo=None # ): # def _handle_qcow_template( # self, # disk_path, # template_spec, # template_store=None, # template_repo=None # ): # def resolve_parent(self, disk_path, template_store, template_repo): # def _create_link_to_parent(self, base, link_name): # def _handle_lago_template( # self, disk_path, template_spec, template_store, template_repo # ): # def _ova_to_spec(self, filename): # def _use_prototype(self, spec, prototypes): # def fetch_url(self, url): # def virt_conf_from_stream( # self, # conf_fd, # template_repo=None, # template_store=None, # do_bootstrap=True, # do_build=True, # ): # def _prepare_domains_images(self, conf, template_repo, template_store): # def _prepare_domain_image( # self, domain_spec, prototypes, template_repo, template_store # ): # def _handle_ova_image(self, domain_spec): # def _create_disks( # self, domain_name, disks_specs, template_repo, template_store # ): # def virt_conf( # self, # conf, # template_repo=None, # template_store=None, # do_bootstrap=True, # do_build=True # ): # def build(self, conf): # def export_vms( # self, # vms_names=None, # standalone=False, # export_dir='.', # compress=False, # init_file_name='LagoInitFile', # out_format=YAMLOutFormatPlugin(), # collect_only=False, # with_threads=True, # ): # def start(self, vm_names=None): # def stop(self, vm_names=None): # def shutdown(self, vm_names=None, reboot=False): # def create_snapshots(self, name): # def revert_snapshots(self, name): # def get_snapshots(self): # def _create_virt_env(self): # def virt_env(self): # def paths(self): # def paths(self, val): # def destroy(self): # def get_vms(self): # def get_nets(self): # def get_paths(self): # def resolve_prefix_path(cls, start_path=None): # def is_prefix(cls, path): # def collect_artifacts(self, output_dir, ignore_nopath): # def _collect_artifacts(vm): # def _get_scripts(self, host_metadata): # def _set_scripts(self, host_metadata, scripts): # def _copy_deploy_scripts_for_hosts(self, domains): # def _copy_delpoy_scripts(self, scripts): # def _deploy_host(self, host): # def deploy(self): # class Prefix(object): # class LagoDeployError(LagoException): # # Path: lago/utils.py # class LagoInitException(LagoException): # pass . Output only the next line.
'nets': {
Given the code snippet: <|code_start|> for argname, opts in args: parser.add_argument(argname, **opts) return parser @patch.dict( 'lago.config.os.environ', { 'LAGO_GLOBAL_VAR_1': 'v1', 'LAGO__SECTION__VAR': 'v2', 'LAGO__LONG_SECTION_NAME__LONG_VAR_NAME': 'v3', 'IGNORE_VAR': 'ignore', 'IGNORE__VAR__TWO': 'ignore', } ) def test_get_env_dict_sections(): assert config.get_env_dict('lago') == { 'lago': { 'global_var_1': 'v1' }, 'section': { 'var': 'v2' }, 'long_section_name': { 'long_var_name': 'v3' }, } @patch.dict( 'lago.config.os.environ', { <|code_end|> , generate the next line using the imports in this file: import argparse import pytest import configparser import six from io import StringIO from mock import call, mock_open, patch from lago import config and context (functions, classes, or occasionally code) from other files: # Path: lago/config.py # def _get_configs_path(): # def get_env_dict(root_section): # def __init__(self, root_section='lago', defaults={}): # def load(self): # def update_args(self, args): # def update_parser(self, parser): # def get(self, *args): # def __getitem__(self, key): # def get_section(self, *args): # def get_ini(self, incl_unset=False): # def __repr__(self): # def __str__(self): # class ConfigLoad(object): . Output only the next line.
'LAGO_GLOBAL': '',
Predict the next line after this snippet: <|code_start|> with tempfile.NamedTemporaryFile(mode="w+", delete=False) as f: f.write(init_str) return f.name @pytest.fixture(scope='module') def test_results(request, global_test_results): results_path = os.path.join( global_test_results, str(request.module.__name__) ) os.makedirs(results_path) return results_path @pytest.fixture(scope='module') def external_log(tmpdir_factory): return tmpdir_factory.mktemp('external_log').join('custom_log.log') @pytest.fixture(scope='module', autouse=True) def env(request, init_fname, test_results, tmp_workdir, external_log): workdir = os.path.join(str(tmp_workdir), 'lago') env = sdk.init( init_fname, workdir=workdir, logfile=str(external_log), loglevel=logging.DEBUG, ) env.start() try: <|code_end|> using the current file's imports: import logging import os import shutil import tempfile import pytest import yaml from lago import sdk and any relevant context from other files: # Path: lago/sdk.py # def add_stream_logger(level=logging.DEBUG, name=None): # def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs): # def load_env(workdir, logfile=None, loglevel=logging.INFO): # def __init__(self, workdir, prefix): # def __getattr__(self, name): # def __dir__(self): # def destroy(self): # def ansible_inventory_temp_file( # self, keys=['vm-type', 'groups', 'vm-provider'] # ): # def ansible_inventory( # self, # keys=['vm-type', 'groups', 'vm-provider'], # ): # class SDK(object): . Output only the next line.
yield env
Given the code snippet: <|code_start|>from __future__ import absolute_import @pytest.fixture(scope='module') def init_str(images): <|code_end|> , generate the next line using the imports in this file: import pytest import textwrap import tempfile import os import logging import uuid import filecmp from time import sleep from jinja2 import Environment, BaseLoader from lago import sdk from lago.utils import run_command from lago.plugins.vm import ExtractPathNoPathError from utils import RandomizedDir and context (functions, classes, or occasionally code) from other files: # Path: lago/sdk.py # def add_stream_logger(level=logging.DEBUG, name=None): # def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs): # def load_env(workdir, logfile=None, loglevel=logging.INFO): # def __init__(self, workdir, prefix): # def __getattr__(self, name): # def __dir__(self): # def destroy(self): # def ansible_inventory_temp_file( # self, keys=['vm-type', 'groups', 'vm-provider'] # ): # def ansible_inventory( # self, # keys=['vm-type', 'groups', 'vm-provider'], # ): # class SDK(object): # # Path: lago/utils.py # def run_command( # command, # input_data=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # **kwargs # ): # """ # Runs a command non-interactively # # Args: # command(list of str): args of the command to execute, including the # command itself as command[0] as `['ls', '-l']` # input_data(str): If passed, will feed that data to the subprocess # through stdin # out_pipe(int or file): File descriptor as passed to # :ref:subprocess.Popen to use as stdout # err_pipe(int or file): File descriptor as passed to # :ref:subprocess.Popen to use as stderr # env(dict of str:str): If set, will use the given dict as env for the # subprocess # **kwargs: Any other keyword args passed will be passed to the # :ref:subprocess.Popen call # # Returns: # lago.utils.CommandStatus: result of the interactive execution # """ # if env is None: # env = os.environ.copy() # # with LogTask( # 'Run command: %s' % ' '.join('"%s"' % arg for arg in command), # logger=LOGGER, # level='debug', # ) as task: # command_result = _run_command( # command=command, # input_data=input_data, # out_pipe=out_pipe, # err_pipe=err_pipe, # env=env, # uuid=task.uuid, # **kwargs # ) # return command_result # # Path: lago/plugins/vm.py # class ExtractPathNoPathError(VMError): # def __init__(self, err): # super().__init__('Failed to extract files: {}'.format(err)) . Output only the next line.
init_template = textwrap.dedent(
Given the code snippet: <|code_start|>from __future__ import absolute_import class SDKWrapper(wrapt.ObjectProxy): """A proxy object that exposes only methods which were decorated with :func:`expose` decorator.""" def __getattr__(self, name): attr = getattr(self.__wrapped__, name) return getattr_sdk(attr, name) def __dir__(self): orig = super(SDKWrapper, self).__dir__() filtered = [] for name in orig: attr = getattr(self.__wrapped__, name) try: getattr_sdk(attr, name) filtered.append(name) except AttributeError: pass return filtered <|code_end|> , generate the next line using the imports in this file: import functools import inspect import wrapt import logging from lago.log_utils import get_default_log_formatter and context (functions, classes, or occasionally code) from other files: # Path: lago/log_utils.py # def get_default_log_formatter(): # return logging.Formatter( # fmt=( # '%(asctime)s::%(filename)s::%(funcName)s::%(lineno)s::' # '%(name)s::%(levelname)s::%(message)s' # ), # ) . Output only the next line.
class SDKMethod(object):
Here is a snippet: <|code_start|> sdk.add_stream_logger(level=level, name=name) logger = logging.getLogger(name) assert logger.getEffectiveLevel() == getattr(logging, level) log_at_level = getattr(logger, level.lower()) log_at_level(msg) assert caplog.record_tuples == [ (name, getattr(logging, level.upper()), msg), ] @pytest.mark.xfail(True, reason="fails in CI for unknown reason") @pytest.mark.parametrize('level', ['INFO', 'CRITICAL', 'DEBUG']) def test_init_logger_new_env( self, tmpdir, monkeypatch, mock_workdir, empty_prefix, level ): log_path = tmpdir.mkdir('logs').join('test.log') monkeypatch.setattr( 'lago.cmd.do_init', lambda **kwargs: (mock_workdir, empty_prefix) ) sdk.init( config=None, workdir=None, logfile=str(log_path), loglevel=level ) handlers = [ h for h in logging.root.handlers if isinstance(h, logging.FileHandler) ] assert len(handlers) == 1 handler = handlers.pop() assert handler.stream.name == str(log_path) assert handler.level == getattr(logging, level) <|code_end|> . Write the next line using the current file imports: import pytest import logging from lago import sdk and context from other files: # Path: lago/sdk.py # def add_stream_logger(level=logging.DEBUG, name=None): # def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs): # def load_env(workdir, logfile=None, loglevel=logging.INFO): # def __init__(self, workdir, prefix): # def __getattr__(self, name): # def __dir__(self): # def destroy(self): # def ansible_inventory_temp_file( # self, keys=['vm-type', 'groups', 'vm-provider'] # ): # def ansible_inventory( # self, # keys=['vm-type', 'groups', 'vm-provider'], # ): # class SDK(object): , which may include functions, classes, or code. Output only the next line.
logging.root.removeHandler(handler)
Based on the snippet: <|code_start|># # Copyright 2017 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import LOGGER = logging.getLogger(__name__) class CPU(object): <|code_end|> , predict the immediate next line with the help of imports: import logging import os import lago.providers.libvirt.utils as utils from lxml import etree as ET from lago.utils import LagoException, LagoInitException and context (classes, functions, sometimes code) from other files: # Path: lago/utils.py # class LagoException(Exception): # pass # # class LagoInitException(LagoException): # pass . Output only the next line.
def __init__(self, spec, host_cpu):
Given the code snippet: <|code_start|> @pytest.fixture() def subnet_store(self, tmpdir): subnet_store_path = tmpdir.mkdir('subnet_store') return subnet_lease.SubnetStore(str(subnet_store_path)) @pytest.fixture() def prefixes(self, tmpdir): return self.create_workdir_with_prefixes(tmpdir) @pytest.fixture() def prefix(self, tmpdir): return \ self.create_workdir_with_prefixes(tmpdir, num_of_prefixes=1)[0] @pytest.mark.parametrize('subnet', [None, '192.168.210.0']) def test_take_random_lease(self, subnet_store, subnet, prefix): network = subnet_store.acquire(prefix.uuid_path, subnet) third_octet = str(network).split('.')[2] path_to_lease = os.path.join( subnet_store.path, '{}.lease'.format(third_octet) ) _, dirnames, filenames = next(os.walk(subnet_store.path)) try: # Don't count the lockfile filenames.remove(LOCK_NAME) except ValueError: pass <|code_end|> , generate the next line using the imports in this file: from lago import subnet_lease from lago.subnet_lease import ( LagoSubnetLeaseOutOfRangeException, LagoSubnetLeaseStoreFullException, LagoSubnetLeaseTakenException, LagoSubnetLeaseMalformedAddrException, LagoSubnetLeaseBadPermissionsException, LOCK_NAME ) from mock import patch import pytest import uuid import os import json import shutil import random and context (functions, classes, or occasionally code) from other files: # Path: lago/subnet_lease.py # LOGGER = logging.getLogger(__name__) # LOCK_NAME = 'subnet-lease.lock' # class SubnetStore(object): # class Lease(object): # class LagoSubnetLeaseException(utils.LagoException): # class LagoSubnetLeaseLockException(LagoSubnetLeaseException): # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__( # self, # path=None, # min_third_octet=200, # max_third_octet=255, # ): # def _create_lock(self): # def _validate_lease_dir(self): # def acquire(self, uuid_path, subnet=None): # def _acquire(self, uuid_path): # def _acquire_given_subnet(self, uuid_path, subnet): # def _lease_valid(self, lease): # def _take_lease(self, lease, uuid_path, safe=True): # def list_leases(self, uuid=None): # def release(self, subnets): # def _release(self, lease): # def _lease_owned(self, lease, current_uuid_path): # def create_lease_object_from_idx(self, idx): # def create_lease_object_from_subnet(self, subnet): # def is_leasable_subnet(self, subnet): # def get_allowed_range(self): # def path(self): # def __init__(self, store_path, subnet): # def _realise_lease_path(self): # def to_ip_network(self): # def valid(self): # def metadata(self): # def uuid(self): # def uuid_path(self): # def has_env(self): # def _has_env(self, uuid_path=None, uuid=None): # def exist(self): # def path(self): # def path(self, data): # def subnet(self): # def subnet(self, data): # def __str__(self): # def __init__(self, msg, prv_msg=None): # def __init__(self, store_path): # def __init__(self, store_range): # def __init__(self, required_subnet, lease_taken_by): # def __init__(self, required_subnet, store_range): # def __init__(self, required_subnet): # def __init__(self, store_path, prv_msg): # # Path: lago/subnet_lease.py # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # def __init__(self, required_subnet, store_range): # super().__init__( # dedent( # """ # Subnet {} is not valid. # Subnet should be in the range {}. # """.format(required_subnet, store_range) # ) # ) # # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # def __init__(self, store_range): # super().__init__( # dedent( # """ # Can't acquire subnet from range {} # The store of subnets is full. # You can free subnets by destroying unused lago environments' # """.format(store_range) # ) # ) # # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # def __init__(self, required_subnet, lease_taken_by): # super().__init__( # dedent( # """ # Can't acquire subnet {}. # The subnet is already taken by {}. # """.format(required_subnet, lease_taken_by) # ) # ) # # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # def __init__(self, required_subnet): # super().__init__( # dedent( # """ # Address {} is not a valid ip address # """.format(required_subnet) # ) # ) # # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__(self, store_path, prv_msg): # super().__init__( # dedent( # """ # Failed to get access to the store at {}. # Please make sure that you have R/W permissions to this # directory and that it exists. # """.format(store_path) # ), # prv_msg=prv_msg, # ) # # LOCK_NAME = 'subnet-lease.lock' . Output only the next line.
assert \
Given the code snippet: <|code_start|> def path(self): return self._path @property def uuid_path(self): return self._uuid_path @pytest.fixture def prefix_mock_gen(tmpdir): def gen(): while True: yield PrefixMock(path=str(tmpdir.mkdtemp(rootdir=str(tmpdir)))) return gen class TestSubnetStore(object): def create_prefixes(self, path_to_workdir, num_of_prefixes=2): prefixes = [] for i in range(0, num_of_prefixes): prefix_path = os.path.join(path_to_workdir, 'prefix_{}'.format(i)) prefixes.append(PrefixMock(prefix_path)) return prefixes def create_workdir_with_prefixes(self, temp_dir, num_of_prefixes=2): workdir = temp_dir.mkdir('workdir') return self.create_prefixes(str(workdir), num_of_prefixes) <|code_end|> , generate the next line using the imports in this file: from lago import subnet_lease from lago.subnet_lease import ( LagoSubnetLeaseOutOfRangeException, LagoSubnetLeaseStoreFullException, LagoSubnetLeaseTakenException, LagoSubnetLeaseMalformedAddrException, LagoSubnetLeaseBadPermissionsException, LOCK_NAME ) from mock import patch import pytest import uuid import os import json import shutil import random and context (functions, classes, or occasionally code) from other files: # Path: lago/subnet_lease.py # LOGGER = logging.getLogger(__name__) # LOCK_NAME = 'subnet-lease.lock' # class SubnetStore(object): # class Lease(object): # class LagoSubnetLeaseException(utils.LagoException): # class LagoSubnetLeaseLockException(LagoSubnetLeaseException): # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__( # self, # path=None, # min_third_octet=200, # max_third_octet=255, # ): # def _create_lock(self): # def _validate_lease_dir(self): # def acquire(self, uuid_path, subnet=None): # def _acquire(self, uuid_path): # def _acquire_given_subnet(self, uuid_path, subnet): # def _lease_valid(self, lease): # def _take_lease(self, lease, uuid_path, safe=True): # def list_leases(self, uuid=None): # def release(self, subnets): # def _release(self, lease): # def _lease_owned(self, lease, current_uuid_path): # def create_lease_object_from_idx(self, idx): # def create_lease_object_from_subnet(self, subnet): # def is_leasable_subnet(self, subnet): # def get_allowed_range(self): # def path(self): # def __init__(self, store_path, subnet): # def _realise_lease_path(self): # def to_ip_network(self): # def valid(self): # def metadata(self): # def uuid(self): # def uuid_path(self): # def has_env(self): # def _has_env(self, uuid_path=None, uuid=None): # def exist(self): # def path(self): # def path(self, data): # def subnet(self): # def subnet(self, data): # def __str__(self): # def __init__(self, msg, prv_msg=None): # def __init__(self, store_path): # def __init__(self, store_range): # def __init__(self, required_subnet, lease_taken_by): # def __init__(self, required_subnet, store_range): # def __init__(self, required_subnet): # def __init__(self, store_path, prv_msg): # # Path: lago/subnet_lease.py # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # def __init__(self, required_subnet, store_range): # super().__init__( # dedent( # """ # Subnet {} is not valid. # Subnet should be in the range {}. # """.format(required_subnet, store_range) # ) # ) # # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # def __init__(self, store_range): # super().__init__( # dedent( # """ # Can't acquire subnet from range {} # The store of subnets is full. # You can free subnets by destroying unused lago environments' # """.format(store_range) # ) # ) # # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # def __init__(self, required_subnet, lease_taken_by): # super().__init__( # dedent( # """ # Can't acquire subnet {}. # The subnet is already taken by {}. # """.format(required_subnet, lease_taken_by) # ) # ) # # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # def __init__(self, required_subnet): # super().__init__( # dedent( # """ # Address {} is not a valid ip address # """.format(required_subnet) # ) # ) # # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__(self, store_path, prv_msg): # super().__init__( # dedent( # """ # Failed to get access to the store at {}. # Please make sure that you have R/W permissions to this # directory and that it exists. # """.format(store_path) # ), # prv_msg=prv_msg, # ) # # LOCK_NAME = 'subnet-lease.lock' . Output only the next line.
@pytest.fixture()
Predict the next line after this snippet: <|code_start|> subnet_store.acquire(prefix.uuid_path) def test_recalim_lease(self, subnet_store, prefix): network = subnet_store.acquire(prefix.uuid_path) reclaimed_network = subnet_store.acquire( prefix.uuid_path, str(network) ) assert network == reclaimed_network def test_fail_to_calim_taken_lease(self, subnet_store, prefixes): with pytest.raises(LagoSubnetLeaseTakenException): network = subnet_store.acquire(prefixes[0].uuid_path) subnet_store.acquire(prefixes[1].uuid_path, str(network)) def test_take_stale_lease(self, subnet_store, prefixes): network = subnet_store.acquire(prefixes[0].uuid_path) prefixes[0].remove() subnet_store.acquire(prefixes[1].uuid_path, str(network)) @pytest.mark.parametrize('num_prefixes', [7, 10, 55]) @pytest.mark.parametrize('remains', [0, 3, 6]) def test_release_several_prefixes( self, subnet_store, prefix_mock_gen, num_prefixes, remains ): def get_leases(): return [f for f in os.listdir(subnet_store.path) if f != LOCK_NAME] gen = prefix_mock_gen() for _ in range(num_prefixes): <|code_end|> using the current file's imports: from lago import subnet_lease from lago.subnet_lease import ( LagoSubnetLeaseOutOfRangeException, LagoSubnetLeaseStoreFullException, LagoSubnetLeaseTakenException, LagoSubnetLeaseMalformedAddrException, LagoSubnetLeaseBadPermissionsException, LOCK_NAME ) from mock import patch import pytest import uuid import os import json import shutil import random and any relevant context from other files: # Path: lago/subnet_lease.py # LOGGER = logging.getLogger(__name__) # LOCK_NAME = 'subnet-lease.lock' # class SubnetStore(object): # class Lease(object): # class LagoSubnetLeaseException(utils.LagoException): # class LagoSubnetLeaseLockException(LagoSubnetLeaseException): # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__( # self, # path=None, # min_third_octet=200, # max_third_octet=255, # ): # def _create_lock(self): # def _validate_lease_dir(self): # def acquire(self, uuid_path, subnet=None): # def _acquire(self, uuid_path): # def _acquire_given_subnet(self, uuid_path, subnet): # def _lease_valid(self, lease): # def _take_lease(self, lease, uuid_path, safe=True): # def list_leases(self, uuid=None): # def release(self, subnets): # def _release(self, lease): # def _lease_owned(self, lease, current_uuid_path): # def create_lease_object_from_idx(self, idx): # def create_lease_object_from_subnet(self, subnet): # def is_leasable_subnet(self, subnet): # def get_allowed_range(self): # def path(self): # def __init__(self, store_path, subnet): # def _realise_lease_path(self): # def to_ip_network(self): # def valid(self): # def metadata(self): # def uuid(self): # def uuid_path(self): # def has_env(self): # def _has_env(self, uuid_path=None, uuid=None): # def exist(self): # def path(self): # def path(self, data): # def subnet(self): # def subnet(self, data): # def __str__(self): # def __init__(self, msg, prv_msg=None): # def __init__(self, store_path): # def __init__(self, store_range): # def __init__(self, required_subnet, lease_taken_by): # def __init__(self, required_subnet, store_range): # def __init__(self, required_subnet): # def __init__(self, store_path, prv_msg): # # Path: lago/subnet_lease.py # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # def __init__(self, required_subnet, store_range): # super().__init__( # dedent( # """ # Subnet {} is not valid. # Subnet should be in the range {}. # """.format(required_subnet, store_range) # ) # ) # # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # def __init__(self, store_range): # super().__init__( # dedent( # """ # Can't acquire subnet from range {} # The store of subnets is full. # You can free subnets by destroying unused lago environments' # """.format(store_range) # ) # ) # # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # def __init__(self, required_subnet, lease_taken_by): # super().__init__( # dedent( # """ # Can't acquire subnet {}. # The subnet is already taken by {}. # """.format(required_subnet, lease_taken_by) # ) # ) # # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # def __init__(self, required_subnet): # super().__init__( # dedent( # """ # Address {} is not a valid ip address # """.format(required_subnet) # ) # ) # # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__(self, store_path, prv_msg): # super().__init__( # dedent( # """ # Failed to get access to the store at {}. # Please make sure that you have R/W permissions to this # directory and that it exists. # """.format(store_path) # ), # prv_msg=prv_msg, # ) # # LOCK_NAME = 'subnet-lease.lock' . Output only the next line.
subnet_store.acquire(next(gen).uuid_path)
Continue the code snippet: <|code_start|> for i in range(0, num_of_prefixes): prefix_path = os.path.join(path_to_workdir, 'prefix_{}'.format(i)) prefixes.append(PrefixMock(prefix_path)) return prefixes def create_workdir_with_prefixes(self, temp_dir, num_of_prefixes=2): workdir = temp_dir.mkdir('workdir') return self.create_prefixes(str(workdir), num_of_prefixes) @pytest.fixture() def subnet_store(self, tmpdir): subnet_store_path = tmpdir.mkdir('subnet_store') return subnet_lease.SubnetStore(str(subnet_store_path)) @pytest.fixture() def prefixes(self, tmpdir): return self.create_workdir_with_prefixes(tmpdir) @pytest.fixture() def prefix(self, tmpdir): return \ self.create_workdir_with_prefixes(tmpdir, num_of_prefixes=1)[0] @pytest.mark.parametrize('subnet', [None, '192.168.210.0']) def test_take_random_lease(self, subnet_store, subnet, prefix): network = subnet_store.acquire(prefix.uuid_path, subnet) third_octet = str(network).split('.')[2] path_to_lease = os.path.join( subnet_store.path, '{}.lease'.format(third_octet) <|code_end|> . Use current file imports: from lago import subnet_lease from lago.subnet_lease import ( LagoSubnetLeaseOutOfRangeException, LagoSubnetLeaseStoreFullException, LagoSubnetLeaseTakenException, LagoSubnetLeaseMalformedAddrException, LagoSubnetLeaseBadPermissionsException, LOCK_NAME ) from mock import patch import pytest import uuid import os import json import shutil import random and context (classes, functions, or code) from other files: # Path: lago/subnet_lease.py # LOGGER = logging.getLogger(__name__) # LOCK_NAME = 'subnet-lease.lock' # class SubnetStore(object): # class Lease(object): # class LagoSubnetLeaseException(utils.LagoException): # class LagoSubnetLeaseLockException(LagoSubnetLeaseException): # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__( # self, # path=None, # min_third_octet=200, # max_third_octet=255, # ): # def _create_lock(self): # def _validate_lease_dir(self): # def acquire(self, uuid_path, subnet=None): # def _acquire(self, uuid_path): # def _acquire_given_subnet(self, uuid_path, subnet): # def _lease_valid(self, lease): # def _take_lease(self, lease, uuid_path, safe=True): # def list_leases(self, uuid=None): # def release(self, subnets): # def _release(self, lease): # def _lease_owned(self, lease, current_uuid_path): # def create_lease_object_from_idx(self, idx): # def create_lease_object_from_subnet(self, subnet): # def is_leasable_subnet(self, subnet): # def get_allowed_range(self): # def path(self): # def __init__(self, store_path, subnet): # def _realise_lease_path(self): # def to_ip_network(self): # def valid(self): # def metadata(self): # def uuid(self): # def uuid_path(self): # def has_env(self): # def _has_env(self, uuid_path=None, uuid=None): # def exist(self): # def path(self): # def path(self, data): # def subnet(self): # def subnet(self, data): # def __str__(self): # def __init__(self, msg, prv_msg=None): # def __init__(self, store_path): # def __init__(self, store_range): # def __init__(self, required_subnet, lease_taken_by): # def __init__(self, required_subnet, store_range): # def __init__(self, required_subnet): # def __init__(self, store_path, prv_msg): # # Path: lago/subnet_lease.py # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # def __init__(self, required_subnet, store_range): # super().__init__( # dedent( # """ # Subnet {} is not valid. # Subnet should be in the range {}. # """.format(required_subnet, store_range) # ) # ) # # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # def __init__(self, store_range): # super().__init__( # dedent( # """ # Can't acquire subnet from range {} # The store of subnets is full. # You can free subnets by destroying unused lago environments' # """.format(store_range) # ) # ) # # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # def __init__(self, required_subnet, lease_taken_by): # super().__init__( # dedent( # """ # Can't acquire subnet {}. # The subnet is already taken by {}. # """.format(required_subnet, lease_taken_by) # ) # ) # # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # def __init__(self, required_subnet): # super().__init__( # dedent( # """ # Address {} is not a valid ip address # """.format(required_subnet) # ) # ) # # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__(self, store_path, prv_msg): # super().__init__( # dedent( # """ # Failed to get access to the store at {}. # Please make sure that you have R/W permissions to this # directory and that it exists. # """.format(store_path) # ), # prv_msg=prv_msg, # ) # # LOCK_NAME = 'subnet-lease.lock' . Output only the next line.
)
Given snippet: <|code_start|> def _create_uuid(self): with open(self.uuid_path, mode='wt') as f: f.write(uuid.uuid1().hex) def remove(self): shutil.rmtree(self.path) @property def path(self): return self._path @property def uuid_path(self): return self._uuid_path @pytest.fixture def prefix_mock_gen(tmpdir): def gen(): while True: yield PrefixMock(path=str(tmpdir.mkdtemp(rootdir=str(tmpdir)))) return gen class TestSubnetStore(object): def create_prefixes(self, path_to_workdir, num_of_prefixes=2): prefixes = [] for i in range(0, num_of_prefixes): prefix_path = os.path.join(path_to_workdir, 'prefix_{}'.format(i)) <|code_end|> , continue by predicting the next line. Consider current file imports: from lago import subnet_lease from lago.subnet_lease import ( LagoSubnetLeaseOutOfRangeException, LagoSubnetLeaseStoreFullException, LagoSubnetLeaseTakenException, LagoSubnetLeaseMalformedAddrException, LagoSubnetLeaseBadPermissionsException, LOCK_NAME ) from mock import patch import pytest import uuid import os import json import shutil import random and context: # Path: lago/subnet_lease.py # LOGGER = logging.getLogger(__name__) # LOCK_NAME = 'subnet-lease.lock' # class SubnetStore(object): # class Lease(object): # class LagoSubnetLeaseException(utils.LagoException): # class LagoSubnetLeaseLockException(LagoSubnetLeaseException): # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__( # self, # path=None, # min_third_octet=200, # max_third_octet=255, # ): # def _create_lock(self): # def _validate_lease_dir(self): # def acquire(self, uuid_path, subnet=None): # def _acquire(self, uuid_path): # def _acquire_given_subnet(self, uuid_path, subnet): # def _lease_valid(self, lease): # def _take_lease(self, lease, uuid_path, safe=True): # def list_leases(self, uuid=None): # def release(self, subnets): # def _release(self, lease): # def _lease_owned(self, lease, current_uuid_path): # def create_lease_object_from_idx(self, idx): # def create_lease_object_from_subnet(self, subnet): # def is_leasable_subnet(self, subnet): # def get_allowed_range(self): # def path(self): # def __init__(self, store_path, subnet): # def _realise_lease_path(self): # def to_ip_network(self): # def valid(self): # def metadata(self): # def uuid(self): # def uuid_path(self): # def has_env(self): # def _has_env(self, uuid_path=None, uuid=None): # def exist(self): # def path(self): # def path(self, data): # def subnet(self): # def subnet(self, data): # def __str__(self): # def __init__(self, msg, prv_msg=None): # def __init__(self, store_path): # def __init__(self, store_range): # def __init__(self, required_subnet, lease_taken_by): # def __init__(self, required_subnet, store_range): # def __init__(self, required_subnet): # def __init__(self, store_path, prv_msg): # # Path: lago/subnet_lease.py # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # def __init__(self, required_subnet, store_range): # super().__init__( # dedent( # """ # Subnet {} is not valid. # Subnet should be in the range {}. # """.format(required_subnet, store_range) # ) # ) # # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # def __init__(self, store_range): # super().__init__( # dedent( # """ # Can't acquire subnet from range {} # The store of subnets is full. # You can free subnets by destroying unused lago environments' # """.format(store_range) # ) # ) # # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # def __init__(self, required_subnet, lease_taken_by): # super().__init__( # dedent( # """ # Can't acquire subnet {}. # The subnet is already taken by {}. # """.format(required_subnet, lease_taken_by) # ) # ) # # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # def __init__(self, required_subnet): # super().__init__( # dedent( # """ # Address {} is not a valid ip address # """.format(required_subnet) # ) # ) # # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__(self, store_path, prv_msg): # super().__init__( # dedent( # """ # Failed to get access to the store at {}. # Please make sure that you have R/W permissions to this # directory and that it exists. # """.format(store_path) # ), # prv_msg=prv_msg, # ) # # LOCK_NAME = 'subnet-lease.lock' which might include code, classes, or functions. Output only the next line.
prefixes.append(PrefixMock(prefix_path))
Using the snippet: <|code_start|>from __future__ import absolute_import def lease_has_valid_uuid(path_to_lease): with open(path_to_lease, mode='rt') as f: <|code_end|> , determine the next line of code. You have imports: from lago import subnet_lease from lago.subnet_lease import ( LagoSubnetLeaseOutOfRangeException, LagoSubnetLeaseStoreFullException, LagoSubnetLeaseTakenException, LagoSubnetLeaseMalformedAddrException, LagoSubnetLeaseBadPermissionsException, LOCK_NAME ) from mock import patch import pytest import uuid import os import json import shutil import random and context (class names, function names, or code) available: # Path: lago/subnet_lease.py # LOGGER = logging.getLogger(__name__) # LOCK_NAME = 'subnet-lease.lock' # class SubnetStore(object): # class Lease(object): # class LagoSubnetLeaseException(utils.LagoException): # class LagoSubnetLeaseLockException(LagoSubnetLeaseException): # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__( # self, # path=None, # min_third_octet=200, # max_third_octet=255, # ): # def _create_lock(self): # def _validate_lease_dir(self): # def acquire(self, uuid_path, subnet=None): # def _acquire(self, uuid_path): # def _acquire_given_subnet(self, uuid_path, subnet): # def _lease_valid(self, lease): # def _take_lease(self, lease, uuid_path, safe=True): # def list_leases(self, uuid=None): # def release(self, subnets): # def _release(self, lease): # def _lease_owned(self, lease, current_uuid_path): # def create_lease_object_from_idx(self, idx): # def create_lease_object_from_subnet(self, subnet): # def is_leasable_subnet(self, subnet): # def get_allowed_range(self): # def path(self): # def __init__(self, store_path, subnet): # def _realise_lease_path(self): # def to_ip_network(self): # def valid(self): # def metadata(self): # def uuid(self): # def uuid_path(self): # def has_env(self): # def _has_env(self, uuid_path=None, uuid=None): # def exist(self): # def path(self): # def path(self, data): # def subnet(self): # def subnet(self, data): # def __str__(self): # def __init__(self, msg, prv_msg=None): # def __init__(self, store_path): # def __init__(self, store_range): # def __init__(self, required_subnet, lease_taken_by): # def __init__(self, required_subnet, store_range): # def __init__(self, required_subnet): # def __init__(self, store_path, prv_msg): # # Path: lago/subnet_lease.py # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # def __init__(self, required_subnet, store_range): # super().__init__( # dedent( # """ # Subnet {} is not valid. # Subnet should be in the range {}. # """.format(required_subnet, store_range) # ) # ) # # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # def __init__(self, store_range): # super().__init__( # dedent( # """ # Can't acquire subnet from range {} # The store of subnets is full. # You can free subnets by destroying unused lago environments' # """.format(store_range) # ) # ) # # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # def __init__(self, required_subnet, lease_taken_by): # super().__init__( # dedent( # """ # Can't acquire subnet {}. # The subnet is already taken by {}. # """.format(required_subnet, lease_taken_by) # ) # ) # # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # def __init__(self, required_subnet): # super().__init__( # dedent( # """ # Address {} is not a valid ip address # """.format(required_subnet) # ) # ) # # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__(self, store_path, prv_msg): # super().__init__( # dedent( # """ # Failed to get access to the store at {}. # Please make sure that you have R/W permissions to this # directory and that it exists. # """.format(store_path) # ), # prv_msg=prv_msg, # ) # # LOCK_NAME = 'subnet-lease.lock' . Output only the next line.
uuid_path, uuid_value = json.load(f)
Continue the code snippet: <|code_start|> @pytest.fixture() def subnet_store(self, tmpdir): subnet_store_path = tmpdir.mkdir('subnet_store') return subnet_lease.SubnetStore(str(subnet_store_path)) @pytest.fixture() def prefixes(self, tmpdir): return self.create_workdir_with_prefixes(tmpdir) @pytest.fixture() def prefix(self, tmpdir): return \ self.create_workdir_with_prefixes(tmpdir, num_of_prefixes=1)[0] @pytest.mark.parametrize('subnet', [None, '192.168.210.0']) def test_take_random_lease(self, subnet_store, subnet, prefix): network = subnet_store.acquire(prefix.uuid_path, subnet) third_octet = str(network).split('.')[2] path_to_lease = os.path.join( subnet_store.path, '{}.lease'.format(third_octet) ) _, dirnames, filenames = next(os.walk(subnet_store.path)) try: # Don't count the lockfile filenames.remove(LOCK_NAME) except ValueError: pass assert \ <|code_end|> . Use current file imports: from lago import subnet_lease from lago.subnet_lease import ( LagoSubnetLeaseOutOfRangeException, LagoSubnetLeaseStoreFullException, LagoSubnetLeaseTakenException, LagoSubnetLeaseMalformedAddrException, LagoSubnetLeaseBadPermissionsException, LOCK_NAME ) from mock import patch import pytest import uuid import os import json import shutil import random and context (classes, functions, or code) from other files: # Path: lago/subnet_lease.py # LOGGER = logging.getLogger(__name__) # LOCK_NAME = 'subnet-lease.lock' # class SubnetStore(object): # class Lease(object): # class LagoSubnetLeaseException(utils.LagoException): # class LagoSubnetLeaseLockException(LagoSubnetLeaseException): # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__( # self, # path=None, # min_third_octet=200, # max_third_octet=255, # ): # def _create_lock(self): # def _validate_lease_dir(self): # def acquire(self, uuid_path, subnet=None): # def _acquire(self, uuid_path): # def _acquire_given_subnet(self, uuid_path, subnet): # def _lease_valid(self, lease): # def _take_lease(self, lease, uuid_path, safe=True): # def list_leases(self, uuid=None): # def release(self, subnets): # def _release(self, lease): # def _lease_owned(self, lease, current_uuid_path): # def create_lease_object_from_idx(self, idx): # def create_lease_object_from_subnet(self, subnet): # def is_leasable_subnet(self, subnet): # def get_allowed_range(self): # def path(self): # def __init__(self, store_path, subnet): # def _realise_lease_path(self): # def to_ip_network(self): # def valid(self): # def metadata(self): # def uuid(self): # def uuid_path(self): # def has_env(self): # def _has_env(self, uuid_path=None, uuid=None): # def exist(self): # def path(self): # def path(self, data): # def subnet(self): # def subnet(self, data): # def __str__(self): # def __init__(self, msg, prv_msg=None): # def __init__(self, store_path): # def __init__(self, store_range): # def __init__(self, required_subnet, lease_taken_by): # def __init__(self, required_subnet, store_range): # def __init__(self, required_subnet): # def __init__(self, store_path, prv_msg): # # Path: lago/subnet_lease.py # class LagoSubnetLeaseOutOfRangeException(LagoSubnetLeaseException): # def __init__(self, required_subnet, store_range): # super().__init__( # dedent( # """ # Subnet {} is not valid. # Subnet should be in the range {}. # """.format(required_subnet, store_range) # ) # ) # # class LagoSubnetLeaseStoreFullException(LagoSubnetLeaseException): # def __init__(self, store_range): # super().__init__( # dedent( # """ # Can't acquire subnet from range {} # The store of subnets is full. # You can free subnets by destroying unused lago environments' # """.format(store_range) # ) # ) # # class LagoSubnetLeaseTakenException(LagoSubnetLeaseException): # def __init__(self, required_subnet, lease_taken_by): # super().__init__( # dedent( # """ # Can't acquire subnet {}. # The subnet is already taken by {}. # """.format(required_subnet, lease_taken_by) # ) # ) # # class LagoSubnetLeaseMalformedAddrException(LagoSubnetLeaseException): # def __init__(self, required_subnet): # super().__init__( # dedent( # """ # Address {} is not a valid ip address # """.format(required_subnet) # ) # ) # # class LagoSubnetLeaseBadPermissionsException(LagoSubnetLeaseException): # def __init__(self, store_path, prv_msg): # super().__init__( # dedent( # """ # Failed to get access to the store at {}. # Please make sure that you have R/W permissions to this # directory and that it exists. # """.format(store_path) # ), # prv_msg=prv_msg, # ) # # LOCK_NAME = 'subnet-lease.lock' . Output only the next line.
len(dirnames) == 0 and \
Using the snippet: <|code_start|># # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import LOGGER = logging.getLogger(__name__) try: except ImportError: LOGGER.debug('guestfs not available, ignoring') def _guestfs_version(): if 'guestfs' in sys.modules: g = guestfs.GuestFS(python_return_dict=True) guestfs_ver = g.version() g.close() else: guestfs_ver = {'major': 1, 'minor': 20} return guestfs_ver def _render_template(distro, loader, **kwargs): env = Environment( loader=loader, <|code_end|> , determine the next line of code. You have imports: import logging import os import sys import tempfile import textwrap import guestfs from jinja2 import Environment, PackageLoader from lago import utils and context (class names, function names, or code) available: # Path: lago/utils.py # LOGGER = logging.getLogger(__name__) # class TimerException(Exception): # class VectorThread: # class CommandStatus(_CommandStatus): # class RollbackContext(object): # class EggTimer: # class ExceptionTimer(object): # class Flock(object): # class LockFile(object): # class TemporaryDirectory(object): # class LagoException(Exception): # class LagoInitException(LagoException): # class LagoUserException(LagoException): # def _ret_via_queue(func, queue): # def func_vector(target, args_sequence): # def __init__(self, targets): # def start_all(self): # def join_all(self, raise_exceptions=True): # def invoke_in_parallel(func, *args_sequences): # def invoke_different_funcs_in_parallel(*funcs): # def __bool__(self): # def _run_command( # command, # input_data=None, # stdin=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # uuid=None, # **kwargs # ): # def run_command( # command, # input_data=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # **kwargs # ): # def run_interactive_command(command, env=None, **kwargs): # def service_is_enabled(name): # def __init__(self, *args): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def defer(self, func, *args, **kwargs): # def prependDefer(self, func, *args, **kwargs): # def clear(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def elapsed(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def start(self): # def raise_timeout(*_): # def stop(self): # def __init__(self, path, readonly=False, blocking=True): # def acquire(self): # def release(self): # def __init__(self, path, timeout=None, lock_cls=None, **kwargs): # def __enter__(self): # def __exit__(self, *_): # def __init__(self, ignore_errors=True): # def __enter__(self): # def __exit__(self, *_): # def read_nonblocking(file_descriptor): # def json_dump(obj, f): # def deepcopy(original_obj): # def load_virt_stream(virt_fd): # def in_prefix(prefix_class, workdir_class): # def decorator(func): # def wrapper(*args, **kwargs): # def with_logging(func): # def wrapper(prefix, *args, **kwargs): # def add_timestamp_suffix(base_string): # def rotate_dir(base_dir): # def ipv4_to_mac(ip): # def argparse_to_ini(parser, root_section=u'lago', incl_unset=False): # def _add_subparser_to_cp(cp, section, actions, incl_unset): # def run_command_with_validation( # cmd, fail_on_error=True, msg='An error has occurred' # ): # def get_qemu_info(path, backing_chain=False, fail_on_error=True): # def qemu_rebase(target, backing_file, safe=True, fail_on_error=True): # def compress(input_file, block_size, fail_on_error=True): # def cp(input_file, output_file, fail_on_error=True): # def sparse(input_file, input_format, fail_on_error=True): # def get_hash(file_path, checksum='sha1'): # def filter_spec(spec, paths, wildcard='*', separator='/'): # def remove_key(path, spec): # def ver_cmp(ver1, ver2): . Output only the next line.
trim_blocks=True,
Given the code snippet: <|code_start|> loaded_conf = utils.load_virt_stream(virt_fd=json_fd) assert deep_compare(self.virt_conf, loaded_conf) def test_fallback_to_yaml(self): bad_json = StringIO("{'one': 1,}") expected = {'one': 1} loaded_conf = utils.load_virt_stream(virt_fd=bad_json) assert deep_compare(expected, loaded_conf) def test_should_give_a_temporary_directory_in(): remembered_dir_path = None remembered_file_path = None with utils.TemporaryDirectory() as tmpdir_path: remembered_dir_path = tmpdir_path assert os.path.isdir(tmpdir_path) some_file_path = os.path.join(tmpdir_path, "smth") remembered_file_path = some_file_path with open(some_file_path, "w") as some_file: some_file.write("stuff") assert os.path.isfile(some_file_path) assert not os.path.exists(remembered_dir_path) assert not os.path.exists(remembered_file_path) <|code_end|> , generate the next line using the imports in this file: import json import os import yaml import pytest from six import StringIO from lago import utils and context (functions, classes, or occasionally code) from other files: # Path: lago/utils.py # LOGGER = logging.getLogger(__name__) # class TimerException(Exception): # class VectorThread: # class CommandStatus(_CommandStatus): # class RollbackContext(object): # class EggTimer: # class ExceptionTimer(object): # class Flock(object): # class LockFile(object): # class TemporaryDirectory(object): # class LagoException(Exception): # class LagoInitException(LagoException): # class LagoUserException(LagoException): # def _ret_via_queue(func, queue): # def func_vector(target, args_sequence): # def __init__(self, targets): # def start_all(self): # def join_all(self, raise_exceptions=True): # def invoke_in_parallel(func, *args_sequences): # def invoke_different_funcs_in_parallel(*funcs): # def __bool__(self): # def _run_command( # command, # input_data=None, # stdin=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # uuid=None, # **kwargs # ): # def run_command( # command, # input_data=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # **kwargs # ): # def run_interactive_command(command, env=None, **kwargs): # def service_is_enabled(name): # def __init__(self, *args): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def defer(self, func, *args, **kwargs): # def prependDefer(self, func, *args, **kwargs): # def clear(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def elapsed(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def start(self): # def raise_timeout(*_): # def stop(self): # def __init__(self, path, readonly=False, blocking=True): # def acquire(self): # def release(self): # def __init__(self, path, timeout=None, lock_cls=None, **kwargs): # def __enter__(self): # def __exit__(self, *_): # def __init__(self, ignore_errors=True): # def __enter__(self): # def __exit__(self, *_): # def read_nonblocking(file_descriptor): # def json_dump(obj, f): # def deepcopy(original_obj): # def load_virt_stream(virt_fd): # def in_prefix(prefix_class, workdir_class): # def decorator(func): # def wrapper(*args, **kwargs): # def with_logging(func): # def wrapper(prefix, *args, **kwargs): # def add_timestamp_suffix(base_string): # def rotate_dir(base_dir): # def ipv4_to_mac(ip): # def argparse_to_ini(parser, root_section=u'lago', incl_unset=False): # def _add_subparser_to_cp(cp, section, actions, incl_unset): # def run_command_with_validation( # cmd, fail_on_error=True, msg='An error has occurred' # ): # def get_qemu_info(path, backing_chain=False, fail_on_error=True): # def qemu_rebase(target, backing_file, safe=True, fail_on_error=True): # def compress(input_file, block_size, fail_on_error=True): # def cp(input_file, output_file, fail_on_error=True): # def sparse(input_file, input_format, fail_on_error=True): # def get_hash(file_path, checksum='sha1'): # def filter_spec(spec, paths, wildcard='*', separator='/'): # def remove_key(path, spec): # def ver_cmp(ver1, ver2): . Output only the next line.
def test_temporary_directory_should_respect_ignoring_errors_in():
Continue the code snippet: <|code_start|> return ServiceState.MISSING class SystemdContainerService(ServicePlugin): BIN_PATH = '/usr/bin/docker' HOST_BIN_PATH = '/usr/bin/systemctl' def _request_start(self): super()._request_start() ret = self._vm.ssh( [self.BIN_PATH, 'exec vdsmc systemctl start', self._name] ) if ret.code == 0: return ret return self._vm.ssh([self.HOST_BIN_PATH, 'start', self._name]) def _request_stop(self): super()._request_stop() ret = self._vm.ssh( [self.BIN_PATH, 'exec vdsmc systemctl stop', self._name] ) if ret.code == 0: return ret return self._vm.ssh([self.HOST_BIN_PATH, 'stop', self._name]) <|code_end|> . Use current file imports: from lago.plugins.service import ( ServicePlugin, ServiceState, ) and context (classes, functions, or code) from other files: # Path: lago/plugins/service.py # class ServicePlugin(with_metaclass(ABCMeta, Plugin)): # def __init__(self, vm, name): # self._vm = vm # self._name = name # # @abstractmethod # def state(self): # """ # Check the current status of the service # # Returns: # ServiceState: Which state the service is at right now # """ # pass # # @abstractmethod # def _request_start(self): # """ # Low level implementation of the service start request, used by the # `func:start` method # # Returns: # bool: True if the service succeeded to start, False otherwise # """ # pass # # @abstractmethod # def _request_stop(self): # """ # Low level implementation of the service stop request, used by the # `func:stop` method # # Returns: # bool: True if the service succeeded to stop, False otherwise # """ # pass # # @abstractproperty # def BIN_PATH(self): # """ # Path to the binary used to manage services in the vm, will be checked # for existence when trying to decide if the serviece is supported on the # VM (see `func:is_supported`). # # Returns: # str: Full path to the binary insithe the domain # """ # pass # # def exists(self): # return self.state() != ServiceState.MISSING # # def alive(self): # return self.state() == ServiceState.ACTIVE # # def start(self): # state = self.state() # if state == ServiceState.MISSING: # raise RuntimeError('Service %s not present' % self._name) # elif state == ServiceState.ACTIVE: # return # # if self._request_start(): # raise RuntimeError('Failed to start service') # # def stop(self): # state = self.state() # if state == ServiceState.MISSING: # raise RuntimeError('Service %s not present' % self._name) # elif state == ServiceState.INACTIVE: # return # # if self._request_stop(): # raise RuntimeError('Failed to stop service') # # @classmethod # def is_supported(cls, vm): # return vm.ssh(['test', '-e', cls.BIN_PATH]).code == 0 # # class ServiceState(Enum): # #: This state corresponds to a service that is not available in the domain # MISSING = 0 # INACTIVE = 1 # ACTIVE = 2 . Output only the next line.
def state(self):
Predict the next line for this snippet: <|code_start|> print(msg) def info(self, msg): print(msg) class TestLogUtils(object): @pytest.fixture(scope='class') def logger(self): return LoggerMock() def thrower(self, logger): with LogTask('I should throw the exception', logger=logger): raise RuntimeError() def catcher(self, logger): with LogTask('I should catch the exception', logger=logger): try: raise RuntimeError() except RuntimeError: pass def test_log_task(self, logger): def check_raises(): with pytest.raises(RuntimeError): self.thrower(logger) def check_catches(): try: self.catcher(logger) <|code_end|> with the help of current file imports: from lago import utils from lago.log_utils import LogTask import pytest and context from other files: # Path: lago/utils.py # LOGGER = logging.getLogger(__name__) # class TimerException(Exception): # class VectorThread: # class CommandStatus(_CommandStatus): # class RollbackContext(object): # class EggTimer: # class ExceptionTimer(object): # class Flock(object): # class LockFile(object): # class TemporaryDirectory(object): # class LagoException(Exception): # class LagoInitException(LagoException): # class LagoUserException(LagoException): # def _ret_via_queue(func, queue): # def func_vector(target, args_sequence): # def __init__(self, targets): # def start_all(self): # def join_all(self, raise_exceptions=True): # def invoke_in_parallel(func, *args_sequences): # def invoke_different_funcs_in_parallel(*funcs): # def __bool__(self): # def _run_command( # command, # input_data=None, # stdin=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # uuid=None, # **kwargs # ): # def run_command( # command, # input_data=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # **kwargs # ): # def run_interactive_command(command, env=None, **kwargs): # def service_is_enabled(name): # def __init__(self, *args): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def defer(self, func, *args, **kwargs): # def prependDefer(self, func, *args, **kwargs): # def clear(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def elapsed(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def start(self): # def raise_timeout(*_): # def stop(self): # def __init__(self, path, readonly=False, blocking=True): # def acquire(self): # def release(self): # def __init__(self, path, timeout=None, lock_cls=None, **kwargs): # def __enter__(self): # def __exit__(self, *_): # def __init__(self, ignore_errors=True): # def __enter__(self): # def __exit__(self, *_): # def read_nonblocking(file_descriptor): # def json_dump(obj, f): # def deepcopy(original_obj): # def load_virt_stream(virt_fd): # def in_prefix(prefix_class, workdir_class): # def decorator(func): # def wrapper(*args, **kwargs): # def with_logging(func): # def wrapper(prefix, *args, **kwargs): # def add_timestamp_suffix(base_string): # def rotate_dir(base_dir): # def ipv4_to_mac(ip): # def argparse_to_ini(parser, root_section=u'lago', incl_unset=False): # def _add_subparser_to_cp(cp, section, actions, incl_unset): # def run_command_with_validation( # cmd, fail_on_error=True, msg='An error has occurred' # ): # def get_qemu_info(path, backing_chain=False, fail_on_error=True): # def qemu_rebase(target, backing_file, safe=True, fail_on_error=True): # def compress(input_file, block_size, fail_on_error=True): # def cp(input_file, output_file, fail_on_error=True): # def sparse(input_file, input_format, fail_on_error=True): # def get_hash(file_path, checksum='sha1'): # def filter_spec(spec, paths, wildcard='*', separator='/'): # def remove_key(path, spec): # def ver_cmp(ver1, ver2): # # Path: lago/log_utils.py # class LogTask(object): # """ # Context manager for a log task # # Example: # >>> with LogTask('mytask'): # ... pass # """ # # def __init__( # self, # task, # logger=logging, # level='info', # propagate_fail=True, # uuid=None, # ): # self.task = task # self.logger = logger # self.level = level # self.propagate = propagate_fail # if uuid is None: # self.uuid = uuid_m.uuid4() # self.header = self.task # if self.level != 'info': # self.header = ':{0}:{1}:'.format(str(self.uuid), self.task) # # def __enter__(self): # getattr(self.logger, self.level)(START_TASK_TRIGGER_MSG % self.header) # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # if exc_type and self.propagate: # end_log_task(self.header, level='error') # str_tb = ''.join(traceback.format_tb(exc_tb)) # self.logger.debug(str_tb) # return False # else: # getattr(self.logger, # self.level)(END_TASK_TRIGGER_MSG % self.header) , which may contain function names, class names, or code. Output only the next line.
except RuntimeError:
Using the snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function class LoggerMock(object): def debug(self, msg): print(msg) def info(self, msg): print(msg) class TestLogUtils(object): @pytest.fixture(scope='class') def logger(self): return LoggerMock() def thrower(self, logger): with LogTask('I should throw the exception', logger=logger): raise RuntimeError() def catcher(self, logger): with LogTask('I should catch the exception', logger=logger): <|code_end|> , determine the next line of code. You have imports: from lago import utils from lago.log_utils import LogTask import pytest and context (class names, function names, or code) available: # Path: lago/utils.py # LOGGER = logging.getLogger(__name__) # class TimerException(Exception): # class VectorThread: # class CommandStatus(_CommandStatus): # class RollbackContext(object): # class EggTimer: # class ExceptionTimer(object): # class Flock(object): # class LockFile(object): # class TemporaryDirectory(object): # class LagoException(Exception): # class LagoInitException(LagoException): # class LagoUserException(LagoException): # def _ret_via_queue(func, queue): # def func_vector(target, args_sequence): # def __init__(self, targets): # def start_all(self): # def join_all(self, raise_exceptions=True): # def invoke_in_parallel(func, *args_sequences): # def invoke_different_funcs_in_parallel(*funcs): # def __bool__(self): # def _run_command( # command, # input_data=None, # stdin=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # uuid=None, # **kwargs # ): # def run_command( # command, # input_data=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # **kwargs # ): # def run_interactive_command(command, env=None, **kwargs): # def service_is_enabled(name): # def __init__(self, *args): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def defer(self, func, *args, **kwargs): # def prependDefer(self, func, *args, **kwargs): # def clear(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def elapsed(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def start(self): # def raise_timeout(*_): # def stop(self): # def __init__(self, path, readonly=False, blocking=True): # def acquire(self): # def release(self): # def __init__(self, path, timeout=None, lock_cls=None, **kwargs): # def __enter__(self): # def __exit__(self, *_): # def __init__(self, ignore_errors=True): # def __enter__(self): # def __exit__(self, *_): # def read_nonblocking(file_descriptor): # def json_dump(obj, f): # def deepcopy(original_obj): # def load_virt_stream(virt_fd): # def in_prefix(prefix_class, workdir_class): # def decorator(func): # def wrapper(*args, **kwargs): # def with_logging(func): # def wrapper(prefix, *args, **kwargs): # def add_timestamp_suffix(base_string): # def rotate_dir(base_dir): # def ipv4_to_mac(ip): # def argparse_to_ini(parser, root_section=u'lago', incl_unset=False): # def _add_subparser_to_cp(cp, section, actions, incl_unset): # def run_command_with_validation( # cmd, fail_on_error=True, msg='An error has occurred' # ): # def get_qemu_info(path, backing_chain=False, fail_on_error=True): # def qemu_rebase(target, backing_file, safe=True, fail_on_error=True): # def compress(input_file, block_size, fail_on_error=True): # def cp(input_file, output_file, fail_on_error=True): # def sparse(input_file, input_format, fail_on_error=True): # def get_hash(file_path, checksum='sha1'): # def filter_spec(spec, paths, wildcard='*', separator='/'): # def remove_key(path, spec): # def ver_cmp(ver1, ver2): # # Path: lago/log_utils.py # class LogTask(object): # """ # Context manager for a log task # # Example: # >>> with LogTask('mytask'): # ... pass # """ # # def __init__( # self, # task, # logger=logging, # level='info', # propagate_fail=True, # uuid=None, # ): # self.task = task # self.logger = logger # self.level = level # self.propagate = propagate_fail # if uuid is None: # self.uuid = uuid_m.uuid4() # self.header = self.task # if self.level != 'info': # self.header = ':{0}:{1}:'.format(str(self.uuid), self.task) # # def __enter__(self): # getattr(self.logger, self.level)(START_TASK_TRIGGER_MSG % self.header) # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # if exc_type and self.propagate: # end_log_task(self.header, level='error') # str_tb = ''.join(traceback.format_tb(exc_tb)) # self.logger.debug(str_tb) # return False # else: # getattr(self.logger, # self.level)(END_TASK_TRIGGER_MSG % self.header) . Output only the next line.
try:
Here is a snippet: <|code_start|># it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import _BRCTL = ['sudo', 'brctl'] _IP = ['sudo', 'ip'] def _brctl(command, *args): ret, out, err = utils.run_command(_BRCTL + [command] + list(args)) if ret: raise RuntimeError( 'brctl %s failed\nrc: %d\n\nout:\n%s\n\nerr:\n%s' % (command, ret, out, err) ) <|code_end|> . Write the next line using the current file imports: from lago import utils and context from other files: # Path: lago/utils.py # LOGGER = logging.getLogger(__name__) # class TimerException(Exception): # class VectorThread: # class CommandStatus(_CommandStatus): # class RollbackContext(object): # class EggTimer: # class ExceptionTimer(object): # class Flock(object): # class LockFile(object): # class TemporaryDirectory(object): # class LagoException(Exception): # class LagoInitException(LagoException): # class LagoUserException(LagoException): # def _ret_via_queue(func, queue): # def func_vector(target, args_sequence): # def __init__(self, targets): # def start_all(self): # def join_all(self, raise_exceptions=True): # def invoke_in_parallel(func, *args_sequences): # def invoke_different_funcs_in_parallel(*funcs): # def __bool__(self): # def _run_command( # command, # input_data=None, # stdin=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # uuid=None, # **kwargs # ): # def run_command( # command, # input_data=None, # out_pipe=subprocess.PIPE, # err_pipe=subprocess.PIPE, # env=None, # **kwargs # ): # def run_interactive_command(command, env=None, **kwargs): # def service_is_enabled(name): # def __init__(self, *args): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def defer(self, func, *args, **kwargs): # def prependDefer(self, func, *args, **kwargs): # def clear(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def elapsed(self): # def __init__(self, timeout): # def __enter__(self): # def __exit__(self, *_): # def start(self): # def raise_timeout(*_): # def stop(self): # def __init__(self, path, readonly=False, blocking=True): # def acquire(self): # def release(self): # def __init__(self, path, timeout=None, lock_cls=None, **kwargs): # def __enter__(self): # def __exit__(self, *_): # def __init__(self, ignore_errors=True): # def __enter__(self): # def __exit__(self, *_): # def read_nonblocking(file_descriptor): # def json_dump(obj, f): # def deepcopy(original_obj): # def load_virt_stream(virt_fd): # def in_prefix(prefix_class, workdir_class): # def decorator(func): # def wrapper(*args, **kwargs): # def with_logging(func): # def wrapper(prefix, *args, **kwargs): # def add_timestamp_suffix(base_string): # def rotate_dir(base_dir): # def ipv4_to_mac(ip): # def argparse_to_ini(parser, root_section=u'lago', incl_unset=False): # def _add_subparser_to_cp(cp, section, actions, incl_unset): # def run_command_with_validation( # cmd, fail_on_error=True, msg='An error has occurred' # ): # def get_qemu_info(path, backing_chain=False, fail_on_error=True): # def qemu_rebase(target, backing_file, safe=True, fail_on_error=True): # def compress(input_file, block_size, fail_on_error=True): # def cp(input_file, output_file, fail_on_error=True): # def sparse(input_file, input_format, fail_on_error=True): # def get_hash(file_path, checksum='sha1'): # def filter_spec(spec, paths, wildcard='*', separator='/'): # def remove_key(path, spec): # def ver_cmp(ver1, ver2): , which may include functions, classes, or code. Output only the next line.
return ret, out, err
Based on the snippet: <|code_start|> with pytest.raises(AssertionError): my_prefix.assert_called_with() my_prefix.initialize.assert_called_with() my_prefix_instance = my_workdir.initialize(prefix_name=prefix_name) my_prefix.assert_called_with(my_workdir.join(prefix_name)) my_prefix_instance.initialize.assert_called_with() mock_makedirs.assert_called_with(my_workdir.join()) mock_exists.assert_called_with(my_workdir.join()) mock_set_current.assert_called_with(prefix_name) mock_load.assert_called_with() def test_load_skip_loaded_workdir(self, mock_workdir): mock_workdir.loaded = True mock_workdir.load = lago.workdir.Workdir.load assert mock_workdir.load(mock_workdir) is None assert not mock_workdir.method_calls def test_load_empty_workdir_throws_exception( self, tmpdir, mock_workdir, monkeypatch, ): mock_workdir.loaded = False mock_workdir.load = lago.workdir.Workdir.load mock_walk = mock_patch( monkeypatch=monkeypatch, <|code_end|> , predict the immediate next line with the help of imports: import functools import os import shutil import pytest import mock import lago.workdir import lago.prefix from collections import OrderedDict from lago.utils import LagoUserException from utils import generate_workdir_params and context (classes, functions, sometimes code) from other files: # Path: lago/utils.py # class LagoUserException(LagoException): # pass . Output only the next line.
topatch=os,
Given the following code snippet before the placeholder: <|code_start|> template.write(content) def add_base(self, content): self.add(content=content, name='sysprep-base.j2') @fixture def factory(tmpdir): return TemplateFactory(dst=str(tmpdir)) class TestSysprep(object): @pytest.mark.parametrize( 'distro,templates,expected', [ ('distro_a', ['base'], 'base'), ('distro_a', ['base', 'distro_a'], 'distro_a'), ('distro_b', ['base', 'distro_a'], 'base') ] ) def test_render_template_loads_expected( self, factory, distro, templates, expected ): for template in templates: factory.add('sysprep-{0}.j2'.format(template), 'empty template') filename = sysprep._render_template( distro=distro, loader=factory.loader ) with open(filename, 'r') as generated: lines = [line.strip() for line in generated.readlines()] <|code_end|> , predict the next line using imports from the current file: import pytest import jinja2 import os from pytest import fixture from lago import sysprep and context including class names, function names, and sometimes code from other files: # Path: lago/sysprep.py # def sysprep(disk, distro, loader=None, backend='direct', **kwargs): # """ # Run virt-sysprep on the ``disk``, commands are built from the distro # specific template and arguments passed in ``kwargs``. If no template is # available it will default to ``sysprep-base.j2``. # # Args: # disk(str): path to disk # distro(str): distro to render template for # loader(jinja2.BaseLoader): Jinja2 template loader, if not passed, # will search Lago's package. # backend(str): libguestfs backend to use # **kwargs(dict): environment variables for Jinja2 template # # Returns: # None # # Raises: # RuntimeError: On virt-sysprep none 0 exit code. # """ # # if loader is None: # loader = PackageLoader('lago', 'templates') # sysprep_file = _render_template(distro, loader=loader, **kwargs) # # cmd = ['virt-sysprep', '-a', disk] # cmd.extend(['--commands-from-file', sysprep_file]) # # env = os.environ.copy() # if 'LIBGUESTFS_BACKEND' not in env: # env['LIBGUESTFS_BACKEND'] = backend # # ret = utils.run_command(cmd, env=env) # if ret: # raise RuntimeError( # 'Failed to bootstrap %s\ncommand:%s\nstdout:%s\nstderr:%s' % ( # disk, # ' '.join('"%s"' % elem for elem in cmd), # ret.out, # ret.err, # ) # ) . Output only the next line.
assert lines[0].strip() == '# sysprep-{0}.j2'.format(expected)
Based on the snippet: <|code_start|> disk_path, disk_root, retries=retries, wait=0 ) as conn: assert call.mount_ro(disk_root, '/') in conn.mock_calls assert call.add_drive_ro(disk_path) in conn.mock_calls assert conn.mount_ro.call_count == retries assert conn.umount.call_count == 1 assert conn.add_drive_ro.call_count == retries assert conn.shutdown.call_count == retries assert conn.close.call_count == retries @pytest.mark.parametrize( 'disk_path,disk_root', [('/path/to/file.qcow', '/dev/sda')] ) @pytest.mark.parametrize('retries', [1, 3]) def test_guestfs_conn_mount_ro_retries_raises( self, mock_gfs, disk_path, disk_root, retries ): side_effects = [RuntimeError()] * (retries) mock_gfs.return_value.mount_ro.side_effect = side_effects with patch('lago.guestfs_tools.find_rootfs') as mock_rootfs: mock_rootfs.return_value = disk_root with pytest.raises(GuestFSError): with guestfs_tools.guestfs_conn_mount_ro( disk_path, disk_root, retries=retries, wait=0 ): pass assert mock_gfs.return_value.mount_ro.call_count == retries assert mock_gfs.return_value.umount.call_count == 0 <|code_end|> , predict the immediate next line with the help of imports: import pytest from mock import call, patch from lago import guestfs_tools from lago.plugins.vm import ExtractPathNoPathError from lago.guestfs_tools import GuestFSError from random import shuffle and context (classes, functions, sometimes code) from other files: # Path: lago/guestfs_tools.py # LOGGER = logging.getLogger(__name__) # class GuestFSError(LagoException): # def guestfs_conn_ro(disk): # def guestfs_conn_mount_ro(disk_path, disk_root, retries=5, wait=1): # def find_rootfs(conn, disk_root): # def extract_paths(disk_path, disk_root, paths, ignore_nopath): # def _copy_path(conn, guest_path, host_path): # # Path: lago/plugins/vm.py # class ExtractPathNoPathError(VMError): # def __init__(self, err): # super().__init__('Failed to extract files: {}'.format(err)) # # Path: lago/guestfs_tools.py # class GuestFSError(LagoException): # pass . Output only the next line.
assert mock_gfs.return_value.add_drive_ro.call_count == retries
Continue the code snippet: <|code_start|> @pytest.mark.parametrize( 'disk_path,disk_root', [('/path/to/file.qcow', '/dev/sda')] ) def test_guestfs_conn_mount_ro(self, mock_gfs, disk_path, disk_root): with patch('lago.guestfs_tools.find_rootfs') as mock_rootfs: mock_rootfs.return_value = disk_root with guestfs_tools.guestfs_conn_mount_ro( disk_path, disk_root ) as conn: assert call.mount_ro(disk_root, '/') in conn.mock_calls assert call.add_drive_ro(disk_path) in conn.mock_calls conn.mount_ro.assert_called_once() conn.add_drive_ro.assert_called_once() mock_rootfs.assert_called_once() mock_gfs.return_value.umount.assert_called_once() @pytest.mark.parametrize( 'disk_path,disk_root', [('/path/to/file.qcow', '/dev/sda')] ) @pytest.mark.parametrize('retries', [1, 3, 13]) def test_guestfs_conn_mount_ro_retries( self, mock_gfs, disk_path, disk_root, retries ): side_effects = [RuntimeError()] * (retries - 1) side_effects.append(None) mock_gfs.return_value.mount_ro.side_effect = side_effects with patch('lago.guestfs_tools.find_rootfs') as mock_rootfs: mock_rootfs.return_value = disk_root with guestfs_tools.guestfs_conn_mount_ro( <|code_end|> . Use current file imports: import pytest from mock import call, patch from lago import guestfs_tools from lago.plugins.vm import ExtractPathNoPathError from lago.guestfs_tools import GuestFSError from random import shuffle and context (classes, functions, or code) from other files: # Path: lago/guestfs_tools.py # LOGGER = logging.getLogger(__name__) # class GuestFSError(LagoException): # def guestfs_conn_ro(disk): # def guestfs_conn_mount_ro(disk_path, disk_root, retries=5, wait=1): # def find_rootfs(conn, disk_root): # def extract_paths(disk_path, disk_root, paths, ignore_nopath): # def _copy_path(conn, guest_path, host_path): # # Path: lago/plugins/vm.py # class ExtractPathNoPathError(VMError): # def __init__(self, err): # super().__init__('Failed to extract files: {}'.format(err)) # # Path: lago/guestfs_tools.py # class GuestFSError(LagoException): # pass . Output only the next line.
disk_path, disk_root, retries=retries, wait=0
Based on the snippet: <|code_start|> def is_file(self): pass def is_dir(self): pass def copy_out(self): pass @pytest.fixture def mock_gfs(): with patch( 'lago.guestfs_tools.guestfs.GuestFS', spec=MockGuestFS ) as mocked: yield mocked @pytest.fixture def mock_gfs_fs(mock_gfs): mock_gfs.return_value.inspect_os.return_value = ['/dev/sda1'] return mock_gfs.return_value class TestGuestFSTools(object): @pytest.mark.parametrize( 'filesystems,root_device', [ ({ '/dev/sdb': '' }, '/dev/sdb'), ( <|code_end|> , predict the immediate next line with the help of imports: import pytest from mock import call, patch from lago import guestfs_tools from lago.plugins.vm import ExtractPathNoPathError from lago.guestfs_tools import GuestFSError from random import shuffle and context (classes, functions, sometimes code) from other files: # Path: lago/guestfs_tools.py # LOGGER = logging.getLogger(__name__) # class GuestFSError(LagoException): # def guestfs_conn_ro(disk): # def guestfs_conn_mount_ro(disk_path, disk_root, retries=5, wait=1): # def find_rootfs(conn, disk_root): # def extract_paths(disk_path, disk_root, paths, ignore_nopath): # def _copy_path(conn, guest_path, host_path): # # Path: lago/plugins/vm.py # class ExtractPathNoPathError(VMError): # def __init__(self, err): # super().__init__('Failed to extract files: {}'.format(err)) # # Path: lago/guestfs_tools.py # class GuestFSError(LagoException): # pass . Output only the next line.
{
Continue the code snippet: <|code_start|> """ <cpu> <arch>{arch}</arch> <model>{model}</model> <vendor>{vendor}</vendor> </cpu> """.format(arch=arch, model=model, vendor=vendor) ) def test_generate_topology(self): _xml = """ <topology sockets="{vcpu_num}" cores="{cores}" threads="{threads}" /> """ combs = [ { 'vcpu_num': tup[0], 'cores': tup[1], 'threads': tup[2] } for tup in permutations(range(1, 4), 3) ] empty_cpu = cpu.CPU(spec={'memory': 2048}, host_cpu=None) for comb in combs: self.assertXmlEquivalentOutputs( ET.tostring(empty_cpu.generate_topology(**comb)), _xml.format(**comb) ) def test_generate_host_passthrough(self): _xml = """ <|code_end|> . Use current file imports: from itertools import permutations from xmlunittest import XmlTestCase from lago.providers.libvirt import cpu from lago.utils import LagoInitException import lxml.etree as ET import pytest import os and context (classes, functions, or code) from other files: # Path: lago/providers/libvirt/cpu.py # LOGGER = logging.getLogger(__name__) # class CPU(object): # class LibvirtCPU(object): # def __init__(self, spec, host_cpu): # def __iter__(self): # def validate(self): # def cpu_xml(self): # def vcpu_xml(self): # def model(self): # def vendor(self): # def generate_cpu_xml(self): # def generate_vcpu_xml(self, vcpu_num): # def generate_host_passthrough(self, vcpu_num): # def generate_custom(self, cpu, vcpu_num, fill_topology): # def generate_exact(self, model, vcpu_num, host_cpu): # def generate_topology(self, vcpu_num, cores=1, threads=1): # def generate_numa(self, vcpu_num): # def generate_vcpu(self, vcpu_num): # def generate_feature(self, name, policy='require'): # def get_cpu_vendor(cls, family, arch='x86'): # def get_cpu_props(cls, family, arch='x86'): # def get_cpus_by_arch(cls, arch): # def create_xml_map(cpu_map_index_xml, cpu_map_dir): # # Path: lago/utils.py # class LagoInitException(LagoException): # pass . Output only the next line.
<cpu mode="host-passthrough">
Here is a snippet: <|code_start|> _numa2 = """ <numa> <cell cpus="0" id="0" memory="1023" unit="MiB"/> <cell cpus="1" id="1" memory="1023" unit="MiB"/> </numa> """ empty_cpu = cpu.CPU(spec={'memory': 2047}, host_cpu=None) vcpu_num = 2 self.assertXmlEquivalentOutputs( ET.tostring(empty_cpu.generate_host_passthrough(vcpu_num)), _xml.format(vcpu_num, _numa2) ) _numa3 = """ <numa> <cell cpus="0" id="0" memory="682" unit="MiB"/> <cell cpus="1" id="1" memory="682" unit="MiB"/> <cell cpus="2" id="2" memory="682" unit="MiB"/> </numa> """ vcpu_num = 3 self.assertXmlEquivalentOutputs( ET.tostring(empty_cpu.generate_host_passthrough(vcpu_num)), _xml.format(vcpu_num, _numa3) ) _numa8 = """ <numa> <cell cpus="0-3" id="0" memory="2048" unit="MiB"/> <|code_end|> . Write the next line using the current file imports: from itertools import permutations from xmlunittest import XmlTestCase from lago.providers.libvirt import cpu from lago.utils import LagoInitException import lxml.etree as ET import pytest import os and context from other files: # Path: lago/providers/libvirt/cpu.py # LOGGER = logging.getLogger(__name__) # class CPU(object): # class LibvirtCPU(object): # def __init__(self, spec, host_cpu): # def __iter__(self): # def validate(self): # def cpu_xml(self): # def vcpu_xml(self): # def model(self): # def vendor(self): # def generate_cpu_xml(self): # def generate_vcpu_xml(self, vcpu_num): # def generate_host_passthrough(self, vcpu_num): # def generate_custom(self, cpu, vcpu_num, fill_topology): # def generate_exact(self, model, vcpu_num, host_cpu): # def generate_topology(self, vcpu_num, cores=1, threads=1): # def generate_numa(self, vcpu_num): # def generate_vcpu(self, vcpu_num): # def generate_feature(self, name, policy='require'): # def get_cpu_vendor(cls, family, arch='x86'): # def get_cpu_props(cls, family, arch='x86'): # def get_cpus_by_arch(cls, arch): # def create_xml_map(cpu_map_index_xml, cpu_map_dir): # # Path: lago/utils.py # class LagoInitException(LagoException): # pass , which may include functions, classes, or code. Output only the next line.
<cell cpus="4-7" id="1" memory="2048" unit="MiB"/>
Given snippet: <|code_start|> CL_ITEMS = [ dict(id="A", name={"en": "Average of observations through period"}), dict(id="B", name={"en": "Beginning of period"}), <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from pandasdmx import message from pandasdmx.model import Agency, Annotation, Code, Codelist and context: # Path: pandasdmx/message.py # def _summarize(obj, fields): # def __repr__(self): # def compare(self, other, strict=True): # def compare(self, other, strict=True): # def to_pandas(self, *args, **kwargs): # def __str__(self): # def __repr__(self): # def compare(self, other, strict=True): # def compare(self, other, strict=True): # def add(self, obj: model.IdentifiableArtefact): # def get( # self, obj_or_id: Union[str, model.IdentifiableArtefact] # ) -> Optional[model.IdentifiableArtefact]: # def objects(self, cls): # def __contains__(self, item): # def __repr__(self): # def structure(self): # def __repr__(self): # def compare(self, other, strict=True): # class Header(BaseModel): # class Footer(BaseModel): # class Message(BaseModel): # class Config: # class ErrorMessage(Message): # class StructureMessage(Message): # class DataMessage(Message): # # Path: pandasdmx/model.py # class Agency(Organisation): # pass # # class Annotation(BaseModel): # #: Can be used to disambiguate multiple annotations for one AnnotableArtefact. # id: Optional[str] = None # #: Title, used to identify an annotation. # title: Optional[str] = None # #: Specifies how the annotation is processed. # type: Optional[str] = None # #: A link to external descriptive text. # url: Optional[str] = None # # #: Content of the annotation. # text: InternationalString = InternationalString() # # class Code(Item["Code"]): # """SDMX-IM Code.""" # # class Codelist(ItemScheme[Code]): # _Item = Code which might include code, classes, or functions. Output only the next line.
dict(id="B1", name={"en": "Child code of B"}),
Given snippet: <|code_start|> CL_ITEMS = [ dict(id="A", name={"en": "Average of observations through period"}), dict(id="B", name={"en": "Beginning of period"}), <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from pandasdmx import message from pandasdmx.model import Agency, Annotation, Code, Codelist and context: # Path: pandasdmx/message.py # def _summarize(obj, fields): # def __repr__(self): # def compare(self, other, strict=True): # def compare(self, other, strict=True): # def to_pandas(self, *args, **kwargs): # def __str__(self): # def __repr__(self): # def compare(self, other, strict=True): # def compare(self, other, strict=True): # def add(self, obj: model.IdentifiableArtefact): # def get( # self, obj_or_id: Union[str, model.IdentifiableArtefact] # ) -> Optional[model.IdentifiableArtefact]: # def objects(self, cls): # def __contains__(self, item): # def __repr__(self): # def structure(self): # def __repr__(self): # def compare(self, other, strict=True): # class Header(BaseModel): # class Footer(BaseModel): # class Message(BaseModel): # class Config: # class ErrorMessage(Message): # class StructureMessage(Message): # class DataMessage(Message): # # Path: pandasdmx/model.py # class Agency(Organisation): # pass # # class Annotation(BaseModel): # #: Can be used to disambiguate multiple annotations for one AnnotableArtefact. # id: Optional[str] = None # #: Title, used to identify an annotation. # title: Optional[str] = None # #: Specifies how the annotation is processed. # type: Optional[str] = None # #: A link to external descriptive text. # url: Optional[str] = None # # #: Content of the annotation. # text: InternationalString = InternationalString() # # class Code(Item["Code"]): # """SDMX-IM Code.""" # # class Codelist(ItemScheme[Code]): # _Item = Code which might include code, classes, or functions. Output only the next line.
dict(id="B1", name={"en": "Child code of B"}),
Continue the code snippet: <|code_start|> CL_ITEMS = [ dict(id="A", name={"en": "Average of observations through period"}), dict(id="B", name={"en": "Beginning of period"}), dict(id="B1", name={"en": "Child code of B"}), ] <|code_end|> . Use current file imports: import pytest from pandasdmx import message from pandasdmx.model import Agency, Annotation, Code, Codelist and context (classes, functions, or code) from other files: # Path: pandasdmx/message.py # def _summarize(obj, fields): # def __repr__(self): # def compare(self, other, strict=True): # def compare(self, other, strict=True): # def to_pandas(self, *args, **kwargs): # def __str__(self): # def __repr__(self): # def compare(self, other, strict=True): # def compare(self, other, strict=True): # def add(self, obj: model.IdentifiableArtefact): # def get( # self, obj_or_id: Union[str, model.IdentifiableArtefact] # ) -> Optional[model.IdentifiableArtefact]: # def objects(self, cls): # def __contains__(self, item): # def __repr__(self): # def structure(self): # def __repr__(self): # def compare(self, other, strict=True): # class Header(BaseModel): # class Footer(BaseModel): # class Message(BaseModel): # class Config: # class ErrorMessage(Message): # class StructureMessage(Message): # class DataMessage(Message): # # Path: pandasdmx/model.py # class Agency(Organisation): # pass # # class Annotation(BaseModel): # #: Can be used to disambiguate multiple annotations for one AnnotableArtefact. # id: Optional[str] = None # #: Title, used to identify an annotation. # title: Optional[str] = None # #: Specifies how the annotation is processed. # type: Optional[str] = None # #: A link to external descriptive text. # url: Optional[str] = None # # #: Content of the annotation. # text: InternationalString = InternationalString() # # class Code(Item["Code"]): # """SDMX-IM Code.""" # # class Codelist(ItemScheme[Code]): # _Item = Code . Output only the next line.
@pytest.fixture
Next line prediction: <|code_start|> # Regular expression for URNs URN = re.compile( r"urn:sdmx:org\.sdmx\.infomodel" r"\.(?P<package>[^\.]*)" r"\.(?P<class>[^=]*)=((?P<agency>[^:]*):)?" r"(?P<id>[^\(\.]*)(\((?P<version>[\d\.]*)\))?" <|code_end|> . Use current file imports: (import re from typing import Dict from pandasdmx.model import PACKAGE, MaintainableArtefact) and context including class names, function names, or small code snippets from other files: # Path: pandasdmx/model.py # PACKAGE = dict() # # class MaintainableArtefact(VersionableArtefact): # #: True if the object is final; otherwise it is in a draft state. # is_final: Optional[bool] = None # #: :obj:`True` if the content of the object is held externally; i.e., not # #: the current :class:`Message`. # is_external_reference: Optional[bool] = None # #: URL of an SDMX-compliant web service from which the object can be # #: retrieved. # service_url: Optional[str] = None # #: URL of an SDMX-ML document containing the object. # structure_url: Optional[str] = None # #: Association to the Agency responsible for maintaining the object. # maintainer: Optional["Agency"] = None # # def __init__(self, **kwargs): # super().__init__(**kwargs) # try: # if self.maintainer and self.maintainer.id != self.urn_group["agency"]: # raise ValueError( # f"Maintainer {self.maintainer} does not match URN {self.urn}" # ) # else: # self.maintainer = Agency(id=self.urn_group["agency"]) # except KeyError: # pass # # def compare(self, other, strict=True): # """Return :obj:`True` if `self` is the same as `other`. # # Two MaintainableArtefacts are the same if: # # - :meth:`.VersionableArtefact.compare` is :obj:`True`, and # - they have the same :attr:`maintainer`. # # Parameters # ---------- # strict : bool, optional # Passed to :func:`.compare` and :meth:`.VersionableArtefact.compare`. # """ # return super().compare(other, strict) and compare( # "maintainer", self, other, strict # ) # # def _repr_kw(self): # return ChainMap( # super()._repr_kw(), # dict(maint=f"{self.maintainer}:" if self.maintainer else ""), # ) # # def __repr__(self): # return "<{cls} {maint}{id}{version}{name}>".format(**self._repr_kw()) . Output only the next line.
r"(\.(?P<item_id>.*))?"
Given the code snippet: <|code_start|> # Regular expression for URNs URN = re.compile( r"urn:sdmx:org\.sdmx\.infomodel" r"\.(?P<package>[^\.]*)" r"\.(?P<class>[^=]*)=((?P<agency>[^:]*):)?" r"(?P<id>[^\(\.]*)(\((?P<version>[\d\.]*)\))?" r"(\.(?P<item_id>.*))?" ) _BASE = ( "urn:sdmx:org.sdmx.infomodel.{package}.{obj.__class__.__name__}=" <|code_end|> , generate the next line using the imports in this file: import re from typing import Dict from pandasdmx.model import PACKAGE, MaintainableArtefact and context (functions, classes, or occasionally code) from other files: # Path: pandasdmx/model.py # PACKAGE = dict() # # class MaintainableArtefact(VersionableArtefact): # #: True if the object is final; otherwise it is in a draft state. # is_final: Optional[bool] = None # #: :obj:`True` if the content of the object is held externally; i.e., not # #: the current :class:`Message`. # is_external_reference: Optional[bool] = None # #: URL of an SDMX-compliant web service from which the object can be # #: retrieved. # service_url: Optional[str] = None # #: URL of an SDMX-ML document containing the object. # structure_url: Optional[str] = None # #: Association to the Agency responsible for maintaining the object. # maintainer: Optional["Agency"] = None # # def __init__(self, **kwargs): # super().__init__(**kwargs) # try: # if self.maintainer and self.maintainer.id != self.urn_group["agency"]: # raise ValueError( # f"Maintainer {self.maintainer} does not match URN {self.urn}" # ) # else: # self.maintainer = Agency(id=self.urn_group["agency"]) # except KeyError: # pass # # def compare(self, other, strict=True): # """Return :obj:`True` if `self` is the same as `other`. # # Two MaintainableArtefacts are the same if: # # - :meth:`.VersionableArtefact.compare` is :obj:`True`, and # - they have the same :attr:`maintainer`. # # Parameters # ---------- # strict : bool, optional # Passed to :func:`.compare` and :meth:`.VersionableArtefact.compare`. # """ # return super().compare(other, strict) and compare( # "maintainer", self, other, strict # ) # # def _repr_kw(self): # return ChainMap( # super()._repr_kw(), # dict(maint=f"{self.maintainer}:" if self.maintainer else ""), # ) # # def __repr__(self): # return "<{cls} {maint}{id}{version}{name}>".format(**self._repr_kw()) . Output only the next line.
"{ma.maintainer.id}:{ma.id}({ma.version}){extra_id}"
Predict the next line for this snippet: <|code_start|> @pytest.mark.xfail(raises=RuntimeError, match="sdmx.format.protobuf_pb2 missing") def test_codelist(caplog, codelist): msg = StructureMessage() <|code_end|> with the help of current file imports: import logging import pytest from pandasdmx.message import StructureMessage from pandasdmx.writer.protobuf import write as to_protobuf and context from other files: # Path: pandasdmx/message.py # class StructureMessage(Message): # #: Collection of :class:`.Categorisation`. # categorisation: DictLike[str, model.Categorisation] = dictlike_field() # #: Collection of :class:`.CategoryScheme`. # category_scheme: DictLike[str, model.CategoryScheme] = dictlike_field() # #: Collection of :class:`.Codelist`. # codelist: DictLike[str, model.Codelist] = dictlike_field() # #: Collection of :class:`.ConceptScheme`. # concept_scheme: DictLike[str, model.ConceptScheme] = dictlike_field() # #: Collection of :class:`.ContentConstraint`. # constraint: DictLike[str, model.ContentConstraint] = dictlike_field() # #: Collection of :class:`.DataflowDefinition`. # dataflow: DictLike[str, model.DataflowDefinition] = dictlike_field() # #: Collection of :class:`.DataStructureDefinition`. # structure: DictLike[str, model.DataStructureDefinition] = dictlike_field() # #: Collection of :class:`.AgencyScheme`. # organisation_scheme: DictLike[str, model.AgencyScheme] = dictlike_field() # #: Collection of :class:`.ProvisionAgreement`. # provisionagreement: DictLike[str, model.ProvisionAgreement] = dictlike_field() # # def compare(self, other, strict=True): # """Return :obj:`True` if `self` is the same as `other`. # # Two StructureMessages compare equal if :meth:`.DictLike.compare` is :obj:`True` # for each of the object collection attributes. # # Parameters # ---------- # strict : bool, optional # Passed to :meth:`.DictLike.compare`. # """ # return super().compare(other, strict) and all( # getattr(self, f).compare(getattr(other, f), strict) # for f in direct_fields(self.__class__).keys() # ) # # def add(self, obj: model.IdentifiableArtefact): # """Add `obj` to the StructureMessage.""" # for field, field_info in direct_fields(self.__class__).items(): # # NB for some reason mypy complains here, but not in __contains__(), below # if isinstance( # obj, get_args(field_info.outer_type_)[1], # type: ignore [attr-defined] # ): # getattr(self, field)[obj.id] = obj # return # raise TypeError(type(obj)) # # def get( # self, obj_or_id: Union[str, model.IdentifiableArtefact] # ) -> Optional[model.IdentifiableArtefact]: # """Retrieve `obj_or_id` from the StructureMessage. # # Parameters # ---------- # obj_or_id : str or .IdentifiableArtefact # If an IdentifiableArtefact, return an object of the same class and # :attr:`~.IdentifiableArtefact.id`; if :class:`str`, an object with this ID. # # Returns # ------- # .IdentifiableArtefact # with the given ID and possibly class. # None # if there is no match. # # Raises # ------ # ValueError # if `obj_or_id` is a string and there are ≥2 objects (of different classes) # with the same ID. # """ # id = ( # obj_or_id.id # if isinstance(obj_or_id, model.IdentifiableArtefact) # else obj_or_id # ) # # candidates: List[model.IdentifiableArtefact] = list( # filter( # None, # map( # lambda f: getattr(self, f).get(id), # direct_fields(self.__class__).keys(), # ), # ) # ) # # if len(candidates) > 1: # raise ValueError(f"ambiguous; {repr(obj_or_id)} matches {repr(candidates)}") # # return candidates[0] if len(candidates) == 1 else None # # def objects(self, cls): # """Get a reference to the attribute for objects of type `cls`. # # For example, if `cls` is the class :class:`DataStructureDefinition` (not an # instance), return a reference to :attr:`structure`. # """ # for name, info in direct_fields(self.__class__).items(): # if issubclass(cls, info.sub_fields[0].type_): # return getattr(self, name) # raise TypeError(cls) # # def __contains__(self, item): # """Return :obj:`True` if `item` is in the StructureMessage.""" # for field, field_info in direct_fields(self.__class__).items(): # if isinstance(item, get_args(field_info.outer_type_)[1]): # return item in getattr(self, field).values() # raise TypeError(f"StructureMessage has no collection of {type(item)}") # # def __repr__(self): # """String representation.""" # lines = [super().__repr__()] # # # StructureMessage contents # for attr in self.__dict__.values(): # if isinstance(attr, DictLike) and attr: # lines.append(summarize_dictlike(attr)) # # return "\n ".join(lines) # # Path: pandasdmx/writer/protobuf.py # def write(obj, *args, **kwargs): # """Convert an SDMX *obj* to protobuf string.""" # return _write(obj, *args, **kwargs).SerializeToString() , which may contain function names, class names, or code. Output only the next line.
msg.codelist[codelist.id] = codelist
Predict the next line after this snippet: <|code_start|> @pytest.mark.xfail(raises=RuntimeError, match="sdmx.format.protobuf_pb2 missing") def test_codelist(caplog, codelist): msg = StructureMessage() msg.codelist[codelist.id] = codelist <|code_end|> using the current file's imports: import logging import pytest from pandasdmx.message import StructureMessage from pandasdmx.writer.protobuf import write as to_protobuf and any relevant context from other files: # Path: pandasdmx/message.py # class StructureMessage(Message): # #: Collection of :class:`.Categorisation`. # categorisation: DictLike[str, model.Categorisation] = dictlike_field() # #: Collection of :class:`.CategoryScheme`. # category_scheme: DictLike[str, model.CategoryScheme] = dictlike_field() # #: Collection of :class:`.Codelist`. # codelist: DictLike[str, model.Codelist] = dictlike_field() # #: Collection of :class:`.ConceptScheme`. # concept_scheme: DictLike[str, model.ConceptScheme] = dictlike_field() # #: Collection of :class:`.ContentConstraint`. # constraint: DictLike[str, model.ContentConstraint] = dictlike_field() # #: Collection of :class:`.DataflowDefinition`. # dataflow: DictLike[str, model.DataflowDefinition] = dictlike_field() # #: Collection of :class:`.DataStructureDefinition`. # structure: DictLike[str, model.DataStructureDefinition] = dictlike_field() # #: Collection of :class:`.AgencyScheme`. # organisation_scheme: DictLike[str, model.AgencyScheme] = dictlike_field() # #: Collection of :class:`.ProvisionAgreement`. # provisionagreement: DictLike[str, model.ProvisionAgreement] = dictlike_field() # # def compare(self, other, strict=True): # """Return :obj:`True` if `self` is the same as `other`. # # Two StructureMessages compare equal if :meth:`.DictLike.compare` is :obj:`True` # for each of the object collection attributes. # # Parameters # ---------- # strict : bool, optional # Passed to :meth:`.DictLike.compare`. # """ # return super().compare(other, strict) and all( # getattr(self, f).compare(getattr(other, f), strict) # for f in direct_fields(self.__class__).keys() # ) # # def add(self, obj: model.IdentifiableArtefact): # """Add `obj` to the StructureMessage.""" # for field, field_info in direct_fields(self.__class__).items(): # # NB for some reason mypy complains here, but not in __contains__(), below # if isinstance( # obj, get_args(field_info.outer_type_)[1], # type: ignore [attr-defined] # ): # getattr(self, field)[obj.id] = obj # return # raise TypeError(type(obj)) # # def get( # self, obj_or_id: Union[str, model.IdentifiableArtefact] # ) -> Optional[model.IdentifiableArtefact]: # """Retrieve `obj_or_id` from the StructureMessage. # # Parameters # ---------- # obj_or_id : str or .IdentifiableArtefact # If an IdentifiableArtefact, return an object of the same class and # :attr:`~.IdentifiableArtefact.id`; if :class:`str`, an object with this ID. # # Returns # ------- # .IdentifiableArtefact # with the given ID and possibly class. # None # if there is no match. # # Raises # ------ # ValueError # if `obj_or_id` is a string and there are ≥2 objects (of different classes) # with the same ID. # """ # id = ( # obj_or_id.id # if isinstance(obj_or_id, model.IdentifiableArtefact) # else obj_or_id # ) # # candidates: List[model.IdentifiableArtefact] = list( # filter( # None, # map( # lambda f: getattr(self, f).get(id), # direct_fields(self.__class__).keys(), # ), # ) # ) # # if len(candidates) > 1: # raise ValueError(f"ambiguous; {repr(obj_or_id)} matches {repr(candidates)}") # # return candidates[0] if len(candidates) == 1 else None # # def objects(self, cls): # """Get a reference to the attribute for objects of type `cls`. # # For example, if `cls` is the class :class:`DataStructureDefinition` (not an # instance), return a reference to :attr:`structure`. # """ # for name, info in direct_fields(self.__class__).items(): # if issubclass(cls, info.sub_fields[0].type_): # return getattr(self, name) # raise TypeError(cls) # # def __contains__(self, item): # """Return :obj:`True` if `item` is in the StructureMessage.""" # for field, field_info in direct_fields(self.__class__).items(): # if isinstance(item, get_args(field_info.outer_type_)[1]): # return item in getattr(self, field).values() # raise TypeError(f"StructureMessage has no collection of {type(item)}") # # def __repr__(self): # """String representation.""" # lines = [super().__repr__()] # # # StructureMessage contents # for attr in self.__dict__.values(): # if isinstance(attr, DictLike) and attr: # lines.append(summarize_dictlike(attr)) # # return "\n ".join(lines) # # Path: pandasdmx/writer/protobuf.py # def write(obj, *args, **kwargs): # """Convert an SDMX *obj* to protobuf string.""" # return _write(obj, *args, **kwargs).SerializeToString() . Output only the next line.
caplog.set_level(logging.ERROR)
Using the snippet: <|code_start|> def add_obs(self, observations, series_key=None): """Add *observations* to a series with *series_key*. Checks consistency and adds group associations.""" if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) for obs in observations: # Associate the observation with any GroupKeys that contain it self._add_group_refs(obs) # Store a reference to the observation self.obs.append(obs) if series_key is not None: if obs.series_key is None: # Assign the observation to the SeriesKey obs.series_key = series_key else: # Check that the Observation is not associated with a different # SeriesKey assert obs.series_key is series_key # Store a reference to the observation self.series[series_key].append(obs) @validator("action") <|code_end|> , determine the next line of code. You have imports: import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) and context (class names, function names, or code) available: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: . Output only the next line.
def _validate_action(cls, value):
Predict the next line after this snippet: <|code_start|> if isinstance(target, Observation): self.group[group_key].append(target) def add_obs(self, observations, series_key=None): """Add *observations* to a series with *series_key*. Checks consistency and adds group associations.""" if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) for obs in observations: # Associate the observation with any GroupKeys that contain it self._add_group_refs(obs) # Store a reference to the observation self.obs.append(obs) if series_key is not None: if obs.series_key is None: # Assign the observation to the SeriesKey obs.series_key = series_key else: # Check that the Observation is not associated with a different # SeriesKey assert obs.series_key is series_key # Store a reference to the observation <|code_end|> using the current file's imports: import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) and any relevant context from other files: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: . Output only the next line.
self.series[series_key].append(obs)
Using the snippet: <|code_start|> #: :mod:`sdmx` extension not in the IM. series: DictLike[SeriesKey, List[Observation]] = dictlike_field() #: Map of group key → list of observations. #: :mod:`sdmx` extension not in the IM. group: DictLike[GroupKey, List[Observation]] = dictlike_field() def __len__(self): return len(self.obs) def _add_group_refs(self, target): """Associate *target* with groups in this dataset. *target* may be an instance of SeriesKey or Observation. """ for group_key in self.group: if group_key in (target if isinstance(target, SeriesKey) else target.key): target.group_keys.add(group_key) if isinstance(target, Observation): self.group[group_key].append(target) def add_obs(self, observations, series_key=None): """Add *observations* to a series with *series_key*. Checks consistency and adds group associations.""" if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) <|code_end|> , determine the next line of code. You have imports: import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) and context (class names, function names, or code) available: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: . Output only the next line.
for obs in observations:
Given the following code snippet before the placeholder: <|code_start|> return len(self.obs) def _add_group_refs(self, target): """Associate *target* with groups in this dataset. *target* may be an instance of SeriesKey or Observation. """ for group_key in self.group: if group_key in (target if isinstance(target, SeriesKey) else target.key): target.group_keys.add(group_key) if isinstance(target, Observation): self.group[group_key].append(target) def add_obs(self, observations, series_key=None): """Add *observations* to a series with *series_key*. Checks consistency and adds group associations.""" if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) for obs in observations: # Associate the observation with any GroupKeys that contain it self._add_group_refs(obs) # Store a reference to the observation self.obs.append(obs) <|code_end|> , predict the next line using imports from the current file: import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) and context including class names, function names, and sometimes code from other files: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: . Output only the next line.
if series_key is not None:
Next line prediction: <|code_start|> def _add_group_refs(self, target): """Associate *target* with groups in this dataset. *target* may be an instance of SeriesKey or Observation. """ for group_key in self.group: if group_key in (target if isinstance(target, SeriesKey) else target.key): target.group_keys.add(group_key) if isinstance(target, Observation): self.group[group_key].append(target) def add_obs(self, observations, series_key=None): """Add *observations* to a series with *series_key*. Checks consistency and adds group associations.""" if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) for obs in observations: # Associate the observation with any GroupKeys that contain it self._add_group_refs(obs) # Store a reference to the observation self.obs.append(obs) if series_key is not None: <|code_end|> . Use current file imports: (import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) ) and context including class names, function names, or small code snippets from other files: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: . Output only the next line.
if obs.series_key is None:
Here is a snippet: <|code_start|> if isinstance(target, Observation): self.group[group_key].append(target) def add_obs(self, observations, series_key=None): """Add *observations* to a series with *series_key*. Checks consistency and adds group associations.""" if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) for obs in observations: # Associate the observation with any GroupKeys that contain it self._add_group_refs(obs) # Store a reference to the observation self.obs.append(obs) if series_key is not None: if obs.series_key is None: # Assign the observation to the SeriesKey obs.series_key = series_key else: # Check that the Observation is not associated with a different # SeriesKey assert obs.series_key is series_key # Store a reference to the observation <|code_end|> . Write the next line using the current file imports: import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) and context from other files: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: , which may include functions, classes, or code. Output only the next line.
self.series[series_key].append(obs)
Continue the code snippet: <|code_start|> return len(self.obs) def _add_group_refs(self, target): """Associate *target* with groups in this dataset. *target* may be an instance of SeriesKey or Observation. """ for group_key in self.group: if group_key in (target if isinstance(target, SeriesKey) else target.key): target.group_keys.add(group_key) if isinstance(target, Observation): self.group[group_key].append(target) def add_obs(self, observations, series_key=None): """Add *observations* to a series with *series_key*. Checks consistency and adds group associations.""" if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) for obs in observations: # Associate the observation with any GroupKeys that contain it self._add_group_refs(obs) # Store a reference to the observation self.obs.append(obs) <|code_end|> . Use current file imports: import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) and context (classes, functions, or code) from other files: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: . Output only the next line.
if series_key is not None:
Here is a snippet: <|code_start|> if series_key is not None: # Associate series_key with any GroupKeys that apply to it self._add_group_refs(series_key) # Maybe initialize empty series self.series.setdefault(series_key, []) for obs in observations: # Associate the observation with any GroupKeys that contain it self._add_group_refs(obs) # Store a reference to the observation self.obs.append(obs) if series_key is not None: if obs.series_key is None: # Assign the observation to the SeriesKey obs.series_key = series_key else: # Check that the Observation is not associated with a different # SeriesKey assert obs.series_key is series_key # Store a reference to the observation self.series[series_key].append(obs) @validator("action") def _validate_action(cls, value): if value in ActionType: return value else: <|code_end|> . Write the next line using the current file imports: import logging import pandasdmx.urn from collections import ChainMap from collections.abc import Collection from collections.abc import Iterable as IterableABC from copy import copy from datetime import date, datetime, timedelta from enum import Enum from functools import lru_cache from inspect import isclass from itertools import product from operator import attrgetter, itemgetter from typing import ( Any, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from warnings import warn from pandasdmx.util import ( BaseModel, DictLike, compare, dictlike_field, only, Resource, validate_dictlike, validator, ) and context from other files: # Path: pandasdmx/util.py # HAS_REQUESTS_CACHE = False # HAS_REQUESTS_CACHE = True # KT = TypeVar("KT") # VT = TypeVar("VT") # CLASS_NAME = { # "dataflow": "DataflowDefinition", # "datastructure": "DataStructureDefinition", # } # VALUE = {v: k for k, v in CLASS_NAME.items()} # RESPONSE_CODE = { # 200: "OK", # 304: "No changes", # 400: "Bad syntax", # 401: "Unauthorized", # 403: "Semantic error", # or "Forbidden" # 404: "Not found", # 406: "Not acceptable", # 413: "Request entity too large", # 414: "URI too long", # 500: "Internal server error", # 501: "Not implemented", # 503: "Unavailable", # } # KT = TypeVar("KT") # VT = TypeVar("VT") # class Resource(str, Enum): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class BaseModel(pydantic.BaseModel): # class Config: # class MaybeCachedSession(type): # class DictLike(dict, typing.MutableMapping[KT, VT]): # def from_obj(cls, obj): # def class_name(cls, value: "Resource", default=None) -> str: # def describe(cls): # def __new__(cls, name, bases, dct): # def __new__(cls, name, bases, dct): # def __init__(self, *args, **kwargs): # def __getitem__(self, key: Union[KT, int]) -> VT: # def __getstate__(self): # def __setitem__(self, key: KT, value: VT) -> None: # def __copy__(self): # def copy(self): # def __get_validators__(cls): # def _validate_whole(cls, v, field: pydantic.fields.ModelField): # def _validate_entry(self, key, value): # def compare(self, other, strict=True): # def dictlike_field(): # def summarize_dictlike(dl, maxwidth=72): # def validate_dictlike(cls): # def compare(attr, a, b, strict: bool) -> bool: # def only(iterator: Iterator) -> Any: # def parse_content_type(value: str) -> Tuple[str, Dict[str, Any]]: # def direct_fields(cls) -> Mapping[str, pydantic.fields.ModelField]: # def get_args(tp) -> Tuple[Any, ...]: , which may include functions, classes, or code. Output only the next line.
return ActionType[value]
Given the code snippet: <|code_start|> class CityManager(models.Manager): def get_by_natural_key(self, slug): return self.get(slug=slug) @register_snippet class City(models.Model): <|code_end|> , generate the next line using the imports in this file: from django.contrib.gis.db import models from django.conf import settings from django.templatetags.l10n import localize from django.template.defaultfilters import strip_tags from django.core.urlresolvers import reverse from django.utils.functional import cached_property from django import forms from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as trans from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, FieldRowPanel, \ MultiFieldPanel, InlinePanel, ObjectList from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsnippets.models import register_snippet from bitfield import BitField from location_field.models.spatial import LocationField from input_mask.widgets import DecimalInputMask from modelcluster.fields import ParentalKey from .edit_handlers import ListingTabbedInterface from .mixins import ListingPageViewMixin from .widgets import NeighbourhoodWidget, CondominiumWidget and context (functions, classes, or occasionally code) from other files: # Path: listing/edit_handlers.py # class ListingTabbedInterface(TabbedInterface): # def bind_to_model(self, model): # cls = super().bind_to_model(model) # base_form_class = cls.get_form_class(model) # cls._form_class = get_form_class(base_form_class) # return cls # # Path: listing/mixins.py # class ListingPageViewMixin(object): # @cached_property # def similar_params(self): # params = {} # params['category'] = self.get_parent().slug # params['city'] = self.city.slug # params['bedrooms'] = self.bedrooms # # if self.listing_type.sell: # params['listing_type'] = 'sell' # price = float(self.sell_price) # # elif self.listing_type.rent: # params['listing_type'] = 'rent' # price = float(self.rent_price) # # diff = float(price) * 0.20 # # params['min_price'] = price - diff # params['max_price'] = price + diff # # return params # # @cached_property # def similar_queryset(self): # category = self.get_parent() # city = self.city # listing_type = self.listing_type # bedrooms = self.bedrooms # # qs = self.__class__.objects.child_of(category).filter( # city=city, listing_type=listing_type, # bedrooms__gte=bedrooms, # ) # # if listing_type.sell: # price = float(self.sell_price) # diff = float(price) * 0.20 # qs = qs.filter(sell_price__range=(price-diff, price+diff)) # # elif listing_type.rent: # price = float(self.rent_price) # diff = float(price) * 0.20 # qs = qs.filter(rent_price__range=(price-diff, price+diff)) # # return qs # # def get_context(self, *args, **kwargs): # ctx = super().get_context(*args, **kwargs) # ctx['condominiums'] = self.get_condominiums() # ctx['neighbourhoods'] = self.get_neighbourhoods() # # return ctx # # def get_neighbourhoods(self, *args): # qs = self.similar_queryset.filter(neighbourhood__isnull=False) # # result = [] # # for row in qs.annotate(Count('neighbourhood')): # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood-{}'.format( # row.neighbourhood.slug) # # result.append(( # row.neighbourhood, # row.neighbourhood__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # def get_condominiums(self): # qs = self.similar_queryset.filter(condominium__isnull=False) # result = [] # # for row in qs.annotate(Count('condominium')): # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium-{}'.format( # row.condominium.slug) # # result.append(( # row.condominium, # row.condominium__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # Path: listing/widgets.py # class NeighbourhoodWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_neighbourhoods_json') # # @property # def media(self): # return forms.Media() # # class CondominiumWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_condominiums_json') # # @property # def media(self): # return forms.Media() . Output only the next line.
name = models.CharField(max_length=255)
Given the following code snippet before the placeholder: <|code_start|> class CityManager(models.Manager): def get_by_natural_key(self, slug): return self.get(slug=slug) <|code_end|> , predict the next line using imports from the current file: from django.contrib.gis.db import models from django.conf import settings from django.templatetags.l10n import localize from django.template.defaultfilters import strip_tags from django.core.urlresolvers import reverse from django.utils.functional import cached_property from django import forms from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as trans from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, FieldRowPanel, \ MultiFieldPanel, InlinePanel, ObjectList from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsnippets.models import register_snippet from bitfield import BitField from location_field.models.spatial import LocationField from input_mask.widgets import DecimalInputMask from modelcluster.fields import ParentalKey from .edit_handlers import ListingTabbedInterface from .mixins import ListingPageViewMixin from .widgets import NeighbourhoodWidget, CondominiumWidget and context including class names, function names, and sometimes code from other files: # Path: listing/edit_handlers.py # class ListingTabbedInterface(TabbedInterface): # def bind_to_model(self, model): # cls = super().bind_to_model(model) # base_form_class = cls.get_form_class(model) # cls._form_class = get_form_class(base_form_class) # return cls # # Path: listing/mixins.py # class ListingPageViewMixin(object): # @cached_property # def similar_params(self): # params = {} # params['category'] = self.get_parent().slug # params['city'] = self.city.slug # params['bedrooms'] = self.bedrooms # # if self.listing_type.sell: # params['listing_type'] = 'sell' # price = float(self.sell_price) # # elif self.listing_type.rent: # params['listing_type'] = 'rent' # price = float(self.rent_price) # # diff = float(price) * 0.20 # # params['min_price'] = price - diff # params['max_price'] = price + diff # # return params # # @cached_property # def similar_queryset(self): # category = self.get_parent() # city = self.city # listing_type = self.listing_type # bedrooms = self.bedrooms # # qs = self.__class__.objects.child_of(category).filter( # city=city, listing_type=listing_type, # bedrooms__gte=bedrooms, # ) # # if listing_type.sell: # price = float(self.sell_price) # diff = float(price) * 0.20 # qs = qs.filter(sell_price__range=(price-diff, price+diff)) # # elif listing_type.rent: # price = float(self.rent_price) # diff = float(price) * 0.20 # qs = qs.filter(rent_price__range=(price-diff, price+diff)) # # return qs # # def get_context(self, *args, **kwargs): # ctx = super().get_context(*args, **kwargs) # ctx['condominiums'] = self.get_condominiums() # ctx['neighbourhoods'] = self.get_neighbourhoods() # # return ctx # # def get_neighbourhoods(self, *args): # qs = self.similar_queryset.filter(neighbourhood__isnull=False) # # result = [] # # for row in qs.annotate(Count('neighbourhood')): # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood-{}'.format( # row.neighbourhood.slug) # # result.append(( # row.neighbourhood, # row.neighbourhood__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # def get_condominiums(self): # qs = self.similar_queryset.filter(condominium__isnull=False) # result = [] # # for row in qs.annotate(Count('condominium')): # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium-{}'.format( # row.condominium.slug) # # result.append(( # row.condominium, # row.condominium__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # Path: listing/widgets.py # class NeighbourhoodWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_neighbourhoods_json') # # @property # def media(self): # return forms.Media() # # class CondominiumWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_condominiums_json') # # @property # def media(self): # return forms.Media() . Output only the next line.
@register_snippet
Continue the code snippet: <|code_start|> class CityManager(models.Manager): def get_by_natural_key(self, slug): return self.get(slug=slug) @register_snippet <|code_end|> . Use current file imports: from django.contrib.gis.db import models from django.conf import settings from django.templatetags.l10n import localize from django.template.defaultfilters import strip_tags from django.core.urlresolvers import reverse from django.utils.functional import cached_property from django import forms from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as trans from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, FieldRowPanel, \ MultiFieldPanel, InlinePanel, ObjectList from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsnippets.models import register_snippet from bitfield import BitField from location_field.models.spatial import LocationField from input_mask.widgets import DecimalInputMask from modelcluster.fields import ParentalKey from .edit_handlers import ListingTabbedInterface from .mixins import ListingPageViewMixin from .widgets import NeighbourhoodWidget, CondominiumWidget and context (classes, functions, or code) from other files: # Path: listing/edit_handlers.py # class ListingTabbedInterface(TabbedInterface): # def bind_to_model(self, model): # cls = super().bind_to_model(model) # base_form_class = cls.get_form_class(model) # cls._form_class = get_form_class(base_form_class) # return cls # # Path: listing/mixins.py # class ListingPageViewMixin(object): # @cached_property # def similar_params(self): # params = {} # params['category'] = self.get_parent().slug # params['city'] = self.city.slug # params['bedrooms'] = self.bedrooms # # if self.listing_type.sell: # params['listing_type'] = 'sell' # price = float(self.sell_price) # # elif self.listing_type.rent: # params['listing_type'] = 'rent' # price = float(self.rent_price) # # diff = float(price) * 0.20 # # params['min_price'] = price - diff # params['max_price'] = price + diff # # return params # # @cached_property # def similar_queryset(self): # category = self.get_parent() # city = self.city # listing_type = self.listing_type # bedrooms = self.bedrooms # # qs = self.__class__.objects.child_of(category).filter( # city=city, listing_type=listing_type, # bedrooms__gte=bedrooms, # ) # # if listing_type.sell: # price = float(self.sell_price) # diff = float(price) * 0.20 # qs = qs.filter(sell_price__range=(price-diff, price+diff)) # # elif listing_type.rent: # price = float(self.rent_price) # diff = float(price) * 0.20 # qs = qs.filter(rent_price__range=(price-diff, price+diff)) # # return qs # # def get_context(self, *args, **kwargs): # ctx = super().get_context(*args, **kwargs) # ctx['condominiums'] = self.get_condominiums() # ctx['neighbourhoods'] = self.get_neighbourhoods() # # return ctx # # def get_neighbourhoods(self, *args): # qs = self.similar_queryset.filter(neighbourhood__isnull=False) # # result = [] # # for row in qs.annotate(Count('neighbourhood')): # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood-{}'.format( # row.neighbourhood.slug) # # result.append(( # row.neighbourhood, # row.neighbourhood__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # def get_condominiums(self): # qs = self.similar_queryset.filter(condominium__isnull=False) # result = [] # # for row in qs.annotate(Count('condominium')): # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium-{}'.format( # row.condominium.slug) # # result.append(( # row.condominium, # row.condominium__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # Path: listing/widgets.py # class NeighbourhoodWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_neighbourhoods_json') # # @property # def media(self): # return forms.Media() # # class CondominiumWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_condominiums_json') # # @property # def media(self): # return forms.Media() . Output only the next line.
class City(models.Model):
Based on the snippet: <|code_start|> class CityManager(models.Manager): def get_by_natural_key(self, slug): return self.get(slug=slug) @register_snippet class City(models.Model): name = models.CharField(max_length=255) <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.gis.db import models from django.conf import settings from django.templatetags.l10n import localize from django.template.defaultfilters import strip_tags from django.core.urlresolvers import reverse from django.utils.functional import cached_property from django import forms from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as trans from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, FieldRowPanel, \ MultiFieldPanel, InlinePanel, ObjectList from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsnippets.models import register_snippet from bitfield import BitField from location_field.models.spatial import LocationField from input_mask.widgets import DecimalInputMask from modelcluster.fields import ParentalKey from .edit_handlers import ListingTabbedInterface from .mixins import ListingPageViewMixin from .widgets import NeighbourhoodWidget, CondominiumWidget and context (classes, functions, sometimes code) from other files: # Path: listing/edit_handlers.py # class ListingTabbedInterface(TabbedInterface): # def bind_to_model(self, model): # cls = super().bind_to_model(model) # base_form_class = cls.get_form_class(model) # cls._form_class = get_form_class(base_form_class) # return cls # # Path: listing/mixins.py # class ListingPageViewMixin(object): # @cached_property # def similar_params(self): # params = {} # params['category'] = self.get_parent().slug # params['city'] = self.city.slug # params['bedrooms'] = self.bedrooms # # if self.listing_type.sell: # params['listing_type'] = 'sell' # price = float(self.sell_price) # # elif self.listing_type.rent: # params['listing_type'] = 'rent' # price = float(self.rent_price) # # diff = float(price) * 0.20 # # params['min_price'] = price - diff # params['max_price'] = price + diff # # return params # # @cached_property # def similar_queryset(self): # category = self.get_parent() # city = self.city # listing_type = self.listing_type # bedrooms = self.bedrooms # # qs = self.__class__.objects.child_of(category).filter( # city=city, listing_type=listing_type, # bedrooms__gte=bedrooms, # ) # # if listing_type.sell: # price = float(self.sell_price) # diff = float(price) * 0.20 # qs = qs.filter(sell_price__range=(price-diff, price+diff)) # # elif listing_type.rent: # price = float(self.rent_price) # diff = float(price) * 0.20 # qs = qs.filter(rent_price__range=(price-diff, price+diff)) # # return qs # # def get_context(self, *args, **kwargs): # ctx = super().get_context(*args, **kwargs) # ctx['condominiums'] = self.get_condominiums() # ctx['neighbourhoods'] = self.get_neighbourhoods() # # return ctx # # def get_neighbourhoods(self, *args): # qs = self.similar_queryset.filter(neighbourhood__isnull=False) # # result = [] # # for row in qs.annotate(Count('neighbourhood')): # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood-{}'.format( # row.neighbourhood.slug) # # result.append(( # row.neighbourhood, # row.neighbourhood__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'neighbourhood' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # def get_condominiums(self): # qs = self.similar_queryset.filter(condominium__isnull=False) # result = [] # # for row in qs.annotate(Count('condominium')): # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium-{}'.format( # row.condominium.slug) # # result.append(( # row.condominium, # row.condominium__count, # params, # )) # # if qs: # params = self.similar_params.copy() # params['neighbourhood'] = 'condominium' # # result.insert(0, ('Todos', qs.count(), params)) # # return result # # Path: listing/widgets.py # class NeighbourhoodWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_neighbourhoods_json') # # @property # def media(self): # return forms.Media() # # class CondominiumWidget(AjaxCitySelect): # filter_url = reverse_lazy('dashboard_condominiums_json') # # @property # def media(self): # return forms.Media() . Output only the next line.
slug = models.SlugField(max_length=255)
Using the snippet: <|code_start|> def neighbourhoods(request): city_id = request.GET.get('city', None) term = slugify(request.GET.get('term', '')) results = Neighbourhood.objects.filter( city__id=city_id, slug__contains=term, ).values_list('id', 'name') results = [{'id': r[0], 'text': r[1]} for r in results] return HttpResponse(content=json.dumps(results), content_type='application/json') <|code_end|> , determine the next line of code. You have imports: import json from django.http import HttpResponse from django.template.defaultfilters import slugify from listing.models import Neighbourhood, Condominium and context (class names, function names, or code) available: # Path: listing/models.py # class Neighbourhood(models.Model): # city = ParentalKey(City, related_name='neighbourhoods') # name = models.CharField(max_length=255) # slug = models.SlugField(max_length=255) # # panels = [ # FieldPanel('city'), # FieldPanel('name'), # FieldPanel('slug'), # ] # # class Meta: # ordering = ('slug',) # verbose_name = 'bairro' # verbose_name_plural = 'bairros' # # def __str__(self): # return self.name # # class Condominium(models.Model): # city = ParentalKey(City, related_name='condominiums') # name = models.CharField(max_length=255) # slug = models.SlugField(max_length=255) # # class Meta: # ordering = ('slug',) # verbose_name = 'condomínio' # verbose_name_plural = 'condomínios' # # def __str__(self): # return self.name . Output only the next line.
def condominiums(request):
Predict the next line after this snippet: <|code_start|> urlpatterns = [ url(r'^ajax/neighbourhoods.json', neighbourhoods, name='dashboard_neighbourhoods_json'), url(r'^ajax/condominiums.json', condominiums, <|code_end|> using the current file's imports: from django.conf.urls import url from dashboard.views import neighbourhoods, condominiums and any relevant context from other files: # Path: dashboard/views.py # def neighbourhoods(request): # city_id = request.GET.get('city', None) # term = slugify(request.GET.get('term', '')) # # results = Neighbourhood.objects.filter( # city__id=city_id, # slug__contains=term, # ).values_list('id', 'name') # # results = [{'id': r[0], 'text': r[1]} for r in results] # # return HttpResponse(content=json.dumps(results), # content_type='application/json') # # def condominiums(request): # city_id = request.GET.get('city', None) # term = slugify(request.GET.get('term', '')) # # results = Condominium.objects.filter( # city__id=city_id, # slug__contains=term, # ).values_list('id', 'name') # # results = [{'id': r[0], 'text': r[1]} for r in results] # # return HttpResponse(content=json.dumps(results), # content_type='application/json') . Output only the next line.
name='dashboard_condominiums_json'),
Next line prediction: <|code_start|> urlpatterns = [ url(r'^ajax/neighbourhoods.json', neighbourhoods, name='dashboard_neighbourhoods_json'), url(r'^ajax/condominiums.json', condominiums, name='dashboard_condominiums_json'), <|code_end|> . Use current file imports: (from django.conf.urls import url from dashboard.views import neighbourhoods, condominiums) and context including class names, function names, or small code snippets from other files: # Path: dashboard/views.py # def neighbourhoods(request): # city_id = request.GET.get('city', None) # term = slugify(request.GET.get('term', '')) # # results = Neighbourhood.objects.filter( # city__id=city_id, # slug__contains=term, # ).values_list('id', 'name') # # results = [{'id': r[0], 'text': r[1]} for r in results] # # return HttpResponse(content=json.dumps(results), # content_type='application/json') # # def condominiums(request): # city_id = request.GET.get('city', None) # term = slugify(request.GET.get('term', '')) # # results = Condominium.objects.filter( # city__id=city_id, # slug__contains=term, # ).values_list('id', 'name') # # results = [{'id': r[0], 'text': r[1]} for r in results] # # return HttpResponse(content=json.dumps(results), # content_type='application/json') . Output only the next line.
]
Predict the next line for this snippet: <|code_start|># standard libraries # rubiks cube libraries logger = logging.getLogger(__name__) class NoSteps(Exception): pass class NoIDASolution(Exception): pass <|code_end|> with the help of current file imports: import datetime as dt import hashlib import json import logging import os import resource import shutil import subprocess from pathlib import Path from subprocess import call from typing import Dict, List, TextIO, Tuple from rubikscubennnsolver.RubiksSide import SolveError from rubikscubennnsolver.RubiksCube222 import rotate_222 from rubikscubennnsolver.RubiksCube444 import rotate_444 from rubikscubennnsolver.RubiksCube555 import rotate_555 from rubikscubennnsolver.RubiksCube666 import rotate_666 from rubikscubennnsolver.RubiksCube777 import rotate_777 and context from other files: # Path: rubikscubennnsolver/RubiksSide.py # class SolveError(Exception): # pass , which may contain function names, class names, or code. Output only the next line.
class NoPruneTableState(Exception):
Continue the code snippet: <|code_start|># -*- encoding: utf-8 -*- logger = logging.getLogger('jenkins') def update_build_info(): lint_jenkins = LintJenkins(settings.JENKINS_URL, username=settings.JENKINS_USER, password=settings.JENKINS_TOKEN) for job in Job.objects.all(): remote_build_numbers = lint_jenkins.get_build_numbers(job.name) local_build_numbers = [int(build['number']) for build in job.builds.values('number')] <|code_end|> . Use current file imports: import json import logging import time from django.conf import settings from django_q.tasks import Async from djmail.template_mail import InlineCSSTemplateMail from lintjenkins import LintJenkins from .models import Build, Job and context (classes, functions, or code) from other files: # Path: src/app/models.py # class Build(models.Model): # # class Meta: # db_table = 'builds' # # number = models.IntegerField() # job = models.ForeignKey(Job, related_name="builds") # created = models.DateTimeField(auto_now_add=True) # result = models.TextField(default="") # # def __str__(self): # return "{0}:{1}".format(self.job.name, self.number) # # class Job(models.Model): # # class Meta: # db_table = 'jobs' # # name = models.CharField(unique=True, max_length=250) # description = models.TextField(blank=True, default='') # svn_url = models.TextField() # svn_username = models.TextField(blank=True, default='') # svn_password = models.TextField(blank=True, default='') # # recipient = models.TextField() # violation_threshold_num = models.IntegerField(default=888) # # def __str__(self): # return self.name . Output only the next line.
new_build_numbers = list(set(remote_build_numbers) - set(local_build_numbers))
Here is a snippet: <|code_start|> permission_classes = ( permissions.AllowAny, # TODO: 上下后需要改为登陆用户 ) pagination_class = StandardResultsSetPagination filter_backends = ( filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter ) class JobViewSet(DefaultsMixin, viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer search_fields = ('name',) ordering_fields = ('name',) filter_fields = ('name', ) # 普通的字段匹配这样够了,如果需要实现高级匹配比如日期基于某个范围等,就需要定义自己的FilterSet类了 # http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend def perform_create(self, serializer): serializer.save() # 创建jenkins job lint_jenkins = LintJenkins(settings.JENKINS_URL, username=settings.JENKINS_USER, password=settings.JENKINS_TOKEN) job_info = serializer.data logger.info(job_info) try: lint_jenkins.add_job(svn=str(job_info['svn_url']), <|code_end|> . Write the next line using the current file imports: import json import logging from django.conf import settings from django.shortcuts import get_object_or_404 from rest_framework import authentication, filters, permissions, viewsets from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from lintjenkins import LintJenkins from silk.profiling.profiler import silk_profile from .models import Build, Job from .serializers import BuildSerializer, JobSerializer and context from other files: # Path: src/app/models.py # class Build(models.Model): # # class Meta: # db_table = 'builds' # # number = models.IntegerField() # job = models.ForeignKey(Job, related_name="builds") # created = models.DateTimeField(auto_now_add=True) # result = models.TextField(default="") # # def __str__(self): # return "{0}:{1}".format(self.job.name, self.number) # # class Job(models.Model): # # class Meta: # db_table = 'jobs' # # name = models.CharField(unique=True, max_length=250) # description = models.TextField(blank=True, default='') # svn_url = models.TextField() # svn_username = models.TextField(blank=True, default='') # svn_password = models.TextField(blank=True, default='') # # recipient = models.TextField() # violation_threshold_num = models.IntegerField(default=888) # # def __str__(self): # return self.name # # Path: src/app/serializers.py # class BuildSerializer(serializers.ModelSerializer): # links = serializers.SerializerMethodField() # # class Meta: # model = Build # fields = ('id', 'number', 'created', 'job', 'result', 'links') # # def get_links(self, obj): # request = self.context['request'] # links = { # 'self': reverse('build-detail', kwargs={'pk': obj.pk}, request=request), # 'job': None, # } # # 注意: 这里用的是sprint_id, assigned用的是 obj.assigned. # if obj.job: # links['job'] = reverse( # 'job-detail', kwargs={'pk': obj.job_id}, request=request) # # return links # # def validate(self, attrs): # return attrs # # class JobSerializer(serializers.ModelSerializer): # links = serializers.SerializerMethodField() # violation_info = serializers.SerializerMethodField() # # class Meta: # model = Job # fields = ('id', 'name', 'description', # 'svn_url', 'svn_username', 'svn_password', # 'recipient', 'violation_threshold_num', 'links', 'violation_info') # # def get_violation_info(self, obj): # last_builds = obj.builds.order_by('-number')[:1] # violation_info = { # "violation_file_num": -1, # 'violation_num': -1, # 'created': '0-0-0 0:0:0', # 'health_url': '/static/img/rain.png', # 'report_url': '' # } # if not last_builds: # return violation_info # last_build = last_builds[0] # build_info = json.loads(last_build.result) # # violation_info = build_info['violation_info'] # if violation_info['violation_num'] >= obj.violation_threshold_num: # health_url = '/static/img/rain.png' # else: # health_url = '/static/img/sun.png' # # violation_info.update({ # 'created': build_info['datetime'], # 'health_url': health_url, # 'report_url': settings.JENKINS_URL + '/job/{job_name}/violations/'.format(job_name=obj.name) # }) # # return violation_info # # def get_links(self, obj): # request = self.context['request'] # return { # 'self': reverse('job-detail', kwargs={'pk': obj.pk}, request=request) # } , which may include functions, classes, or code. Output only the next line.
username=str(job_info['svn_username']),
Continue the code snippet: <|code_start|> ordering_fields = ('name',) filter_fields = ('name', ) # 普通的字段匹配这样够了,如果需要实现高级匹配比如日期基于某个范围等,就需要定义自己的FilterSet类了 # http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend def perform_create(self, serializer): serializer.save() # 创建jenkins job lint_jenkins = LintJenkins(settings.JENKINS_URL, username=settings.JENKINS_USER, password=settings.JENKINS_TOKEN) job_info = serializer.data logger.info(job_info) try: lint_jenkins.add_job(svn=str(job_info['svn_url']), username=str(job_info['svn_username']), password=str(job_info['svn_password']), job_name=str(job_info['name'])) except Exception as e: logger.exception(e) Job.objects.filter(id=job_info['id']).delete() raise Exception(e) logger.info('create params:%s', serializer.data) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: <|code_end|> . Use current file imports: import json import logging from django.conf import settings from django.shortcuts import get_object_or_404 from rest_framework import authentication, filters, permissions, viewsets from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from lintjenkins import LintJenkins from silk.profiling.profiler import silk_profile from .models import Build, Job from .serializers import BuildSerializer, JobSerializer and context (classes, functions, or code) from other files: # Path: src/app/models.py # class Build(models.Model): # # class Meta: # db_table = 'builds' # # number = models.IntegerField() # job = models.ForeignKey(Job, related_name="builds") # created = models.DateTimeField(auto_now_add=True) # result = models.TextField(default="") # # def __str__(self): # return "{0}:{1}".format(self.job.name, self.number) # # class Job(models.Model): # # class Meta: # db_table = 'jobs' # # name = models.CharField(unique=True, max_length=250) # description = models.TextField(blank=True, default='') # svn_url = models.TextField() # svn_username = models.TextField(blank=True, default='') # svn_password = models.TextField(blank=True, default='') # # recipient = models.TextField() # violation_threshold_num = models.IntegerField(default=888) # # def __str__(self): # return self.name # # Path: src/app/serializers.py # class BuildSerializer(serializers.ModelSerializer): # links = serializers.SerializerMethodField() # # class Meta: # model = Build # fields = ('id', 'number', 'created', 'job', 'result', 'links') # # def get_links(self, obj): # request = self.context['request'] # links = { # 'self': reverse('build-detail', kwargs={'pk': obj.pk}, request=request), # 'job': None, # } # # 注意: 这里用的是sprint_id, assigned用的是 obj.assigned. # if obj.job: # links['job'] = reverse( # 'job-detail', kwargs={'pk': obj.job_id}, request=request) # # return links # # def validate(self, attrs): # return attrs # # class JobSerializer(serializers.ModelSerializer): # links = serializers.SerializerMethodField() # violation_info = serializers.SerializerMethodField() # # class Meta: # model = Job # fields = ('id', 'name', 'description', # 'svn_url', 'svn_username', 'svn_password', # 'recipient', 'violation_threshold_num', 'links', 'violation_info') # # def get_violation_info(self, obj): # last_builds = obj.builds.order_by('-number')[:1] # violation_info = { # "violation_file_num": -1, # 'violation_num': -1, # 'created': '0-0-0 0:0:0', # 'health_url': '/static/img/rain.png', # 'report_url': '' # } # if not last_builds: # return violation_info # last_build = last_builds[0] # build_info = json.loads(last_build.result) # # violation_info = build_info['violation_info'] # if violation_info['violation_num'] >= obj.violation_threshold_num: # health_url = '/static/img/rain.png' # else: # health_url = '/static/img/sun.png' # # violation_info.update({ # 'created': build_info['datetime'], # 'health_url': health_url, # 'report_url': settings.JENKINS_URL + '/job/{job_name}/violations/'.format(job_name=obj.name) # }) # # return violation_info # # def get_links(self, obj): # request = self.context['request'] # return { # 'self': reverse('job-detail', kwargs={'pk': obj.pk}, request=request) # } . Output only the next line.
serializer = self.get_serializer(page, many=True)
Predict the next line for this snippet: <|code_start|> filters.SearchFilter, filters.OrderingFilter ) class JobViewSet(DefaultsMixin, viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer search_fields = ('name',) ordering_fields = ('name',) filter_fields = ('name', ) # 普通的字段匹配这样够了,如果需要实现高级匹配比如日期基于某个范围等,就需要定义自己的FilterSet类了 # http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend def perform_create(self, serializer): serializer.save() # 创建jenkins job lint_jenkins = LintJenkins(settings.JENKINS_URL, username=settings.JENKINS_USER, password=settings.JENKINS_TOKEN) job_info = serializer.data logger.info(job_info) try: lint_jenkins.add_job(svn=str(job_info['svn_url']), username=str(job_info['svn_username']), password=str(job_info['svn_password']), job_name=str(job_info['name'])) except Exception as e: logger.exception(e) Job.objects.filter(id=job_info['id']).delete() <|code_end|> with the help of current file imports: import json import logging from django.conf import settings from django.shortcuts import get_object_or_404 from rest_framework import authentication, filters, permissions, viewsets from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from lintjenkins import LintJenkins from silk.profiling.profiler import silk_profile from .models import Build, Job from .serializers import BuildSerializer, JobSerializer and context from other files: # Path: src/app/models.py # class Build(models.Model): # # class Meta: # db_table = 'builds' # # number = models.IntegerField() # job = models.ForeignKey(Job, related_name="builds") # created = models.DateTimeField(auto_now_add=True) # result = models.TextField(default="") # # def __str__(self): # return "{0}:{1}".format(self.job.name, self.number) # # class Job(models.Model): # # class Meta: # db_table = 'jobs' # # name = models.CharField(unique=True, max_length=250) # description = models.TextField(blank=True, default='') # svn_url = models.TextField() # svn_username = models.TextField(blank=True, default='') # svn_password = models.TextField(blank=True, default='') # # recipient = models.TextField() # violation_threshold_num = models.IntegerField(default=888) # # def __str__(self): # return self.name # # Path: src/app/serializers.py # class BuildSerializer(serializers.ModelSerializer): # links = serializers.SerializerMethodField() # # class Meta: # model = Build # fields = ('id', 'number', 'created', 'job', 'result', 'links') # # def get_links(self, obj): # request = self.context['request'] # links = { # 'self': reverse('build-detail', kwargs={'pk': obj.pk}, request=request), # 'job': None, # } # # 注意: 这里用的是sprint_id, assigned用的是 obj.assigned. # if obj.job: # links['job'] = reverse( # 'job-detail', kwargs={'pk': obj.job_id}, request=request) # # return links # # def validate(self, attrs): # return attrs # # class JobSerializer(serializers.ModelSerializer): # links = serializers.SerializerMethodField() # violation_info = serializers.SerializerMethodField() # # class Meta: # model = Job # fields = ('id', 'name', 'description', # 'svn_url', 'svn_username', 'svn_password', # 'recipient', 'violation_threshold_num', 'links', 'violation_info') # # def get_violation_info(self, obj): # last_builds = obj.builds.order_by('-number')[:1] # violation_info = { # "violation_file_num": -1, # 'violation_num': -1, # 'created': '0-0-0 0:0:0', # 'health_url': '/static/img/rain.png', # 'report_url': '' # } # if not last_builds: # return violation_info # last_build = last_builds[0] # build_info = json.loads(last_build.result) # # violation_info = build_info['violation_info'] # if violation_info['violation_num'] >= obj.violation_threshold_num: # health_url = '/static/img/rain.png' # else: # health_url = '/static/img/sun.png' # # violation_info.update({ # 'created': build_info['datetime'], # 'health_url': health_url, # 'report_url': settings.JENKINS_URL + '/job/{job_name}/violations/'.format(job_name=obj.name) # }) # # return violation_info # # def get_links(self, obj): # request = self.context['request'] # return { # 'self': reverse('job-detail', kwargs={'pk': obj.pk}, request=request) # } , which may contain function names, class names, or code. Output only the next line.
raise Exception(e)
Given the following code snippet before the placeholder: <|code_start|># -*- encoding: utf-8 -*- User = get_user_model() class JobSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField() violation_info = serializers.SerializerMethodField() class Meta: model = Job <|code_end|> , predict the next line using imports from the current file: import json from datetime import date, datetime from django.conf import settings from django.contrib.auth import get_user_model from rest_framework import serializers from rest_framework.reverse import reverse from .models import Build, Job and context including class names, function names, and sometimes code from other files: # Path: src/app/models.py # class Build(models.Model): # # class Meta: # db_table = 'builds' # # number = models.IntegerField() # job = models.ForeignKey(Job, related_name="builds") # created = models.DateTimeField(auto_now_add=True) # result = models.TextField(default="") # # def __str__(self): # return "{0}:{1}".format(self.job.name, self.number) # # class Job(models.Model): # # class Meta: # db_table = 'jobs' # # name = models.CharField(unique=True, max_length=250) # description = models.TextField(blank=True, default='') # svn_url = models.TextField() # svn_username = models.TextField(blank=True, default='') # svn_password = models.TextField(blank=True, default='') # # recipient = models.TextField() # violation_threshold_num = models.IntegerField(default=888) # # def __str__(self): # return self.name . Output only the next line.
fields = ('id', 'name', 'description',
Predict the next line after this snippet: <|code_start|># -*- encoding: utf-8 -*- User = get_user_model() class JobSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField() violation_info = serializers.SerializerMethodField() class Meta: model = Job fields = ('id', 'name', 'description', 'svn_url', 'svn_username', 'svn_password', 'recipient', 'violation_threshold_num', 'links', 'violation_info') def get_violation_info(self, obj): last_builds = obj.builds.order_by('-number')[:1] violation_info = { "violation_file_num": -1, 'violation_num': -1, 'created': '0-0-0 0:0:0', 'health_url': '/static/img/rain.png', 'report_url': '' } if not last_builds: <|code_end|> using the current file's imports: import json from datetime import date, datetime from django.conf import settings from django.contrib.auth import get_user_model from rest_framework import serializers from rest_framework.reverse import reverse from .models import Build, Job and any relevant context from other files: # Path: src/app/models.py # class Build(models.Model): # # class Meta: # db_table = 'builds' # # number = models.IntegerField() # job = models.ForeignKey(Job, related_name="builds") # created = models.DateTimeField(auto_now_add=True) # result = models.TextField(default="") # # def __str__(self): # return "{0}:{1}".format(self.job.name, self.number) # # class Job(models.Model): # # class Meta: # db_table = 'jobs' # # name = models.CharField(unique=True, max_length=250) # description = models.TextField(blank=True, default='') # svn_url = models.TextField() # svn_username = models.TextField(blank=True, default='') # svn_password = models.TextField(blank=True, default='') # # recipient = models.TextField() # violation_threshold_num = models.IntegerField(default=888) # # def __str__(self): # return self.name . Output only the next line.
return violation_info
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # # Atizo - The Open Innovation Platform # http://www.atizo.com/ # # Copyright (c) 2008-2010 Atizo AG. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # class Command(NoArgsCommand): help = "Dumps the project db" flag = __name__ option_list = NoArgsCommand.option_list + ( make_option('--outputpath', <|code_end|> , predict the immediate next line with the help of imports: from django.core.management.base import NoArgsCommand from optparse import make_option from djangojames.db.utils import dump_db from django.db.utils import DEFAULT_DB_ALIAS from django.conf import settings and context (classes, functions, sometimes code) from other files: # Path: djangojames/db/utils.py # def dump_db(database_config, outputpath='/tmp/'): # db_engine = _get_engine(database_config) # database_config['OUTPUT_FILE'] = os.path.join(outputpath, get_dumpdb_name()) # #from fabric.api import local # # if db_engine in ['postgresql_psycopg2', 'postgresql']: # cmd = 'pg_dump -U postgres %(NAME)s > %(OUTPUT_FILE)s' % database_config # elif db_engine == 'mysql': # # if database_config['HOST']: # database_config['HOST'] = '--host %s' % database_config['HOST'] # cmd = '/usr/bin/mysqldump %(NAME)s %(HOST)s -u %(USER)s -p%(PASSWORD)s > %(OUTPUT_FILE)s' % database_config # else: # raise NotImplementedError, "This database backend is not yet supported: %s" % db_engine # # print cmd # call(cmd, shell=True) . Output only the next line.
help='a directory to write the dump to'),