Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
def refresh_info(self):
self.info = self.fetch_info()
return self.info
def commit_info(self):
if self.info:
self.cache.upload_single(
self.meta.join(self.mesh_path, 'info'),
jsonify(self.info),
content_type='application/json',
compress=False,
cache_control='no-cache',
)
def default_info(self):
return {
'@type': 'neuroglancer_legacy_mesh',
'spatial_index': None, # { 'chunk_size': physical units }
}
def is_sharded(self):
if 'sharding' not in self.info:
return False
elif self.info['sharding'] is None:
return False
else:
return True
def is_multires(self):
<|code_end|>
, predict the next line using imports from the current file:
import re
import numpy as np
from ....lib import jsonify
and context including class names, function names, and sometimes code from other files:
# Path: cloudvolume/lib.py
# def jsonify(obj, **kwargs):
# return json.dumps(obj, cls=NumpyEncoder, **kwargs)
. Output only the next line. | return self.info['@type'] == 'neuroglancer_multilod_draco' |
Predict the next line for this snippet: <|code_start|>CredentialType = Dict[str,Union[str,int]]
CredentialCacheType = Dict[str,CredentialType]
PROJECT_NAME = default_google_project_name()
GOOGLE_CREDENTIALS_CACHE:CredentialCacheType = {}
google_credentials_path = secretpath('secrets/google-secret.json')
def google_credentials(bucket = ''):
global PROJECT_NAME
global GOOGLE_CREDENTIALS_CACHE
if bucket in GOOGLE_CREDENTIALS_CACHE.keys():
return GOOGLE_CREDENTIALS_CACHE[bucket]
paths = [
secretpath('secrets/google-secret.json')
]
if bucket:
paths = [ secretpath('secrets/{}-google-secret.json'.format(bucket)) ] + paths
google_credentials = None
project_name = PROJECT_NAME
for google_credentials_path in paths:
if os.path.exists(google_credentials_path):
google_credentials = service_account.Credentials \
.from_service_account_file(google_credentials_path)
with open(google_credentials_path, 'rt') as f:
project_name = json.loads(f.read())['project_id']
<|code_end|>
with the help of current file imports:
from typing import Optional, Union, Dict
from collections import defaultdict
from google.oauth2 import service_account
from .lib import mkdir, colorize
import os
import json
and context from other files:
# Path: cloudvolume/lib.py
# def mkdir(path):
# path = toabs(path)
#
# try:
# if path != '' and not os.path.exists(path):
# os.makedirs(path)
# except OSError as e:
# if e.errno == 17: # File Exists
# time.sleep(0.1)
# return mkdir(path)
# else:
# raise
#
# return path
#
# def colorize(color, text):
# color = color.upper()
# return COLORS[color] + text + COLORS['RESET']
, which may contain function names, class names, or code. Output only the next line. | break |
Continue the code snippet: <|code_start|> secretpath('project_name')
]
def default_google_project_name():
if 'GOOGLE_PROJECT_NAME' in os.environ:
return os.environ['GOOGLE_PROJECT_NAME']
else:
for path in project_name_paths:
if os.path.exists(path):
with open(path, 'r') as f:
return f.read().strip()
default_credentials_path = secretpath('secrets/google-secret.json')
if os.path.exists(default_credentials_path):
with open(default_credentials_path, 'rt') as f:
return json.loads(f.read())['project_id']
return None
CredentialType = Dict[str,Union[str,int]]
CredentialCacheType = Dict[str,CredentialType]
PROJECT_NAME = default_google_project_name()
GOOGLE_CREDENTIALS_CACHE:CredentialCacheType = {}
google_credentials_path = secretpath('secrets/google-secret.json')
def google_credentials(bucket = ''):
global PROJECT_NAME
global GOOGLE_CREDENTIALS_CACHE
<|code_end|>
. Use current file imports:
from typing import Optional, Union, Dict
from collections import defaultdict
from google.oauth2 import service_account
from .lib import mkdir, colorize
import os
import json
and context (classes, functions, or code) from other files:
# Path: cloudvolume/lib.py
# def mkdir(path):
# path = toabs(path)
#
# try:
# if path != '' and not os.path.exists(path):
# os.makedirs(path)
# except OSError as e:
# if e.errno == 17: # File Exists
# time.sleep(0.1)
# return mkdir(path)
# else:
# raise
#
# return path
#
# def colorize(color, text):
# color = color.upper()
# return COLORS[color] + text + COLORS['RESET']
. Output only the next line. | if bucket in GOOGLE_CREDENTIALS_CACHE.keys(): |
Given snippet: <|code_start|>
# NOTE: Plugins are registered in __init__.py
# Set the interpreter bool
try:
INTERACTIVE = bool(sys.ps1)
except AttributeError:
INTERACTIVE = bool(sys.flags.interactive)
REGISTERED_PLUGINS = {}
def register_plugin(key, creation_function):
REGISTERED_PLUGINS[key.lower()] = creation_function
CompressType = Optional[Union[str,bool]]
ParallelType = Union[int,bool]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import time
import multiprocessing as mp
import numpy as np
from typing import Optional, Union
from .exceptions import UnsupportedFormatError, DimensionError
from .lib import generate_random_string
from .paths import strict_extract, to_https_protocol
from .frontends import CloudVolumePrecomputed
and context:
# Path: cloudvolume/exceptions.py
# class UnsupportedFormatError(Exception):
# """Unable to interpret the format of this URI. e.g. precomputed://"""
# pass
#
# class DimensionError(BaseException):
# """Wrong number of dimensions."""
# pass
#
# Path: cloudvolume/lib.py
# def generate_random_string(size=6):
# return ''.join(random.SystemRandom().choice(
# string.ascii_lowercase + string.digits) for _ in range(size)
# )
#
# Path: cloudvolume/paths.py
# def strict_extract(cloudpath, windows=None, disable_toabs=False):
# """
# Same as cloudvolume.paths.extract, but raise an additional
# cloudvolume.exceptions.UnsupportedProtocolError
# if either dataset or layer is not set.
#
# Returns: ExtractedPath
# """
# path = extract(cloudpath, windows, disable_toabs)
#
# if path.dataset == '' or path.layer == '':
# raise UnsupportedProtocolError(cloudpath_error(cloudpath))
#
# return path
#
# def to_https_protocol(cloudpath):
# if isinstance(cloudpath, ExtractedPath):
# if cloudpath.protocol in ('gs', 's3', 'matrix', 'tigerdata'):
# return extract(to_https_protocol(ascloudpath(cloudpath)))
# return cloudpath
#
# return cloudfiles.paths.to_https_protocol(cloudpath)
which might include code, classes, or functions. Output only the next line. | CacheType = Union[bool,str] |
Next line prediction: <|code_start|>
# NOTE: Plugins are registered in __init__.py
# Set the interpreter bool
try:
INTERACTIVE = bool(sys.ps1)
except AttributeError:
<|code_end|>
. Use current file imports:
(import sys
import time
import multiprocessing as mp
import numpy as np
from typing import Optional, Union
from .exceptions import UnsupportedFormatError, DimensionError
from .lib import generate_random_string
from .paths import strict_extract, to_https_protocol
from .frontends import CloudVolumePrecomputed)
and context including class names, function names, or small code snippets from other files:
# Path: cloudvolume/exceptions.py
# class UnsupportedFormatError(Exception):
# """Unable to interpret the format of this URI. e.g. precomputed://"""
# pass
#
# class DimensionError(BaseException):
# """Wrong number of dimensions."""
# pass
#
# Path: cloudvolume/lib.py
# def generate_random_string(size=6):
# return ''.join(random.SystemRandom().choice(
# string.ascii_lowercase + string.digits) for _ in range(size)
# )
#
# Path: cloudvolume/paths.py
# def strict_extract(cloudpath, windows=None, disable_toabs=False):
# """
# Same as cloudvolume.paths.extract, but raise an additional
# cloudvolume.exceptions.UnsupportedProtocolError
# if either dataset or layer is not set.
#
# Returns: ExtractedPath
# """
# path = extract(cloudpath, windows, disable_toabs)
#
# if path.dataset == '' or path.layer == '':
# raise UnsupportedProtocolError(cloudpath_error(cloudpath))
#
# return path
#
# def to_https_protocol(cloudpath):
# if isinstance(cloudpath, ExtractedPath):
# if cloudpath.protocol in ('gs', 's3', 'matrix', 'tigerdata'):
# return extract(to_https_protocol(ascloudpath(cloudpath)))
# return cloudpath
#
# return cloudfiles.paths.to_https_protocol(cloudpath)
. Output only the next line. | INTERACTIVE = bool(sys.flags.interactive) |
Predict the next line for this snippet: <|code_start|>
# NOTE: Plugins are registered in __init__.py
# Set the interpreter bool
try:
INTERACTIVE = bool(sys.ps1)
except AttributeError:
INTERACTIVE = bool(sys.flags.interactive)
<|code_end|>
with the help of current file imports:
import sys
import time
import multiprocessing as mp
import numpy as np
from typing import Optional, Union
from .exceptions import UnsupportedFormatError, DimensionError
from .lib import generate_random_string
from .paths import strict_extract, to_https_protocol
from .frontends import CloudVolumePrecomputed
and context from other files:
# Path: cloudvolume/exceptions.py
# class UnsupportedFormatError(Exception):
# """Unable to interpret the format of this URI. e.g. precomputed://"""
# pass
#
# class DimensionError(BaseException):
# """Wrong number of dimensions."""
# pass
#
# Path: cloudvolume/lib.py
# def generate_random_string(size=6):
# return ''.join(random.SystemRandom().choice(
# string.ascii_lowercase + string.digits) for _ in range(size)
# )
#
# Path: cloudvolume/paths.py
# def strict_extract(cloudpath, windows=None, disable_toabs=False):
# """
# Same as cloudvolume.paths.extract, but raise an additional
# cloudvolume.exceptions.UnsupportedProtocolError
# if either dataset or layer is not set.
#
# Returns: ExtractedPath
# """
# path = extract(cloudpath, windows, disable_toabs)
#
# if path.dataset == '' or path.layer == '':
# raise UnsupportedProtocolError(cloudpath_error(cloudpath))
#
# return path
#
# def to_https_protocol(cloudpath):
# if isinstance(cloudpath, ExtractedPath):
# if cloudpath.protocol in ('gs', 's3', 'matrix', 'tigerdata'):
# return extract(to_https_protocol(ascloudpath(cloudpath)))
# return cloudpath
#
# return cloudfiles.paths.to_https_protocol(cloudpath)
, which may contain function names, class names, or code. Output only the next line. | REGISTERED_PLUGINS = {} |
Continue the code snippet: <|code_start|> return os.path.join(
self._path.basepath, self._path.layer, file_path
)
def put_file(
self, file_path, content,
content_type, compress,
cache_control=None
):
path = self.get_path_to_file(file_path)
mkdir(os.path.dirname(path))
# keep default as gzip
if compress == "br":
path += ".br"
elif compress:
path += '.gz'
if content \
and content_type \
and re.search('json|te?xt', content_type) \
and type(content) is str:
content = content.encode('utf-8')
try:
with open(path, 'wb') as f:
f.write(content)
except IOError as err:
with open(path, 'wb') as f:
<|code_end|>
. Use current file imports:
import six
import json
import os.path
import posixpath
import re
import boto3
import botocore
import google.cloud.exceptions
import requests
import tenacity
import gc
from collections import defaultdict
from glob import glob
from google.cloud.storage import Batch, Client
from cloudvolume.connectionpools import S3ConnectionPool, GCloudBucketPool
from cloudvolume.lib import mkdir
from cloudvolume.exceptions import UnsupportedCompressionType
and context (classes, functions, or code) from other files:
# Path: cloudvolume/connectionpools.py
# class S3ConnectionPool(ConnectionPool):
# def __init__(self, service, bucket):
# self.service = service
# self.bucket = bucket
# self.credentials = aws_credentials(bucket, service)
# super(S3ConnectionPool, self).__init__()
#
# @retry
# def _create_connection(self):
# if self.service in ('aws', 's3'):
# return boto3.client(
# 's3',
# aws_access_key_id=self.credentials['AWS_ACCESS_KEY_ID'],
# aws_secret_access_key=self.credentials['AWS_SECRET_ACCESS_KEY'],
# region_name='us-east-1',
# )
# elif self.service == 'matrix':
# return boto3.client(
# 's3',
# aws_access_key_id=self.credentials['AWS_ACCESS_KEY_ID'],
# aws_secret_access_key=self.credentials['AWS_SECRET_ACCESS_KEY'],
# endpoint_url='https://s3-hpcrc.rc.princeton.edu',
# )
# else:
# raise UnsupportedProtocolError("{} unknown. Choose from 's3' or 'matrix'.", self.service)
#
# def close(self, conn):
# try:
# return conn.close()
# except AttributeError:
# pass # AttributeError: 'S3' object has no attribute 'close' on shutdown
#
# class GCloudBucketPool(ConnectionPool):
# def __init__(self, bucket):
# self.bucket = bucket
# self.project, self.credentials = google_credentials(bucket)
# super(GCloudBucketPool, self).__init__()
#
# @retry
# def _create_connection(self):
# client = Client(
# credentials=self.credentials,
# project=self.project,
# )
#
# return client.bucket(self.bucket)
#
# Path: cloudvolume/lib.py
# def mkdir(path):
# path = toabs(path)
#
# try:
# if path != '' and not os.path.exists(path):
# os.makedirs(path)
# except OSError as e:
# if e.errno == 17: # File Exists
# time.sleep(0.1)
# return mkdir(path)
# else:
# raise
#
# return path
#
# Path: cloudvolume/exceptions.py
# class UnsupportedCompressionType(ValueError):
# """
# Raised when attempting to use a compression type which is unsupported
# by the storage interface.
# """
. Output only the next line. | f.write(content) |
Given the following code snippet before the placeholder: <|code_start|> with open(path, 'wb') as f:
f.write(content)
def get_file(self, file_path, start=None, end=None):
path = self.get_path_to_file(file_path)
if os.path.exists(path + '.gz'):
encoding = "gzip"
path += '.gz'
elif os.path.exists(path + '.br'):
encoding = "br"
path += ".br"
else:
encoding = None
try:
with open(path, 'rb') as f:
if start is not None:
f.seek(start)
if end is not None:
start = start if start is not None else 0
num_bytes = end - start
data = f.read(num_bytes)
else:
data = f.read()
return data, encoding
except IOError:
return None, encoding
def exists(self, file_path):
<|code_end|>
, predict the next line using imports from the current file:
import six
import json
import os.path
import posixpath
import re
import boto3
import botocore
import google.cloud.exceptions
import requests
import tenacity
import gc
from collections import defaultdict
from glob import glob
from google.cloud.storage import Batch, Client
from cloudvolume.connectionpools import S3ConnectionPool, GCloudBucketPool
from cloudvolume.lib import mkdir
from cloudvolume.exceptions import UnsupportedCompressionType
and context including class names, function names, and sometimes code from other files:
# Path: cloudvolume/connectionpools.py
# class S3ConnectionPool(ConnectionPool):
# def __init__(self, service, bucket):
# self.service = service
# self.bucket = bucket
# self.credentials = aws_credentials(bucket, service)
# super(S3ConnectionPool, self).__init__()
#
# @retry
# def _create_connection(self):
# if self.service in ('aws', 's3'):
# return boto3.client(
# 's3',
# aws_access_key_id=self.credentials['AWS_ACCESS_KEY_ID'],
# aws_secret_access_key=self.credentials['AWS_SECRET_ACCESS_KEY'],
# region_name='us-east-1',
# )
# elif self.service == 'matrix':
# return boto3.client(
# 's3',
# aws_access_key_id=self.credentials['AWS_ACCESS_KEY_ID'],
# aws_secret_access_key=self.credentials['AWS_SECRET_ACCESS_KEY'],
# endpoint_url='https://s3-hpcrc.rc.princeton.edu',
# )
# else:
# raise UnsupportedProtocolError("{} unknown. Choose from 's3' or 'matrix'.", self.service)
#
# def close(self, conn):
# try:
# return conn.close()
# except AttributeError:
# pass # AttributeError: 'S3' object has no attribute 'close' on shutdown
#
# class GCloudBucketPool(ConnectionPool):
# def __init__(self, bucket):
# self.bucket = bucket
# self.project, self.credentials = google_credentials(bucket)
# super(GCloudBucketPool, self).__init__()
#
# @retry
# def _create_connection(self):
# client = Client(
# credentials=self.credentials,
# project=self.project,
# )
#
# return client.bucket(self.bucket)
#
# Path: cloudvolume/lib.py
# def mkdir(path):
# path = toabs(path)
#
# try:
# if path != '' and not os.path.exists(path):
# os.makedirs(path)
# except OSError as e:
# if e.errno == 17: # File Exists
# time.sleep(0.1)
# return mkdir(path)
# else:
# raise
#
# return path
#
# Path: cloudvolume/exceptions.py
# class UnsupportedCompressionType(ValueError):
# """
# Raised when attempting to use a compression type which is unsupported
# by the storage interface.
# """
. Output only the next line. | path = self.get_path_to_file(file_path) |
Using the snippet: <|code_start|> def __exit__(self, exception_type, exception_value, traceback):
self.release_connection()
class FileInterface(StorageInterface):
def __init__(self, path):
super(StorageInterface, self).__init__()
self._path = path
def get_path_to_file(self, file_path):
return os.path.join(
self._path.basepath, self._path.layer, file_path
)
def put_file(
self, file_path, content,
content_type, compress,
cache_control=None
):
path = self.get_path_to_file(file_path)
mkdir(os.path.dirname(path))
# keep default as gzip
if compress == "br":
path += ".br"
elif compress:
path += '.gz'
if content \
and content_type \
and re.search('json|te?xt', content_type) \
<|code_end|>
, determine the next line of code. You have imports:
import six
import json
import os.path
import posixpath
import re
import boto3
import botocore
import google.cloud.exceptions
import requests
import tenacity
import gc
from collections import defaultdict
from glob import glob
from google.cloud.storage import Batch, Client
from cloudvolume.connectionpools import S3ConnectionPool, GCloudBucketPool
from cloudvolume.lib import mkdir
from cloudvolume.exceptions import UnsupportedCompressionType
and context (class names, function names, or code) available:
# Path: cloudvolume/connectionpools.py
# class S3ConnectionPool(ConnectionPool):
# def __init__(self, service, bucket):
# self.service = service
# self.bucket = bucket
# self.credentials = aws_credentials(bucket, service)
# super(S3ConnectionPool, self).__init__()
#
# @retry
# def _create_connection(self):
# if self.service in ('aws', 's3'):
# return boto3.client(
# 's3',
# aws_access_key_id=self.credentials['AWS_ACCESS_KEY_ID'],
# aws_secret_access_key=self.credentials['AWS_SECRET_ACCESS_KEY'],
# region_name='us-east-1',
# )
# elif self.service == 'matrix':
# return boto3.client(
# 's3',
# aws_access_key_id=self.credentials['AWS_ACCESS_KEY_ID'],
# aws_secret_access_key=self.credentials['AWS_SECRET_ACCESS_KEY'],
# endpoint_url='https://s3-hpcrc.rc.princeton.edu',
# )
# else:
# raise UnsupportedProtocolError("{} unknown. Choose from 's3' or 'matrix'.", self.service)
#
# def close(self, conn):
# try:
# return conn.close()
# except AttributeError:
# pass # AttributeError: 'S3' object has no attribute 'close' on shutdown
#
# class GCloudBucketPool(ConnectionPool):
# def __init__(self, bucket):
# self.bucket = bucket
# self.project, self.credentials = google_credentials(bucket)
# super(GCloudBucketPool, self).__init__()
#
# @retry
# def _create_connection(self):
# client = Client(
# credentials=self.credentials,
# project=self.project,
# )
#
# return client.bucket(self.bucket)
#
# Path: cloudvolume/lib.py
# def mkdir(path):
# path = toabs(path)
#
# try:
# if path != '' and not os.path.exists(path):
# os.makedirs(path)
# except OSError as e:
# if e.errno == 17: # File Exists
# time.sleep(0.1)
# return mkdir(path)
# else:
# raise
#
# return path
#
# Path: cloudvolume/exceptions.py
# class UnsupportedCompressionType(ValueError):
# """
# Raised when attempting to use a compression type which is unsupported
# by the storage interface.
# """
. Output only the next line. | and type(content) is str: |
Continue the code snippet: <|code_start|>
if sys.version_info < (3,):
integer_types = (int, long, np.integer)
string_types = (str, basestring, unicode)
else:
integer_types = (int, np.integer)
string_types = (str,)
floating_types = (float, np.floating)
COLORS = {
'RESET': "\033[m",
'YELLOW': "\033[1;93m",
<|code_end|>
. Use current file imports:
from typing import Union, Sequence, List, cast
from functools import reduce
from itertools import product
from PIL import Image
from tqdm import tqdm
from .exceptions import OutOfBoundsError
import decimal
import json
import math
import operator
import os
import random
import re
import sys
import time
import types
import string
import numpy as np
and context (classes, functions, or code) from other files:
# Path: cloudvolume/exceptions.py
# class OutOfBoundsError(ValueError):
# """
# Raised upon trying to obtain or assign to a bbox of a volume outside
# of the volume's bounds
# """
. Output only the next line. | 'RED': '\033[1;91m', |
Here is a snippet: <|code_start|>
ExtractedPath = namedtuple('ExtractedPath',
('format', 'protocol', 'bucket', 'basepath', 'no_bucket_basepath', 'dataset', 'layer')
)
ALLOWED_PROTOCOLS = cloudfiles.paths.ALLOWED_PROTOCOLS
ALLOWED_FORMATS = [ 'graphene', 'precomputed', 'boss' ]
<|code_end|>
. Write the next line using the current file imports:
import cloudfiles.paths
import os
import posixpath
import re
import sys
from collections import namedtuple
from .exceptions import UnsupportedProtocolError
from .lib import yellow, toabs
and context from other files:
# Path: cloudvolume/exceptions.py
# class UnsupportedProtocolError(ValueError):
# """Unknown protocol extension."""
# pass
#
# Path: cloudvolume/lib.py
# def yellow(text):
# return colorize('yellow', text)
#
# def toabs(path):
# path = os.path.expanduser(path)
# return os.path.abspath(path)
, which may include functions, classes, or code. Output only the next line. | def cloudpath_error(cloudpath): |
Predict the next line for this snippet: <|code_start|>
retry = tenacity.retry(
reraise=True,
stop=tenacity.stop_after_attempt(7),
wait=tenacity.wait_random_exponential(0.5, 60.0),
<|code_end|>
with the help of current file imports:
from six.moves import queue as Queue
from functools import partial
from google.cloud.storage import Client
from .secrets import google_credentials, aws_credentials
from .exceptions import UnsupportedProtocolError
import threading
import time
import boto3
import tenacity
and context from other files:
# Path: cloudvolume/secrets.py
# def google_credentials(bucket = ''):
# global PROJECT_NAME
# global GOOGLE_CREDENTIALS_CACHE
#
# if bucket in GOOGLE_CREDENTIALS_CACHE.keys():
# return GOOGLE_CREDENTIALS_CACHE[bucket]
#
# paths = [
# secretpath('secrets/google-secret.json')
# ]
#
# if bucket:
# paths = [ secretpath('secrets/{}-google-secret.json'.format(bucket)) ] + paths
#
# google_credentials = None
# project_name = PROJECT_NAME
# for google_credentials_path in paths:
# if os.path.exists(google_credentials_path):
# google_credentials = service_account.Credentials \
# .from_service_account_file(google_credentials_path)
#
# with open(google_credentials_path, 'rt') as f:
# project_name = json.loads(f.read())['project_id']
# break
#
# if google_credentials == None:
# print(colorize('yellow', 'Using default Google credentials. There is no ~/.cloudvolume/secrets/google-secret.json set.'))
# else:
# GOOGLE_CREDENTIALS_CACHE[bucket] = (project_name, google_credentials)
#
# return project_name, google_credentials
#
# def aws_credentials(bucket = '', service = 'aws'):
# global AWS_CREDENTIALS_CACHE
#
# if service == 's3':
# service = 'aws'
#
# if bucket in AWS_CREDENTIALS_CACHE.keys():
# return AWS_CREDENTIALS_CACHE[bucket]
#
# default_file_path = 'secrets/{}-secret.json'.format(service)
#
# paths = [
# secretpath(default_file_path)
# ]
#
# if bucket:
# paths = [ secretpath('secrets/{}-{}-secret.json'.format(bucket, service)) ] + paths
#
# aws_credentials = {}
# aws_credentials_path = secretpath(default_file_path)
# for aws_credentials_path in paths:
# if os.path.exists(aws_credentials_path):
# with open(aws_credentials_path, 'r') as f:
# aws_credentials = json.loads(f.read())
# break
#
# if not aws_credentials:
# # did not find any secret json file, will try to find it in environment variables
# if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
# aws_credentials = {
# 'AWS_ACCESS_KEY_ID': os.environ['AWS_ACCESS_KEY_ID'],
# 'AWS_SECRET_ACCESS_KEY': os.environ['AWS_SECRET_ACCESS_KEY'],
# }
# if 'AWS_DEFAULT_REGION' in os.environ:
# aws_credentials['AWS_DEFAULT_REGION'] = os.environ['AWS_DEFAULT_REGION']
#
# AWS_CREDENTIALS_CACHE[service][bucket] = aws_credentials
# return aws_credentials
#
# Path: cloudvolume/exceptions.py
# class UnsupportedProtocolError(ValueError):
# """Unknown protocol extension."""
# pass
, which may contain function names, class names, or code. Output only the next line. | ) |
Continue the code snippet: <|code_start|>
NOTICE = {
'vertices': 0,
'num_vertices': 0,
'faces': 0,
}
def deprecation_notice(key):
<|code_end|>
. Use current file imports:
import copy
import re
import struct
import numpy as np
import DracoPy
import vtk
from .exceptions import MeshDecodeError
from .lib import yellow, Vec
and context (classes, functions, or code) from other files:
# Path: cloudvolume/exceptions.py
# class MeshDecodeError(ValueError):
# """Unable to decode a mesh object."""
# pass
#
# Path: cloudvolume/lib.py
# def yellow(text):
# return colorize('yellow', text)
#
# class Vec(np.ndarray):
# def __new__(cls, *args, **kwargs):
# if 'dtype' in kwargs:
# dtype = kwargs['dtype']
# elif floating(args):
# dtype = float
# else:
# dtype = int
#
# return super(Vec, cls).__new__(cls, shape=(len(args),), buffer=np.array(args).astype(dtype), dtype=dtype)
#
# @classmethod
# def clamp(cls, val, minvec, maxvec):
# x = np.minimum.reduce([
# np.maximum.reduce([val,minvec]),
# maxvec
# ])
# return Vec(*x)
#
# def clone(self):
# return Vec(*self[:], dtype=self.dtype)
#
# def null(self):
# return self.length() <= 10 * np.finfo(np.float32).eps
#
# def dot(self, vec):
# return sum(self * vec)
#
# def length2(self):
# return self.dot(self)
#
# def length(self):
# return math.sqrt(self.dot(self))
#
# def rectVolume(self):
# return reduce(operator.mul, self)
#
# def __hash__(self):
# return int(''.join(map(str, self)))
#
# def __repr__(self):
# values = ",".join([ str(x) for x in self ])
# return f"Vec({values}, dtype={self.dtype})"
. Output only the next line. | if NOTICE[key] < 1: |
Next line prediction: <|code_start|> # normal_vector_map = np.vectorize(lambda idx: normals[idx])
# eff_normals = normal_vector_map(uniq_idx)
return Mesh(eff_verts, eff_faces, None,
segid=self.segid,
encoding_type=copy.deepcopy(self.encoding_type),
encoding_options=copy.deepcopy(self.encoding_options),
)
@classmethod
def from_precomputed(self, binary, segid=None):
"""
Mesh from_precomputed(self, binary)
Decode a Precomputed format mesh from a byte string.
Format:
uint32 Nv * float32 * 3 uint32 * 3 until end
Nv (x,y,z) (v1,v2,v2)
N Vertices Vertices Faces
"""
num_vertices = struct.unpack("=I", binary[0:4])[0]
try:
# count=-1 means all data in buffer
vertices = np.frombuffer(binary, dtype=np.float32, count=3*num_vertices, offset=4)
faces = np.frombuffer(binary, dtype=np.uint32, count=-1, offset=(4 + 12 * num_vertices))
except ValueError:
raise MeshDecodeError("""
The input buffer is too small for the Precomputed format.
Minimum Bytes: {}
<|code_end|>
. Use current file imports:
(import copy
import re
import struct
import numpy as np
import DracoPy
import vtk
from .exceptions import MeshDecodeError
from .lib import yellow, Vec)
and context including class names, function names, or small code snippets from other files:
# Path: cloudvolume/exceptions.py
# class MeshDecodeError(ValueError):
# """Unable to decode a mesh object."""
# pass
#
# Path: cloudvolume/lib.py
# def yellow(text):
# return colorize('yellow', text)
#
# class Vec(np.ndarray):
# def __new__(cls, *args, **kwargs):
# if 'dtype' in kwargs:
# dtype = kwargs['dtype']
# elif floating(args):
# dtype = float
# else:
# dtype = int
#
# return super(Vec, cls).__new__(cls, shape=(len(args),), buffer=np.array(args).astype(dtype), dtype=dtype)
#
# @classmethod
# def clamp(cls, val, minvec, maxvec):
# x = np.minimum.reduce([
# np.maximum.reduce([val,minvec]),
# maxvec
# ])
# return Vec(*x)
#
# def clone(self):
# return Vec(*self[:], dtype=self.dtype)
#
# def null(self):
# return self.length() <= 10 * np.finfo(np.float32).eps
#
# def dot(self, vec):
# return sum(self * vec)
#
# def length2(self):
# return self.dot(self)
#
# def length(self):
# return math.sqrt(self.dot(self))
#
# def rectVolume(self):
# return reduce(operator.mul, self)
#
# def __hash__(self):
# return int(''.join(map(str, self)))
#
# def __repr__(self):
# values = ",".join([ str(x) for x in self ])
# return f"Vec({values}, dtype={self.dtype})"
. Output only the next line. | Actual Bytes: {} |
Given the following code snippet before the placeholder: <|code_start|> # normal_vector_map = np.vectorize(lambda idx: normals[idx])
# eff_normals = normal_vector_map(uniq_idx)
return Mesh(eff_verts, eff_faces, None,
segid=self.segid,
encoding_type=copy.deepcopy(self.encoding_type),
encoding_options=copy.deepcopy(self.encoding_options),
)
@classmethod
def from_precomputed(self, binary, segid=None):
"""
Mesh from_precomputed(self, binary)
Decode a Precomputed format mesh from a byte string.
Format:
uint32 Nv * float32 * 3 uint32 * 3 until end
Nv (x,y,z) (v1,v2,v2)
N Vertices Vertices Faces
"""
num_vertices = struct.unpack("=I", binary[0:4])[0]
try:
# count=-1 means all data in buffer
vertices = np.frombuffer(binary, dtype=np.float32, count=3*num_vertices, offset=4)
faces = np.frombuffer(binary, dtype=np.uint32, count=-1, offset=(4 + 12 * num_vertices))
except ValueError:
raise MeshDecodeError("""
The input buffer is too small for the Precomputed format.
Minimum Bytes: {}
<|code_end|>
, predict the next line using imports from the current file:
import copy
import re
import struct
import numpy as np
import DracoPy
import vtk
from .exceptions import MeshDecodeError
from .lib import yellow, Vec
and context including class names, function names, and sometimes code from other files:
# Path: cloudvolume/exceptions.py
# class MeshDecodeError(ValueError):
# """Unable to decode a mesh object."""
# pass
#
# Path: cloudvolume/lib.py
# def yellow(text):
# return colorize('yellow', text)
#
# class Vec(np.ndarray):
# def __new__(cls, *args, **kwargs):
# if 'dtype' in kwargs:
# dtype = kwargs['dtype']
# elif floating(args):
# dtype = float
# else:
# dtype = int
#
# return super(Vec, cls).__new__(cls, shape=(len(args),), buffer=np.array(args).astype(dtype), dtype=dtype)
#
# @classmethod
# def clamp(cls, val, minvec, maxvec):
# x = np.minimum.reduce([
# np.maximum.reduce([val,minvec]),
# maxvec
# ])
# return Vec(*x)
#
# def clone(self):
# return Vec(*self[:], dtype=self.dtype)
#
# def null(self):
# return self.length() <= 10 * np.finfo(np.float32).eps
#
# def dot(self, vec):
# return sum(self * vec)
#
# def length2(self):
# return self.dot(self)
#
# def length(self):
# return math.sqrt(self.dot(self))
#
# def rectVolume(self):
# return reduce(operator.mul, self)
#
# def __hash__(self):
# return int(''.join(map(str, self)))
#
# def __repr__(self):
# values = ",".join([ str(x) for x in self ])
# return f"Vec({values}, dtype={self.dtype})"
. Output only the next line. | Actual Bytes: {} |
Next line prediction: <|code_start|> assert a.chunks == a2.chunks
@pytest.mark.skipif(sys.version_info[0] < 3, reason="Python 2 not supported.")
def test_roundtrip_4d_channel_rechunked():
da = pytest.importorskip('dask.array')
du = pytest.importorskip('dask.utils')
a = da.random.randint(100, size=(3, 3, 3, 3), chunks=(2, 2, 2, 3))
with du.tmpdir() as d:
d = 'file://' + d
dasklib.to_cloudvolume(a, d)
a2 = dasklib.from_cloudvolume(d)
np.testing.assert_array_equal(a.compute(), a2.compute())
# Channel has single chunk
assert a2.chunks == ((2, 1), (2, 1), (2, 1), (3, ))
@pytest.mark.skipif(sys.version_info[0] < 3, reason="Python 2 not supported.")
def test_roundtrip_4d_1channel():
da = pytest.importorskip('dask.array')
du = pytest.importorskip('dask.utils')
a = da.random.randint(100, size=(3, 3, 3, 1))
with du.tmpdir() as d:
d = 'file://' + d
dasklib.to_cloudvolume(a, d)
a2 = dasklib.from_cloudvolume(d)
da.utils.assert_eq(a, a2, check_type=False)
assert a.chunks == a2.chunks
@pytest.mark.skipif(sys.version_info[0] < 3, reason="Python 2 not supported.")
def test_roundtrip_rechunk_3d():
da = pytest.importorskip('dask.array')
<|code_end|>
. Use current file imports:
(import os
import pytest
import sys
import numpy as np
from cloudvolume import dask as dasklib)
and context including class names, function names, or small code snippets from other files:
# Path: cloudvolume/dask.py
# def to_cloudvolume(arr,
# cloudpath,
# resolution=(1, 1, 1),
# voxel_offset=(0, 0, 0),
# layer_type=None,
# encoding='raw',
# max_mip=0,
# compute=True,
# return_stored=False,
# **kwargs):
# def _create_cloudvolume(cloudpath, info, **kwargs):
# def from_cloudvolume(cloudpath, chunks=None, name=None, **kwargs):
. Output only the next line. | du = pytest.importorskip('dask.utils') |
Given snippet: <|code_start|> lru[i] = i
assert 0 < lru.nbytes <= small_int_bytes * base_size
for i in range(100):
lru[i] = i
assert 0 < lru.nbytes <= small_int_bytes * base_size
assert len(lru) == 5
lru.resize(size * 2)
for i in range(5):
lru[i] = i
assert 0 < lru.nbytes <= small_int_bytes * base_size * 2
assert lru.queue.tolist() == [
(4,4), (3,3), (2,2), (1,1), (0,0),
(99,99), (98,98), (97,97), (96,96), (95,95)
]
lru.resize(size)
assert lru.queue.tolist() == [
(4,4), (3,3), (2,2), (1,1), (0,0)
]
assert 0 < lru.nbytes <= small_int_bytes * base_size
assert lru[0] == 0
assert lru.queue.tolist() == [
(0,0), (4,4), (3,3), (2,2), (1,1)
]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import time
import random
import sys
from cloudvolume.lru import LRU
and context:
# Path: cloudvolume/lru.py
# class LRU:
# """
# A Least Recently Used dict implementation based on
# a dict + a doubly linked list.
# """
# def __init__(self, size:int = 100, size_in_bytes:bool = False):
# """
# size specifies the upper inclusive limit to the size of the
# LRU.
#
# If size_in_bytes is False, this refers to the number of elements
# in the LRU.
# If size_in_bytes is True, this refers to the size in bytes of the
# stored elements (not counting internal data structures of the LRU)
# as measured by sys.getsizeof which does not handle nested objects
# (unless they implement a __sizeof__ handler).
#
# Therefore, size_in_bytes is most easily used with Python base types.
# It was designed for with byte strings in mind that represent file
# content.
# """
# self.size = int(size)
# self.size_in_bytes = size_in_bytes
# self.nbytes = 0
# self.queue = DoublyLinkedList()
# self.hash = {}
# self.lock = threading.Lock()
#
# def __len__(self):
# return self.queue.size
#
# def keys(self):
# return self.hash.keys()
#
# def values(self):
# return ( node.val for val in self.queue )
#
# def items(self):
# return ( (key, node.val) for key, node in self.hash.items() )
#
# def is_oversized(self):
# if self.size_in_bytes:
# return self.nbytes > self.size
# return len(self.queue) > self.size
#
# def clear(self):
# with self.lock:
# self.queue = DoublyLinkedList()
# self.hash = {}
# self.nbytes = 0
#
# def resize(self, new_size):
# if new_size < 0:
# raise ValueError("The LRU limit must be a positive number. Got: " + str(new_size))
#
# if new_size == 0:
# self.clear()
# return
#
# with self.lock:
# try:
# if new_size >= self.size:
# return
# finally:
# self.size = int(new_size)
#
# while self.is_oversized():
# (key,val) = self.queue.delete_tail()
# del self.hash[key]
# self.nbytes -= sys.getsizeof(val)
#
# def delete(self, key):
# with self.lock:
# if key not in self.hash:
# raise KeyError("{} not in cache.".format(key))
#
# node = self.hash[key]
# self.queue.delete(node)
# del self.hash[key]
# self.nbytes -= sys.getsizeof(node.val)
# return node.val
#
# def pop(self, key, *args):
# try:
# return self.delete(key)
# except KeyError:
# if len(args):
# return args[0]
# raise
#
# def get(self, key, default=None):
# with self.lock:
# if key not in self.hash:
# if default is None:
# raise KeyError("{} not in cache.".format(key))
# return default
#
# node = self.hash[key]
# self.queue.promote_to_head(node)
#
# return node.val[1]
#
# def set(self, key, val):
# with self.lock:
# if self.size == 0:
# return
#
# pair = (key,val)
# if key in self.hash:
# node = self.hash[key]
# node.val = pair
# self.queue.promote_to_head(node)
# return
#
# self.queue.prepend(pair)
# self.hash[key] = self.queue.head
# self.nbytes += sys.getsizeof(val)
#
# while self.is_oversized():
# (tkey,tval) = self.queue.delete_tail()
# del self.hash[tkey]
# self.nbytes -= sys.getsizeof(tval)
#
# def __contains__(self, key):
# return key in self.hash
#
# def __getitem__(self, key):
# return self.get(key)
#
# def __setitem__(self, key, val):
# return self.set(key, val)
#
# def __delitem__(self, key):
# return self.delete(key)
#
# def __str__(self):
# return str(self.queue)
#
# def __getstate__(self):
# # Copy the object's state from self.__dict__ which contains
# # all our instance attributes. Always use the dict.copy()
# # method to avoid modifying the original state.
# state = self.__dict__.copy()
# # Remove the unpicklable entries.
# del state['lock']
# return state
#
# def __setstate__(self, state):
# # Restore instance attributes (i.e., filename and lineno).
# self.__dict__.update(state)
# self.lock = threading.Lock()
which might include code, classes, or functions. Output only the next line. | def test_lru_chaos(): |
Given snippet: <|code_start|> self.info = self.default_info()
@property
def spatial_index(self):
if 'spatial_index' in self.info:
return self.info['spatial_index']
return None
@property
def skeleton_path(self):
if 'skeletons' in self.meta.info:
return self.meta.info['skeletons']
return 'skeletons'
@property
def mip(self):
if 'mip' in self.info:
return int(self.info['mip'])
# Igneous has long used skeletons_mip_N to store
# some information about the skeletonizing job. Let's
# exploit that for now.
matches = re.search(SKEL_MIP_REGEXP, self.skeleton_path)
if matches is None:
return None
mip, = matches.groups()
return int(mip)
def join(self, *paths):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import re
import numpy as np
from ....lib import jsonify
and context:
# Path: cloudvolume/lib.py
# def jsonify(obj, **kwargs):
# return json.dumps(obj, cls=NumpyEncoder, **kwargs)
which might include code, classes, or functions. Output only the next line. | return self.meta.join(*paths) |
Given the following code snippet before the placeholder: <|code_start|>
def test_create_campaign():
campaign = models.Campaign('test')
campaign.put()
<|code_end|>
, predict the next line using imports from the current file:
import time
from mothership import models
and context including class names, function names, and sometimes code from other files:
# Path: mothership/models.py
# def init_db():
# def process_bind_param(self, value, dialect):
# def process_result_value(self, value, dialect):
# def get(cls, **kwargs):
# def all(cls, **kwargs):
# def create(cls, **kwargs):
# def put(self):
# def delete(self):
# def commit():
# def update(self, **kwargs):
# def update_all(cls, **kwargs):
# def to_dict(self):
# def children(self):
# def __init__(self, name):
# def started(self):
# def active_fuzzers(self):
# def master_fuzzer(self):
# def num_executions(self):
# def num_crashes(self):
# def bitmap_cvg(self):
# def name(self):
# def campaign(self):
# def started(self):
# def running(self):
# class JsonType(types.TypeDecorator):
# class Model:
# class Campaign(Model, db.Model):
# class FuzzerInstance(Model, db.Model):
# class FuzzerSnapshot(Model, db.Model):
# class Crash(Model, db.Model):
. Output only the next line. | assert campaign.id > 0
|
Given the code snippet: <|code_start|>
class CampaignForm(Form):
name = StringField('Name', validators=[validators.required()])
executable_name = StringField('Executable Name', validators=[validators.required()], default='executable')
executable_args = StringField('Executable Args', default='@@')
afl_args = StringField('AFL Args', default='-m 100 -t 50+')
copy_of = SelectField('Copy of', coerce=int, choices=[(-1, 'None')])
desired_fuzzers = IntegerField('Desired Fuzzers')
executable = FileField()
libraries = FileField(
render_kw={'multiple': True},
)
testcases = FileField(
render_kw={'multiple': True},
)
ld_preload = FileField(
'LD PRELOAD',
render_kw={'multiple': True},
)
dictionary = FileField()
use_libdislocator = BooleanField('Use libdislocator')
def validate(self):
<|code_end|>
, generate the next line using the imports in this file:
import os
from flask import current_app
from flask_wtf import Form
from werkzeug.utils import secure_filename
from wtforms import StringField, SelectField, IntegerField, BooleanField
from flask_wtf.file import FileField
from wtforms import validators
from mothership.models import Campaign
and context (functions, classes, or occasionally code) from other files:
# Path: mothership/models.py
# class Campaign(Model, db.Model):
# __tablename__ = 'campaign'
#
# name = db.Column(db.String(128))
# fuzzers = db.relationship('FuzzerInstance', backref='fuzzer', lazy='dynamic')
# crashes = db.relationship('Crash', backref='campaign', lazy='dynamic')
#
# active = db.Column(db.Boolean(), default=False)
# desired_fuzzers = db.Column(db.Integer())
#
# has_dictionary = db.Column(db.Boolean(), default=False)
# executable_name = db.Column(db.String(512))
# executable_args = db.Column(db.String(1024))
# afl_args = db.Column(db.String(1024))
#
# parent_id = db.Column(db.Integer, db.ForeignKey('campaign.id'))
# @property
# def children(self):
# return Campaign.all(parent_id=self.id)
#
# def __init__(self, name):
# self.name = name
#
# @property
# def started(self):
# return bool(self.fuzzers.filter(FuzzerInstance.last_update).first())
#
# @property
# def active_fuzzers(self):
# return sum(i.running for i in self.fuzzers if not i.master)
#
# @property
# def master_fuzzer(self):
# return self.fuzzers.filter_by(master=True).first()
#
# @property
# def num_executions(self):
# return sum(i.execs_done for i in self.fuzzers if i.started)
#
# @property
# def num_crashes(self):
# return sum(i.unique_crashes for i in self.fuzzers if i.started)
#
# @property
# def bitmap_cvg(self):
# if not self.started:
# return 0, 0
# bitmap_cvgs = []
# newest = self.fuzzers.order_by(desc(FuzzerInstance.last_update)).first()
# for fuzzer in self.fuzzers.filter(FuzzerInstance.last_update):
# if newest.last_update - fuzzer.last_update < 10 * 60:
# bitmap_cvgs.append(fuzzer.bitmap_cvg)
# return statistics.mean(bitmap_cvgs), statistics.stdev(bitmap_cvgs) if len(bitmap_cvgs) > 1 else 0.
. Output only the next line. | check_validate = super().validate() |
Predict the next line after this snippet: <|code_start|> return 'Campaign already has a master', 400
instance = models.FuzzerInstance.create(hostname=hostname, master=True)
instance.start_time = time.time()
campaign.fuzzers.append(instance)
campaign.commit()
# avoid all hosts uploading at the same time from reporting at the same time
deviation = random.randint(15, 30)
return jsonify(
id=instance.id,
name=secure_filename(instance.name),
program=campaign.executable_name,
program_args=campaign.executable_args.split(' ') if campaign.executable_args else [], # TODO: add support for spaces
args=campaign.afl_args.split(' ') if campaign.afl_args else [],
campaign_id=campaign.id,
campaign_name=secure_filename(campaign.name),
download=request.host_url[:-1] + url_for('fuzzers.download', campaign_id=campaign.id),
submit=request.host_url[:-1] + url_for('fuzzers.submit', instance_id=instance.id),
submit_crash=request.host_url[:-1] + url_for('fuzzers.submit_crash', instance_id=instance.id),
upload=request.host_url[:-1] + url_for('fuzzers.upload', instance_id=instance.id),
upload_in=current_app.config['UPLOAD_FREQUENCY'] + deviation
)
@fuzzers.route('/fuzzers/terminate/<int:instance_id>', methods=['POST'])
def terminate(instance_id):
instance = models.FuzzerInstance.get(id=instance_id)
instance.update(terminated=True)
<|code_end|>
using the current file's imports:
import glob
import io
import os
import tarfile
import random
import time
from flask import Blueprint, jsonify, request, current_app, send_file, url_for
from werkzeug.utils import secure_filename
from mothership import models
and any relevant context from other files:
# Path: mothership/models.py
# def init_db():
# def process_bind_param(self, value, dialect):
# def process_result_value(self, value, dialect):
# def get(cls, **kwargs):
# def all(cls, **kwargs):
# def create(cls, **kwargs):
# def put(self):
# def delete(self):
# def commit():
# def update(self, **kwargs):
# def update_all(cls, **kwargs):
# def to_dict(self):
# def children(self):
# def __init__(self, name):
# def started(self):
# def active_fuzzers(self):
# def master_fuzzer(self):
# def num_executions(self):
# def num_crashes(self):
# def bitmap_cvg(self):
# def name(self):
# def campaign(self):
# def started(self):
# def running(self):
# class JsonType(types.TypeDecorator):
# class Model:
# class Campaign(Model, db.Model):
# class FuzzerInstance(Model, db.Model):
# class FuzzerSnapshot(Model, db.Model):
# class Crash(Model, db.Model):
. Output only the next line. | instance.commit() |
Here is a snippet: <|code_start|> copy.desired_fuzzers = size
copy.has_dictionary = original.has_dictionary
copy.executable_name = original.executable_name
copy.executable_args = original.executable_args
copy.afl_args = original.afl_args
copy.parent_id = original.id
copy.put()
dir = os.path.join(current_app.config['DATA_DIRECTORY'], secure_filename(copy.name))
os.mkdir(dir)
for tocopy in ['executable', 'libraries', 'testcases', 'ld_preload', 'dictionary']:
original_path = os.path.join(original_dir, tocopy)
new_path = os.path.join(dir, tocopy)
if os.path.exists(original_path):
if os.path.isdir(original_path):
shutil.copytree(original_path, new_path)
else:
shutil.copy(original_path, new_path)
flash('Tests created', 'info')
return redirect(url_for('campaigns.campaign', campaign_id=original.id))
else:
return render_template('make-tests.html', campaign=original, form=form)
@campaigns.route('/campaigns/<int:campaign_id>', methods=['GET', 'POST'])
def campaign(campaign_id):
campaign_model = models.Campaign.get(id=campaign_id)
if not campaign_model:
return 'Campaign not found', 404
if request.method == 'POST':
dir = os.path.join(current_app.config['DATA_DIRECTORY'], secure_filename(campaign_model.name))
if 'delete' in request.form:
<|code_end|>
. Write the next line using the current file imports:
import shutil
import subprocess
import time
import os
import sqlalchemy
from flask import Blueprint, render_template, render_template_string, flash, redirect, request, url_for, jsonify, current_app
from datetime import datetime
from sqlalchemy import case
from werkzeug.utils import secure_filename
from mothership import forms, models
from mothership.utils import format_timedelta_secs, pretty_size_dec, format_ago
and context from other files:
# Path: mothership/forms.py
# class CampaignForm(Form):
# class MakeTestsForm(Form):
# def validate(self):
# def validate(self):
#
# Path: mothership/models.py
# def init_db():
# def process_bind_param(self, value, dialect):
# def process_result_value(self, value, dialect):
# def get(cls, **kwargs):
# def all(cls, **kwargs):
# def create(cls, **kwargs):
# def put(self):
# def delete(self):
# def commit():
# def update(self, **kwargs):
# def update_all(cls, **kwargs):
# def to_dict(self):
# def children(self):
# def __init__(self, name):
# def started(self):
# def active_fuzzers(self):
# def master_fuzzer(self):
# def num_executions(self):
# def num_crashes(self):
# def bitmap_cvg(self):
# def name(self):
# def campaign(self):
# def started(self):
# def running(self):
# class JsonType(types.TypeDecorator):
# class Model:
# class Campaign(Model, db.Model):
# class FuzzerInstance(Model, db.Model):
# class FuzzerSnapshot(Model, db.Model):
# class Crash(Model, db.Model):
#
# Path: mothership/utils.py
# def format_timedelta_secs(secs, time_format='{days} days {hours} hours {minutes} minutes'):
# return format_timedelta(datetime.timedelta(seconds=secs), time_format=time_format)
#
# def pretty_size_dec(value):
# return pretty_size(value, b=1000, u = '', pre = ['', 'Thousand', 'Million', 'Billion'])
#
# def format_ago(current_time, ago):
# return (format_timedelta_secs(current_time - ago) + ' ago') if ago else 'none so far',
, which may include functions, classes, or code. Output only the next line. | return redirect(url_for('campaigns.delete', campaign_id=campaign_id)) |
Predict the next line for this snippet: <|code_start|>
def get_ldd(campaign_model):
env = dict(os.environ)
if 'LD_LIBRARY_PATH' in env:
env['LD_LIBRARY_PATH'] = ':' + env['LD_LIBRARY_PATH']
else:
env['LD_LIBRARY_PATH'] = ''
env['LD_LIBRARY_PATH'] = os.path.join(current_app.config['DATA_DIRECTORY'], secure_filename(campaign_model.name), 'libraries') + env['LD_LIBRARY_PATH']
try:
p = subprocess.Popen(['ldd', os.path.join(current_app.config['DATA_DIRECTORY'], secure_filename(campaign_model.name), 'executable')], env=env, stdout=subprocess.PIPE)
process_output = p.communicate()
except FileNotFoundError:
ldd = None
else:
ldd = []
for line in process_output[0].decode('ascii').split('\n'):
if not line or line[0] != '\t':
continue
parts = line.split()
if len(parts) < 3:
continue
found = 'not found' not in line
if found:
path = parts[2]
if path.startswith(current_app.config['DATA_DIRECTORY']):
ldd_row = (parts[0], 'info', path.rsplit(os.path.sep, 1)[-1])
else:
ldd_row = (parts[0], '', path)
else:
<|code_end|>
with the help of current file imports:
import shutil
import subprocess
import time
import os
import sqlalchemy
from flask import Blueprint, render_template, render_template_string, flash, redirect, request, url_for, jsonify, current_app
from datetime import datetime
from sqlalchemy import case
from werkzeug.utils import secure_filename
from mothership import forms, models
from mothership.utils import format_timedelta_secs, pretty_size_dec, format_ago
and context from other files:
# Path: mothership/forms.py
# class CampaignForm(Form):
# class MakeTestsForm(Form):
# def validate(self):
# def validate(self):
#
# Path: mothership/models.py
# def init_db():
# def process_bind_param(self, value, dialect):
# def process_result_value(self, value, dialect):
# def get(cls, **kwargs):
# def all(cls, **kwargs):
# def create(cls, **kwargs):
# def put(self):
# def delete(self):
# def commit():
# def update(self, **kwargs):
# def update_all(cls, **kwargs):
# def to_dict(self):
# def children(self):
# def __init__(self, name):
# def started(self):
# def active_fuzzers(self):
# def master_fuzzer(self):
# def num_executions(self):
# def num_crashes(self):
# def bitmap_cvg(self):
# def name(self):
# def campaign(self):
# def started(self):
# def running(self):
# class JsonType(types.TypeDecorator):
# class Model:
# class Campaign(Model, db.Model):
# class FuzzerInstance(Model, db.Model):
# class FuzzerSnapshot(Model, db.Model):
# class Crash(Model, db.Model):
#
# Path: mothership/utils.py
# def format_timedelta_secs(secs, time_format='{days} days {hours} hours {minutes} minutes'):
# return format_timedelta(datetime.timedelta(seconds=secs), time_format=time_format)
#
# def pretty_size_dec(value):
# return pretty_size(value, b=1000, u = '', pre = ['', 'Thousand', 'Million', 'Billion'])
#
# def format_ago(current_time, ago):
# return (format_timedelta_secs(current_time - ago) + ' ago') if ago else 'none so far',
, which may contain function names, class names, or code. Output only the next line. | ldd_row = (parts[0], 'danger', 'Not Found') |
Next line prediction: <|code_start|> return redirect(url_for('campaigns.campaign', campaign_id=original.id))
else:
return render_template('make-tests.html', campaign=original, form=form)
@campaigns.route('/campaigns/<int:campaign_id>', methods=['GET', 'POST'])
def campaign(campaign_id):
campaign_model = models.Campaign.get(id=campaign_id)
if not campaign_model:
return 'Campaign not found', 404
if request.method == 'POST':
dir = os.path.join(current_app.config['DATA_DIRECTORY'], secure_filename(campaign_model.name))
if 'delete' in request.form:
return redirect(url_for('campaigns.delete', campaign_id=campaign_id))
if 'enable' in request.form:
campaign_model.active = request.form['enable'].lower() == 'true'
campaign_model.put()
if campaign_model.active:
flash('Campaign enabled', 'success')
else:
flash('Campaign disabled', 'success')
if 'reset' in request.form:
reset_campaign(campaign_model)
flash('Campaign reset', 'success')
if 'activate_children' in request.form:
for child in campaign_model.children:
child.active = True
child.put()
if 'deactivate_children' in request.form:
for child in campaign_model.children:
child.active = False
<|code_end|>
. Use current file imports:
(import shutil
import subprocess
import time
import os
import sqlalchemy
from flask import Blueprint, render_template, render_template_string, flash, redirect, request, url_for, jsonify, current_app
from datetime import datetime
from sqlalchemy import case
from werkzeug.utils import secure_filename
from mothership import forms, models
from mothership.utils import format_timedelta_secs, pretty_size_dec, format_ago)
and context including class names, function names, or small code snippets from other files:
# Path: mothership/forms.py
# class CampaignForm(Form):
# class MakeTestsForm(Form):
# def validate(self):
# def validate(self):
#
# Path: mothership/models.py
# def init_db():
# def process_bind_param(self, value, dialect):
# def process_result_value(self, value, dialect):
# def get(cls, **kwargs):
# def all(cls, **kwargs):
# def create(cls, **kwargs):
# def put(self):
# def delete(self):
# def commit():
# def update(self, **kwargs):
# def update_all(cls, **kwargs):
# def to_dict(self):
# def children(self):
# def __init__(self, name):
# def started(self):
# def active_fuzzers(self):
# def master_fuzzer(self):
# def num_executions(self):
# def num_crashes(self):
# def bitmap_cvg(self):
# def name(self):
# def campaign(self):
# def started(self):
# def running(self):
# class JsonType(types.TypeDecorator):
# class Model:
# class Campaign(Model, db.Model):
# class FuzzerInstance(Model, db.Model):
# class FuzzerSnapshot(Model, db.Model):
# class Crash(Model, db.Model):
#
# Path: mothership/utils.py
# def format_timedelta_secs(secs, time_format='{days} days {hours} hours {minutes} minutes'):
# return format_timedelta(datetime.timedelta(seconds=secs), time_format=time_format)
#
# def pretty_size_dec(value):
# return pretty_size(value, b=1000, u = '', pre = ['', 'Thousand', 'Million', 'Billion'])
#
# def format_ago(current_time, ago):
# return (format_timedelta_secs(current_time - ago) + ' ago') if ago else 'none so far',
. Output only the next line. | child.put() |
Given snippet: <|code_start|> if form.executable.has_file():
form.executable.data.save(os.path.join(dir, 'executable'))
elif other:
shutil.copy(os.path.join(other, 'executable'), os.path.join(dir, 'executable'))
for config_files in ['libraries', 'testcases', 'ld_preload']:
dest = os.path.join(dir, config_files)
if getattr(form, config_files).has_file():
os.makedirs(dest)
for lib in request.files.getlist(config_files):
lib.save(os.path.join(dest, os.path.basename(lib.filename)))
elif other:
shutil.copytree(os.path.join(other, config_files), dest)
else:
os.makedirs(dest)
if form.use_libdislocator.data:
shutil.copy(os.path.join(current_app.config['DATA_DIRECTORY'], 'libdislocator.so'), os.path.join(dir, 'ld_preload'))
dictionary = os.path.join(dir, 'dictionary')
if form.dictionary.has_file():
form.dictionary.data.save(dictionary)
model.has_dictionary = True
model.commit()
elif other and os.path.exists(os.path.join(other, 'dictionary')):
shutil.copy(os.path.join(other, 'dictionary'), os.path.join(dir, 'dictionary'))
model.has_dictionary = True
model.commit()
flash('Campaign created', 'success')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import shutil
import subprocess
import time
import os
import sqlalchemy
from flask import Blueprint, render_template, render_template_string, flash, redirect, request, url_for, jsonify, current_app
from datetime import datetime
from sqlalchemy import case
from werkzeug.utils import secure_filename
from mothership import forms, models
from mothership.utils import format_timedelta_secs, pretty_size_dec, format_ago
and context:
# Path: mothership/forms.py
# class CampaignForm(Form):
# class MakeTestsForm(Form):
# def validate(self):
# def validate(self):
#
# Path: mothership/models.py
# def init_db():
# def process_bind_param(self, value, dialect):
# def process_result_value(self, value, dialect):
# def get(cls, **kwargs):
# def all(cls, **kwargs):
# def create(cls, **kwargs):
# def put(self):
# def delete(self):
# def commit():
# def update(self, **kwargs):
# def update_all(cls, **kwargs):
# def to_dict(self):
# def children(self):
# def __init__(self, name):
# def started(self):
# def active_fuzzers(self):
# def master_fuzzer(self):
# def num_executions(self):
# def num_crashes(self):
# def bitmap_cvg(self):
# def name(self):
# def campaign(self):
# def started(self):
# def running(self):
# class JsonType(types.TypeDecorator):
# class Model:
# class Campaign(Model, db.Model):
# class FuzzerInstance(Model, db.Model):
# class FuzzerSnapshot(Model, db.Model):
# class Crash(Model, db.Model):
#
# Path: mothership/utils.py
# def format_timedelta_secs(secs, time_format='{days} days {hours} hours {minutes} minutes'):
# return format_timedelta(datetime.timedelta(seconds=secs), time_format=time_format)
#
# def pretty_size_dec(value):
# return pretty_size(value, b=1000, u = '', pre = ['', 'Thousand', 'Million', 'Billion'])
#
# def format_ago(current_time, ago):
# return (format_timedelta_secs(current_time - ago) + ' ago') if ago else 'none so far',
which might include code, classes, or functions. Output only the next line. | return redirect(request.args.get('next') or url_for('campaigns.campaign', campaign_id=model.id)) |
Predict the next line after this snippet: <|code_start|> child.put()
if 'deactivate_children' in request.form:
for child in campaign_model.children:
child.active = False
child.put()
if 'delete_children' in request.form:
for child in campaign_model.children:
delete_campaign(child)
if 'reset_children' in request.form:
for child in campaign_model.children:
reset_campaign(child)
uploaded = 0
for lib in request.files.getlist('libraries'):
if lib.filename:
lib.save(os.path.join(dir, 'libraries', os.path.basename(lib.filename)))
uploaded += 1
for test in request.files.getlist('testcases'):
if test.filename:
test.save(os.path.join(dir, 'testcases', os.path.basename(test.filename)))
uploaded += 1
if uploaded:
flash('Uploaded %d files' % uploaded, 'success')
return redirect(url_for('campaigns.campaign', campaign_id=campaign_id))
# TODO show campaign options, allow editing and show ldd output
crashes = campaign_model.crashes.filter_by(analyzed=True, crash_in_debugger=True).group_by(models.Crash.backtrace).order_by(case({
'EXPLOITABLE': 0,
'PROBABLY_EXPLOITABLE': 1,
'UNKNOWN': 2,
<|code_end|>
using the current file's imports:
import shutil
import subprocess
import time
import os
import sqlalchemy
from flask import Blueprint, render_template, render_template_string, flash, redirect, request, url_for, jsonify, current_app
from datetime import datetime
from sqlalchemy import case
from werkzeug.utils import secure_filename
from mothership import forms, models
from mothership.utils import format_timedelta_secs, pretty_size_dec, format_ago
and any relevant context from other files:
# Path: mothership/forms.py
# class CampaignForm(Form):
# class MakeTestsForm(Form):
# def validate(self):
# def validate(self):
#
# Path: mothership/models.py
# def init_db():
# def process_bind_param(self, value, dialect):
# def process_result_value(self, value, dialect):
# def get(cls, **kwargs):
# def all(cls, **kwargs):
# def create(cls, **kwargs):
# def put(self):
# def delete(self):
# def commit():
# def update(self, **kwargs):
# def update_all(cls, **kwargs):
# def to_dict(self):
# def children(self):
# def __init__(self, name):
# def started(self):
# def active_fuzzers(self):
# def master_fuzzer(self):
# def num_executions(self):
# def num_crashes(self):
# def bitmap_cvg(self):
# def name(self):
# def campaign(self):
# def started(self):
# def running(self):
# class JsonType(types.TypeDecorator):
# class Model:
# class Campaign(Model, db.Model):
# class FuzzerInstance(Model, db.Model):
# class FuzzerSnapshot(Model, db.Model):
# class Crash(Model, db.Model):
#
# Path: mothership/utils.py
# def format_timedelta_secs(secs, time_format='{days} days {hours} hours {minutes} minutes'):
# return format_timedelta(datetime.timedelta(seconds=secs), time_format=time_format)
#
# def pretty_size_dec(value):
# return pretty_size(value, b=1000, u = '', pre = ['', 'Thousand', 'Million', 'Billion'])
#
# def format_ago(current_time, ago):
# return (format_timedelta_secs(current_time - ago) + ' ago') if ago else 'none so far',
. Output only the next line. | 'PROBABLY_NOT_EXPLOITABLE': 3}, |
Given the code snippet: <|code_start|>
def test_davidson():
np.random.seed(0)
dim = 1000
A = np.diag(np.arange(dim,dtype=np.float64))
A[1:3,1:3] = 0
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from mmd.utils.davidson import davidson
and context (functions, classes, or occasionally code) from other files:
# Path: mmd/utils/davidson.py
# def davidson(A,roots,tol=1e-8):
#
# mat_dim = A.shape[0]
# sub_dim = 4*roots
# V = np.eye(mat_dim,sub_dim)
#
# converged = False
# while not converged:
# # subspace
# S = np.dot(V.T,np.dot(A,V))
#
# # diag subspace
# E,C = scipy.linalg.eigh(S) # note already ordered if using eigh
# E,C = E[:roots], C[:,:roots]
#
# # get current approx. eigenvectors
# X = np.dot(V,C)
#
# # form residual vectors
# R = np.zeros((mat_dim,roots))
# Delta = np.zeros((mat_dim,roots))
# unconverged = []
# for j in range(roots):
# R[:,j] = np.dot((A - E[j] * np.eye(mat_dim)),X[:,j])
# if np.linalg.norm(R[:,j]) > tol:
# unconverged.append(j)
#
# # check convergence
# if len(unconverged) < 1:
# converged = True
#
# for j in unconverged:
# preconditioner = np.zeros(mat_dim)
# for i in range(mat_dim):
# if np.abs(E[j] - A[i,i]) < 1e-4:
# continue # don't let preconditioner blow up -- keep as zero
# else:
# preconditioner[i] = -1/(A[i,i] - E[j])
#
# # normalize correction vectors
# Delta[:,j] = preconditioner * R[:,j]
# Delta[:,j] /= np.linalg.norm(Delta[:,j])
#
# # project corrections onto orthogonal complement
# q = np.dot((np.eye(mat_dim) - np.dot(V,V.T)),Delta[:,j])
# norm = np.linalg.norm(q)
#
# if (norm > 1e-4):
# if (sub_dim + 1 > min(500,mat_dim//4)):
# # subspace collapse
# print("Subspace too big: collapsing")
# print("Eigs at current: ", E)
# sub_dim = roots # restart uses best guess of eigenvecs
# V = X
# V, _ = np.linalg.qr(V)
# break
#
# else:
# V_copy = np.copy(V)
# sub_dim += 1
# V = np.eye(mat_dim,sub_dim)
# V[:,:(sub_dim-1)] = V_copy
# # add new vector to end of subspace
# V[:,-1] = q/norm
#
# if converged:
# return E, X
. Output only the next line. | M = np.random.randn(dim,dim) |
Based on the snippet: <|code_start|>
x, y = reshape_data(x, y)
data_scaler = StandardScaler()
x = data_scaler.fit_transform(x)
lda = LDA()
lda.fit(x, y)
coef = lda.scalings_ * lda.coef_[:1].T
channels = []
fbins = []
for c in range(n_channels):
fbins.extend(range(n_fbins)) # 0- delta, 1- theta ...
channels.extend([c] * n_fbins)
if plot:
fig = plt.figure()
for i in range(n_channels):
if n_channels == 24:
fig.add_subplot(4, 6, i)
else:
fig.add_subplot(4, 4, i)
ax = plt.gca()
ax.set_xlim([0, n_fbins])
ax.set_xticks(np.arange(0.5, n_fbins + 0.5, 1))
ax.set_xticklabels(np.arange(0, n_fbins))
max_y = max(abs(coef)) + 0.01
ax.set_ylim([0, max_y])
ax.set_yticks(np.around(np.arange(0, max_y, max_y / 4.0), decimals=1))
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
label.set_fontsize(15)
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import json
import os
import matplotlib.pyplot as plt
import preprocessors.fft as fft
from pandas import DataFrame
from sklearn.preprocessing import StandardScaler
from sklearn.lda import LDA
from utils.loader import load_test_data, load_train_data
from utils.config_name_creator import *
from merger import merge_csv_files
from commons import reshape_data
from commons import load_test_labels
and context (classes, functions, sometimes code) from other files:
# Path: utils/loader.py
# def load_test_data(data_path, subject):
# read_dir = data_path + '/' + subject
# data, id = [], []
# filenames = sorted(os.listdir(read_dir))
# for filename in sorted(filenames, key=lambda x: int(re.search(r'(\d+).mat', x).group(1))):
# if 'test' in filename or 'holdout' in filename:
# data.append(loadmat(read_dir + '/' + filename, squeeze_me=True))
# id.append(filename)
#
# n_test = len(data)
# x = np.zeros(((n_test,) + data[0]['data'].shape), dtype='float32')
# for i, datum in enumerate(data):
# x[i] = datum['data']
#
# return {'x': x, 'id': id}
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | plt.bar(range(0, n_fbins), abs(coef[i * n_fbins:i * n_fbins + n_fbins])) |
Given the code snippet: <|code_start|> channels = []
fbins = []
for c in range(n_channels):
fbins.extend(range(n_fbins)) # 0- delta, 1- theta ...
channels.extend([c] * n_fbins)
if plot:
fig = plt.figure()
for i in range(n_channels):
if n_channels == 24:
fig.add_subplot(4, 6, i)
else:
fig.add_subplot(4, 4, i)
ax = plt.gca()
ax.set_xlim([0, n_fbins])
ax.set_xticks(np.arange(0.5, n_fbins + 0.5, 1))
ax.set_xticklabels(np.arange(0, n_fbins))
max_y = max(abs(coef)) + 0.01
ax.set_ylim([0, max_y])
ax.set_yticks(np.around(np.arange(0, max_y, max_y / 4.0), decimals=1))
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
label.set_fontsize(15)
plt.bar(range(0, n_fbins), abs(coef[i * n_fbins:i * n_fbins + n_fbins]))
fig.suptitle(subject, fontsize=20)
plt.show()
coefs = np.reshape(coef, (n_channels, n_fbins))
return lda, data_scaler, coefs
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import json
import os
import matplotlib.pyplot as plt
import preprocessors.fft as fft
from pandas import DataFrame
from sklearn.preprocessing import StandardScaler
from sklearn.lda import LDA
from utils.loader import load_test_data, load_train_data
from utils.config_name_creator import *
from merger import merge_csv_files
from commons import reshape_data
from commons import load_test_labels
and context (functions, classes, or occasionally code) from other files:
# Path: utils/loader.py
# def load_test_data(data_path, subject):
# read_dir = data_path + '/' + subject
# data, id = [], []
# filenames = sorted(os.listdir(read_dir))
# for filename in sorted(filenames, key=lambda x: int(re.search(r'(\d+).mat', x).group(1))):
# if 'test' in filename or 'holdout' in filename:
# data.append(loadmat(read_dir + '/' + filename, squeeze_me=True))
# id.append(filename)
#
# n_test = len(data)
# x = np.zeros(((n_test,) + data[0]['data'].shape), dtype='float32')
# for i, datum in enumerate(data):
# x[i] = datum['data']
#
# return {'x': x, 'id': id}
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | def predict(subject, model, data_scaler, data_path, submission_path, test_labels, opt_threshold_train): |
Based on the snippet: <|code_start|> def __init__(self, rng, input, nkerns, recept_width, pool_width, stride, training_mode, dropout_prob, activation,
weights_variance, n_channels, n_timesteps, n_fbins, global_pooling):
self.layer0 = ConvPoolLayer(rng, input=input,
image_shape=(None, 1, n_channels * n_fbins, n_timesteps),
filter_shape=(nkerns[0], 1, n_fbins * n_channels, recept_width[0]),
poolsize=(1, pool_width[0]), activation=activation[0],
weights_variance=weights_variance, subsample=(1, stride[0]))
input_layer1_width = ((n_timesteps - recept_width[0]) / stride[0] + 1) / pool_width[0]
self.layer1 = ConvPoolLayer(rng, input=self.layer0.output,
image_shape=(None, nkerns[0], 1, input_layer1_width),
filter_shape=(nkerns[1], nkerns[0], 1, recept_width[1]),
poolsize=(1, pool_width[1]), activation=activation[1],
weights_variance=weights_variance, subsample=(1, stride[1]))
if global_pooling:
self.glob_pool = GlobalPoolLayer(self.layer1.output)
layer2_input = self.glob_pool.output.flatten(2)
input_layer2_shape = nkerns[1] * 6
self.layer2 = HiddenLayer(rng=rng, input=layer2_input,
n_in=input_layer2_shape, n_out=nkerns[2],
training_mode=training_mode,
dropout_prob=dropout_prob, activation=activation[2],
weights_variance=weights_variance)
else:
layer2_input = self.layer1.output.flatten(2)
input_layer2_size = ((input_layer1_width - recept_width[1]) / stride[1] + 1) / pool_width[1]
self.layer2 = HiddenLayer(rng=rng, input=layer2_input,
n_in=nkerns[1] * input_layer2_size, n_out=nkerns[2],
<|code_end|>
, predict the immediate next line with the help of imports:
from layers.hidden_layer import HiddenLayer
from layers.conv_layer import ConvPoolLayer
from glob_pool_layer import GlobalPoolLayer
and context (classes, functions, sometimes code) from other files:
# Path: layers/hidden_layer.py
# class HiddenLayer(object):
# def __init__(self, rng, input, n_in, n_out, training_mode, dropout_prob, activation, weights_variance):
# self.input = input
# if activation == 'tanh':
# activation_function = lambda x: T.tanh(x)
# W_values = np.asarray(rng.uniform(
# low=-np.sqrt(6. / (n_in + n_out)),
# high=np.sqrt(6. / (n_in + n_out)),
# size=(n_in, n_out)), dtype='float32')
# b_values = np.zeros((n_out,), dtype='float32')
#
# elif activation == 'relu':
# activation_function = lambda x: T.maximum(0.0, x)
# W_values = np.asarray(rng.normal(0.0, weights_variance, size=(n_in, n_out)), dtype='float32')
# b_values = np.ones((n_out,), dtype='float32') / 10.0
# else:
# raise ValueError('unknown activation function')
#
# self.W = theano.shared(value=W_values, name='W', borrow=True)
# self.b = theano.shared(value=b_values, name='b', borrow=True)
#
# inv_dropout_prob = np.float32(1.0 - dropout_prob)
# lin_output = ifelse(T.eq(training_mode, 1),
# T.dot(self._dropout(rng, input, dropout_prob), self.W) + self.b,
# T.dot(input, inv_dropout_prob * self.W) + self.b)
#
# self.output = activation_function(lin_output)
# self.weights = [self.W, self.b]
#
# def _dropout(self, rng, layer, p):
# srng = T.shared_randomstreams.RandomStreams(rng.randint(777777))
# mask = srng.binomial(n=1, p=1 - p, size=layer.shape)
# output = layer * T.cast(mask, 'float32')
# return output
#
# Path: layers/conv_layer.py
# class ConvPoolLayer(object):
# def __init__(self, rng, input, filter_shape, image_shape, poolsize, activation, weights_variance, subsample):
#
# assert image_shape[1] == filter_shape[1]
# self.input =input
#
# if activation == 'tanh':
# activation_function = lambda x: T.tanh(x)
# fan_in = np.prod(filter_shape[1:])
# fan_out = (filter_shape[0] * np.prod(filter_shape[2:]) / np.prod(poolsize))
# W_bound = np.sqrt(6. / (fan_in + fan_out))
# W_values = np.asarray(rng.uniform(low=-W_bound, high=W_bound, size=filter_shape), dtype='float32')
# b_values = np.zeros((filter_shape[0],), dtype='float32')
#
# elif activation == 'relu':
# activation_function = lambda x: T.maximum(0.0, x)
# W_values = np.asarray(rng.normal(0.0, weights_variance, size=filter_shape), dtype='float32')
# b_values = np.ones((filter_shape[0],), dtype='float32') / 10.0
# else:
# raise ValueError('unknown activation function')
#
# self.W = theano.shared(value=W_values, name='W', borrow=True)
# self.b = theano.shared(value=b_values, name='b', borrow=True)
#
# conv_out = conv.conv2d(input, self.W, filter_shape=filter_shape, image_shape=image_shape, subsample=subsample)
# pooled_out = downsample.max_pool_2d(conv_out, poolsize, ignore_border=True) if poolsize[1] > 1 else conv_out
# self.output = activation_function(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))
# self.weights = [self.W, self.b]
. Output only the next line. | training_mode=training_mode, |
Given the code snippet: <|code_start|>
class FeatureExtractor(object):
def __init__(self, rng, input, nkerns, recept_width, pool_width, stride, training_mode, dropout_prob, activation,
weights_variance, n_channels, n_timesteps, n_fbins, global_pooling):
self.layer0 = ConvPoolLayer(rng, input=input,
image_shape=(None, 1, n_channels * n_fbins, n_timesteps),
filter_shape=(nkerns[0], 1, n_fbins * n_channels, recept_width[0]),
poolsize=(1, pool_width[0]), activation=activation[0],
weights_variance=weights_variance, subsample=(1, stride[0]))
input_layer1_width = ((n_timesteps - recept_width[0]) / stride[0] + 1) / pool_width[0]
self.layer1 = ConvPoolLayer(rng, input=self.layer0.output,
image_shape=(None, nkerns[0], 1, input_layer1_width),
filter_shape=(nkerns[1], nkerns[0], 1, recept_width[1]),
poolsize=(1, pool_width[1]), activation=activation[1],
weights_variance=weights_variance, subsample=(1, stride[1]))
if global_pooling:
<|code_end|>
, generate the next line using the imports in this file:
from layers.hidden_layer import HiddenLayer
from layers.conv_layer import ConvPoolLayer
from glob_pool_layer import GlobalPoolLayer
and context (functions, classes, or occasionally code) from other files:
# Path: layers/hidden_layer.py
# class HiddenLayer(object):
# def __init__(self, rng, input, n_in, n_out, training_mode, dropout_prob, activation, weights_variance):
# self.input = input
# if activation == 'tanh':
# activation_function = lambda x: T.tanh(x)
# W_values = np.asarray(rng.uniform(
# low=-np.sqrt(6. / (n_in + n_out)),
# high=np.sqrt(6. / (n_in + n_out)),
# size=(n_in, n_out)), dtype='float32')
# b_values = np.zeros((n_out,), dtype='float32')
#
# elif activation == 'relu':
# activation_function = lambda x: T.maximum(0.0, x)
# W_values = np.asarray(rng.normal(0.0, weights_variance, size=(n_in, n_out)), dtype='float32')
# b_values = np.ones((n_out,), dtype='float32') / 10.0
# else:
# raise ValueError('unknown activation function')
#
# self.W = theano.shared(value=W_values, name='W', borrow=True)
# self.b = theano.shared(value=b_values, name='b', borrow=True)
#
# inv_dropout_prob = np.float32(1.0 - dropout_prob)
# lin_output = ifelse(T.eq(training_mode, 1),
# T.dot(self._dropout(rng, input, dropout_prob), self.W) + self.b,
# T.dot(input, inv_dropout_prob * self.W) + self.b)
#
# self.output = activation_function(lin_output)
# self.weights = [self.W, self.b]
#
# def _dropout(self, rng, layer, p):
# srng = T.shared_randomstreams.RandomStreams(rng.randint(777777))
# mask = srng.binomial(n=1, p=1 - p, size=layer.shape)
# output = layer * T.cast(mask, 'float32')
# return output
#
# Path: layers/conv_layer.py
# class ConvPoolLayer(object):
# def __init__(self, rng, input, filter_shape, image_shape, poolsize, activation, weights_variance, subsample):
#
# assert image_shape[1] == filter_shape[1]
# self.input =input
#
# if activation == 'tanh':
# activation_function = lambda x: T.tanh(x)
# fan_in = np.prod(filter_shape[1:])
# fan_out = (filter_shape[0] * np.prod(filter_shape[2:]) / np.prod(poolsize))
# W_bound = np.sqrt(6. / (fan_in + fan_out))
# W_values = np.asarray(rng.uniform(low=-W_bound, high=W_bound, size=filter_shape), dtype='float32')
# b_values = np.zeros((filter_shape[0],), dtype='float32')
#
# elif activation == 'relu':
# activation_function = lambda x: T.maximum(0.0, x)
# W_values = np.asarray(rng.normal(0.0, weights_variance, size=filter_shape), dtype='float32')
# b_values = np.ones((filter_shape[0],), dtype='float32') / 10.0
# else:
# raise ValueError('unknown activation function')
#
# self.W = theano.shared(value=W_values, name='W', borrow=True)
# self.b = theano.shared(value=b_values, name='b', borrow=True)
#
# conv_out = conv.conv2d(input, self.W, filter_shape=filter_shape, image_shape=image_shape, subsample=subsample)
# pooled_out = downsample.max_pool_2d(conv_out, poolsize, ignore_border=True) if poolsize[1] > 1 else conv_out
# self.output = activation_function(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))
# self.weights = [self.W, self.b]
. Output only the next line. | self.glob_pool = GlobalPoolLayer(self.layer1.output) |
Using the snippet: <|code_start|> x_train = np.concatenate(x_train, axis=3)
x_train = np.rollaxis(x_train, axis=3)
y_train = np.array(y_train)
x_valid = [x[..., np.newaxis] for x in x_valid]
x_valid = np.concatenate(x_valid, axis=3)
x_valid = np.rollaxis(x_valid, axis=3)
y_valid = np.array(y_valid)
n_valid_examples = x_valid.shape[0]
n_timesteps = x_valid.shape[-1]
x_train, y_train = reshape_data(x_train, y_train)
data_scaler = StandardScaler()
x_train = data_scaler.fit_transform(x_train)
logreg = LogisticRegression(C=reg_C)
logreg.fit(x_train, y_train)
x_valid = reshape_data(x_valid)
x_valid = data_scaler.transform(x_valid)
p_valid = predict(logreg, x_valid, n_valid_examples, n_timesteps)
preictal_probs.extend(p_valid)
labels.extend(y_valid)
return preictal_probs, labels
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import json, os
import preprocessors.fft as fft
import cPickle
from utils.loader import load_grouped_train_data, load_train_data
from utils.config_name_creator import *
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import log_loss, roc_curve, auc
from commons import reshape_data
and context (class names, function names, or code) available:
# Path: utils/loader.py
# def load_grouped_train_data(data_path, subject, files_names_grouped_by_hour):
# def fill_data_grouped_by_hour(class_label, train_filenames):
# current_group_idx = 0
# current_ten_minutes_idx = 0
# for i, filename in enumerate(train_filenames):
# if subject + '/' + filename not in files_names_grouped_by_hour[subject][class_label][current_group_idx]:
# raise ValueError(
# '{}/{} not in group for {}{}{}'.format(subject, filename, subject, class_label, current_group_idx))
# if current_ten_minutes_idx == 0:
# data_grouped_by_hour[class_label].append([])
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# data_grouped_by_hour[class_label][-1].append(datum['data'])
# current_ten_minutes_idx += 1
# if len(data_grouped_by_hour[class_label][-1]) == len(
# files_names_grouped_by_hour[subject][class_label][current_group_idx]):
# current_group_idx += 1
# current_ten_minutes_idx = 0
#
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = [filename for filename in filenames if 'test' not in filename]
# interictal_train_filenames = [filename for filename in train_filenames if 'interictal' in filename]
# preictal_train_filenames = [filename for filename in train_filenames if 'preictal' in filename]
#
# data_grouped_by_hour = defaultdict(lambda: [])
# fill_data_grouped_by_hour('interictal', interictal_train_filenames)
# fill_data_grouped_by_hour('preictal', preictal_train_filenames)
#
# return data_grouped_by_hour
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | def run_trainer(): |
Continue the code snippet: <|code_start|>
def predict(model, x_test, n_test_examples, n_timesteps):
pred_1m = model.predict_proba(x_test)[:, 1]
pred_10m = np.reshape(pred_1m, (n_test_examples, n_timesteps))
pred_10m = np.mean(pred_10m, axis=1)
return pred_10m
def cross_validate(subject, data_path, reg_C, random_cv=False):
if random_cv:
d = load_train_data(data_path,subject)
x, y = d['x'], d['y']
skf = StratifiedKFold(y, n_folds=10)
else:
filenames_grouped_by_hour = cPickle.load(open('filenames.pickle'))
data_grouped_by_hour = load_grouped_train_data(data_path, subject, filenames_grouped_by_hour)
n_preictal, n_interictal = len(data_grouped_by_hour['preictal']), len(data_grouped_by_hour['interictal'])
hours_data = data_grouped_by_hour['preictal'] + data_grouped_by_hour['interictal']
hours_labels = np.concatenate((np.ones(n_preictal), np.zeros(n_interictal)))
n_folds = n_preictal
skf = StratifiedKFold(hours_labels, n_folds=n_folds)
preictal_probs, labels = [], []
for train_indexes, valid_indexes in skf:
x_train, x_valid = [], []
y_train, y_valid = [], []
<|code_end|>
. Use current file imports:
import numpy as np
import json, os
import preprocessors.fft as fft
import cPickle
from utils.loader import load_grouped_train_data, load_train_data
from utils.config_name_creator import *
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import log_loss, roc_curve, auc
from commons import reshape_data
and context (classes, functions, or code) from other files:
# Path: utils/loader.py
# def load_grouped_train_data(data_path, subject, files_names_grouped_by_hour):
# def fill_data_grouped_by_hour(class_label, train_filenames):
# current_group_idx = 0
# current_ten_minutes_idx = 0
# for i, filename in enumerate(train_filenames):
# if subject + '/' + filename not in files_names_grouped_by_hour[subject][class_label][current_group_idx]:
# raise ValueError(
# '{}/{} not in group for {}{}{}'.format(subject, filename, subject, class_label, current_group_idx))
# if current_ten_minutes_idx == 0:
# data_grouped_by_hour[class_label].append([])
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# data_grouped_by_hour[class_label][-1].append(datum['data'])
# current_ten_minutes_idx += 1
# if len(data_grouped_by_hour[class_label][-1]) == len(
# files_names_grouped_by_hour[subject][class_label][current_group_idx]):
# current_group_idx += 1
# current_ten_minutes_idx = 0
#
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = [filename for filename in filenames if 'test' not in filename]
# interictal_train_filenames = [filename for filename in train_filenames if 'interictal' in filename]
# preictal_train_filenames = [filename for filename in train_filenames if 'preictal' in filename]
#
# data_grouped_by_hour = defaultdict(lambda: [])
# fill_data_grouped_by_hour('interictal', interictal_train_filenames)
# fill_data_grouped_by_hour('preictal', preictal_train_filenames)
#
# return data_grouped_by_hour
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | for i in train_indexes: |
Continue the code snippet: <|code_start|>
def curve_per_subject(subject, data_path, test_labels):
d = load_train_data(data_path, subject)
x, y_10m = d['x'], d['y']
n_train_examples = x.shape[0]
n_timesteps = x.shape[-1]
print 'n_preictal', np.sum(y_10m)
print 'n_inetrictal', np.sum(y_10m - 1)
x, y = reshape_data(x, y_10m)
<|code_end|>
. Use current file imports:
import numpy as np
import json
import os
import matplotlib.pyplot as plt
import preprocessors.fft as fft
from sklearn.preprocessing import StandardScaler
from sklearn.lda import LDA
from sklearn.metrics import confusion_matrix
from utils.loader import load_test_data, load_train_data
from utils.config_name_creator import *
from commons import reshape_data
from commons import load_test_labels
from commons import print_cm
from sklearn.metrics import roc_curve
and context (classes, functions, or code) from other files:
# Path: utils/loader.py
# def load_test_data(data_path, subject):
# read_dir = data_path + '/' + subject
# data, id = [], []
# filenames = sorted(os.listdir(read_dir))
# for filename in sorted(filenames, key=lambda x: int(re.search(r'(\d+).mat', x).group(1))):
# if 'test' in filename or 'holdout' in filename:
# data.append(loadmat(read_dir + '/' + filename, squeeze_me=True))
# id.append(filename)
#
# n_test = len(data)
# x = np.zeros(((n_test,) + data[0]['data'].shape), dtype='float32')
# for i, datum in enumerate(data):
# x[i] = datum['data']
#
# return {'x': x, 'id': id}
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | data_scaler = StandardScaler() |
Predict the next line after this snippet: <|code_start|>
def curve_per_subject(subject, data_path, test_labels):
d = load_train_data(data_path, subject)
x, y_10m = d['x'], d['y']
<|code_end|>
using the current file's imports:
import numpy as np
import json
import os
import matplotlib.pyplot as plt
import preprocessors.fft as fft
from sklearn.preprocessing import StandardScaler
from sklearn.lda import LDA
from sklearn.metrics import confusion_matrix
from utils.loader import load_test_data, load_train_data
from utils.config_name_creator import *
from commons import reshape_data
from commons import load_test_labels
from commons import print_cm
from sklearn.metrics import roc_curve
and any relevant context from other files:
# Path: utils/loader.py
# def load_test_data(data_path, subject):
# read_dir = data_path + '/' + subject
# data, id = [], []
# filenames = sorted(os.listdir(read_dir))
# for filename in sorted(filenames, key=lambda x: int(re.search(r'(\d+).mat', x).group(1))):
# if 'test' in filename or 'holdout' in filename:
# data.append(loadmat(read_dir + '/' + filename, squeeze_me=True))
# id.append(filename)
#
# n_test = len(data)
# x = np.zeros(((n_test,) + data[0]['data'].shape), dtype='float32')
# for i, datum in enumerate(data):
# x[i] = datum['data']
#
# return {'x': x, 'id': id}
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | n_train_examples = x.shape[0] |
Next line prediction: <|code_start|> d = load_test_data(data_path, subject)
x_test, id = d['x'], d['id']
n_test_examples = x_test.shape[0]
n_timesteps = x_test.shape[3]
x_test = reshape_data(x_test)
x_test = data_scaler.transform(x_test)
pred_1m = model.predict_proba(x_test)[:, 1]
pred_10m = np.reshape(pred_1m, (n_test_examples, n_timesteps))
pred_10m = np.mean(pred_10m, axis=1)
ans = zip(id, pred_10m)
df = DataFrame(data=ans, columns=['clip', 'preictal'])
df.to_csv(submission_path + '/' + subject + '.csv', index=False, header=True)
return pred_10m
def run_trainer():
with open('SETTINGS.json') as f:
settings_dict = json.load(f)
reg_list = [10000000, 100, 10, 1.0, 0.1, 0.01]
for reg_C in reg_list:
print reg_C
data_path = settings_dict['path']['processed_data_path'] + '/' + create_fft_data_name(settings_dict)
submission_path = settings_dict['path']['submission_path'] + '/logreg_' + str(
reg_C) + '_' + create_fft_data_name(settings_dict)
<|code_end|>
. Use current file imports:
(import numpy as np
import json, os
import preprocessors.fft as fft
from pandas import DataFrame
from utils.loader import load_test_data, load_train_data
from utils.config_name_creator import *
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from merger import merge_csv_files
from commons import reshape_data)
and context including class names, function names, or small code snippets from other files:
# Path: utils/loader.py
# def load_test_data(data_path, subject):
# read_dir = data_path + '/' + subject
# data, id = [], []
# filenames = sorted(os.listdir(read_dir))
# for filename in sorted(filenames, key=lambda x: int(re.search(r'(\d+).mat', x).group(1))):
# if 'test' in filename or 'holdout' in filename:
# data.append(loadmat(read_dir + '/' + filename, squeeze_me=True))
# id.append(filename)
#
# n_test = len(data)
# x = np.zeros(((n_test,) + data[0]['data'].shape), dtype='float32')
# for i, datum in enumerate(data):
# x[i] = datum['data']
#
# return {'x': x, 'id': id}
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | if not os.path.exists(data_path): |
Given the code snippet: <|code_start|>
def train(subject, data_path, reg_C=None):
d = load_train_data(data_path, subject)
x, y = d['x'], d['y']
x, y = reshape_data(x, y)
data_scaler = StandardScaler()
x = data_scaler.fit_transform(x)
lda = LogisticRegression(C=reg_C)
lda.fit(x, y)
return lda, data_scaler
def predict(subject, model, data_scaler, data_path, submission_path):
d = load_test_data(data_path, subject)
x_test, id = d['x'], d['id']
n_test_examples = x_test.shape[0]
n_timesteps = x_test.shape[3]
x_test = reshape_data(x_test)
x_test = data_scaler.transform(x_test)
pred_1m = model.predict_proba(x_test)[:, 1]
pred_10m = np.reshape(pred_1m, (n_test_examples, n_timesteps))
pred_10m = np.mean(pred_10m, axis=1)
ans = zip(id, pred_10m)
df = DataFrame(data=ans, columns=['clip', 'preictal'])
df.to_csv(submission_path + '/' + subject + '.csv', index=False, header=True)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import json, os
import preprocessors.fft as fft
from pandas import DataFrame
from utils.loader import load_test_data, load_train_data
from utils.config_name_creator import *
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from merger import merge_csv_files
from commons import reshape_data
and context (functions, classes, or occasionally code) from other files:
# Path: utils/loader.py
# def load_test_data(data_path, subject):
# read_dir = data_path + '/' + subject
# data, id = [], []
# filenames = sorted(os.listdir(read_dir))
# for filename in sorted(filenames, key=lambda x: int(re.search(r'(\d+).mat', x).group(1))):
# if 'test' in filename or 'holdout' in filename:
# data.append(loadmat(read_dir + '/' + filename, squeeze_me=True))
# id.append(filename)
#
# n_test = len(data)
# x = np.zeros(((n_test,) + data[0]['data'].shape), dtype='float32')
# for i, datum in enumerate(data):
# x[i] = datum['data']
#
# return {'x': x, 'id': id}
#
# def load_train_data(data_path, subject):
# read_dir = data_path + '/' + subject
# filenames = sorted(os.listdir(read_dir))
# train_filenames = []
# for filename in filenames:
# if 'test' not in filename:
# train_filenames.append(filename)
#
# n = len(train_filenames)
# datum = loadmat(read_dir + '/' + train_filenames[0], squeeze_me=True)
# x = np.zeros(((n,) + datum['data'].shape), dtype='float32')
# y = np.zeros(n, dtype='int8')
#
# filename_to_idx = {}
# for i, filename in enumerate(train_filenames):
# datum = loadmat(read_dir + '/' + filename, squeeze_me=True)
# x[i] = datum['data']
# y[i] = 1 if 'preictal' in filename else 0
# filename_to_idx[subject + '/' + filename] = i
#
# return {'x': x, 'y': y, 'filename_to_idx': filename_to_idx}
. Output only the next line. | return pred_10m |
Continue the code snippet: <|code_start|>
def merge_csv_files(submission_path, subjects, submission_name):
print subjects
with open(submission_path + '/' + submission_name + '.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(['clip', 'preictal'])
<|code_end|>
. Use current file imports:
import csv
import json
from pandas import read_csv
from utils.config_name_creator import create_fft_data_name
from commons import softmax_scaler,minmax_scaler, median_scaler
and context (classes, functions, or code) from other files:
# Path: utils/config_name_creator.py
# def create_fft_data_name(settings_dict):
# return 'fft_' + settings_dict['preprocessor']['features'] + '_' + create_time_data_name(settings_dict) \
# + 'nfreq_bands' + str(settings_dict['preprocessor']['nfreq_bands']) \
# + 'win_length_sec' + str(settings_dict['preprocessor']['win_length_sec']) \
# + 'stride_sec' + str(settings_dict['preprocessor']['stride_sec'])
. Output only the next line. | for subject in subjects: |
Given snippet: <|code_start|> if 'test' in raw_file_path or 'holdout' in raw_file_path:
sequence = np.Inf
else:
sequence = d[sample][0][0][4][0][0]
new_sampling_frequency = 400
new_x = filter(x, new_sampling_frequency, data_length_sec, lowcut, highcut)
data_dict = {'data': new_x, 'data_length_sec': data_length_sec,
'sampling_frequency': new_sampling_frequency, 'sequence': sequence}
savemat(preprocessed_file_path, data_dict, do_compression=True)
def run_filter_preprocessor():
with open('SETTINGS.json') as f:
settings_dict = json.load(f)
raw_data_path = settings_dict['path']['raw_data_path']
processed_data_path = settings_dict['path']['processed_data_path'] + '/'+create_time_data_name(settings_dict)
if not os.path.exists(processed_data_path):
os.makedirs(processed_data_path)
shutil.copy2('SETTINGS.json', processed_data_path + '/SETTINGS.json')
highcut = settings_dict['preprocessor']['highcut']
lowcut = settings_dict['preprocessor']['lowcut']
#subjects = ['Dog_1', 'Dog_2', 'Dog_3', 'Dog_4', 'Dog_5', 'Patient_1', 'Patient_2']
# subjects = ['Dog_1', 'Dog_2', 'Dog_3', 'Dog_4']
subjects=['Dog_5']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import scipy as sc
import scipy.signal
import json
import os
import shutil
import numpy as np
from functools import partial
from multiprocessing import Pool
from scipy.io import loadmat, savemat
from utils.config_name_creator import create_time_data_name
and context:
# Path: utils/config_name_creator.py
# def create_time_data_name(settings_dict):
# highcut = settings_dict['preprocessor']['highcut']
# lowcut = settings_dict['preprocessor']['lowcut']
# config_name = 'lowcut' + str(lowcut) + 'highcut' + str(highcut)
# return config_name
which might include code, classes, or functions. Output only the next line. | for subject in subjects: |
Given snippet: <|code_start|>"""Abstract Handler with helper methods."""
log = logging.getLogger('handler')
class CursorKindException(TypeError):
"""When a child node of a VAR_DECL is parsed as an initialization value,
when its not actually part of that initiwlization value."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clang.cindex import CursorKind, TypeKind
from ctypeslib.codegen import typedesc
from ctypeslib.codegen.util import log_entity
import logging
and context:
# Path: ctypeslib/codegen/typedesc.py
# class T(object):
# class Argument(T):
# class _HasArgs(T):
# class Alias(T):
# class Macro(T):
# class File(T):
# class Function(_HasArgs):
# class Ignored(_HasArgs):
# class OperatorFunction(_HasArgs):
# class FunctionType(_HasArgs):
# class Method(_HasArgs):
# class FundamentalType(T):
# class PointerType(T):
# class Typedef(T):
# class ArrayType(T):
# class StructureHead(T):
# class StructureBody(T):
# class _Struct_Union_Base(T):
# class Structure(_Struct_Union_Base):
# class Union(_Struct_Union_Base):
# class Field(T):
# class CvQualifiedType(T):
# class Enumeration(T):
# class EnumValue(T):
# class Variable(T):
# class UndefinedIdentifier(T):
# def __repr__(self):
# def __init__(self, name, _type):
# def __init__(self):
# def add_argument(self, arg):
# def iterArgTypes(self):
# def iterArgNames(self):
# def fixup_argtypes(self, cb):
# def __init__(self, name, alias, typ=None):
# def __init__(self, name, args, body):
# def __init__(self, name):
# def __init__(self, name, returns, attributes, extern):
# def __init__(self, name):
# def __init__(self, name, returns):
# def __init__(self, returns, attributes, name=''):
# def __init__(self, name, returns):
# def __init__(self, name, size, align):
# def __init__(self, typ, size, align):
# def __init__(self, name, typ):
# def __init__(self, typ, size):
# def __init__(self, struct):
# def name(self):
# def __init__(self, struct):
# def name(self):
# def get_body(self):
# def get_head(self):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, typ, offset, bits, is_bitfield=False,
# is_anonymous=False, is_padding=False):
# def __init__(self, typ, const, volatile):
# def __init__(self, name, size, align):
# def add_value(self, v):
# def __init__(self, name, value, enumeration):
# def __init__(self, name, typ, init=None, extern=False):
# def __init__(self, name):
# def __str__(self):
# def is_record(t):
#
# Path: ctypeslib/codegen/util.py
# @decorator
# def log_entity(func):
# def fn(*args, **kwargs):
# name = args[0].get_unique_name(args[1])
# if name == '':
# parent = args[1].semantic_parent
# if parent:
# name = 'child of %s' % parent.displayname
# log.debug("%s: displayname:'%s'",func.__name__, name)
# # print 'calling {}'.format(func.__name__)
# return func(*args, **kwargs)
# return fn
which might include code, classes, or functions. Output only the next line. | pass |
Predict the next line after this snippet: <|code_start|> elif literal_kind == CursorKind.STRING_LITERAL:
return [TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.CHAR_S,
TypeKind.SCHAR, TypeKind.WCHAR] # DEBUG
elif literal_kind == CursorKind.CHARACTER_LITERAL:
return [TypeKind.CHAR_U, TypeKind.UCHAR]
elif literal_kind == CursorKind.FLOATING_LITERAL:
return [TypeKind.FLOAT, TypeKind.DOUBLE, TypeKind.LONGDOUBLE]
elif literal_kind == CursorKind.IMAGINARY_LITERAL:
return []
return []
def get_ctypes_name(self, typekind):
return self.parser.get_ctypes_name(typekind)
def get_ctypes_size(self, typekind):
return self.parser.get_ctypes_size(typekind)
def parse_cursor(self, cursor):
return self.parser.parse_cursor(cursor)
def parse_cursor_type(self, _cursor_type):
return self.parser.parse_cursor_type(_cursor_type)
################################
# do-nothing element handlers
@log_entity
def _pass_through_children(self, node, **args):
for child in node.get_children():
self.parser.startElement(child)
<|code_end|>
using the current file's imports:
from clang.cindex import CursorKind, TypeKind
from ctypeslib.codegen import typedesc
from ctypeslib.codegen.util import log_entity
import logging
and any relevant context from other files:
# Path: ctypeslib/codegen/typedesc.py
# class T(object):
# class Argument(T):
# class _HasArgs(T):
# class Alias(T):
# class Macro(T):
# class File(T):
# class Function(_HasArgs):
# class Ignored(_HasArgs):
# class OperatorFunction(_HasArgs):
# class FunctionType(_HasArgs):
# class Method(_HasArgs):
# class FundamentalType(T):
# class PointerType(T):
# class Typedef(T):
# class ArrayType(T):
# class StructureHead(T):
# class StructureBody(T):
# class _Struct_Union_Base(T):
# class Structure(_Struct_Union_Base):
# class Union(_Struct_Union_Base):
# class Field(T):
# class CvQualifiedType(T):
# class Enumeration(T):
# class EnumValue(T):
# class Variable(T):
# class UndefinedIdentifier(T):
# def __repr__(self):
# def __init__(self, name, _type):
# def __init__(self):
# def add_argument(self, arg):
# def iterArgTypes(self):
# def iterArgNames(self):
# def fixup_argtypes(self, cb):
# def __init__(self, name, alias, typ=None):
# def __init__(self, name, args, body):
# def __init__(self, name):
# def __init__(self, name, returns, attributes, extern):
# def __init__(self, name):
# def __init__(self, name, returns):
# def __init__(self, returns, attributes, name=''):
# def __init__(self, name, returns):
# def __init__(self, name, size, align):
# def __init__(self, typ, size, align):
# def __init__(self, name, typ):
# def __init__(self, typ, size):
# def __init__(self, struct):
# def name(self):
# def __init__(self, struct):
# def name(self):
# def get_body(self):
# def get_head(self):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, typ, offset, bits, is_bitfield=False,
# is_anonymous=False, is_padding=False):
# def __init__(self, typ, const, volatile):
# def __init__(self, name, size, align):
# def add_value(self, v):
# def __init__(self, name, value, enumeration):
# def __init__(self, name, typ, init=None, extern=False):
# def __init__(self, name):
# def __str__(self):
# def is_record(t):
#
# Path: ctypeslib/codegen/util.py
# @decorator
# def log_entity(func):
# def fn(*args, **kwargs):
# name = args[0].get_unique_name(args[1])
# if name == '':
# parent = args[1].semantic_parent
# if parent:
# name = 'child of %s' % parent.displayname
# log.debug("%s: displayname:'%s'",func.__name__, name)
# # print 'calling {}'.format(func.__name__)
# return func(*args, **kwargs)
# return fn
. Output only the next line. | return True |
Predict the next line after this snippet: <|code_start|>
# logging.basicConfig(level=logging.DEBUG)
class StringConstantsTest(ClangTest):
"""Tests some string variations.
"""
def test_char(self):
self.convert("""
char x = 'x';
<|code_end|>
using the current file's imports:
import logging
import unittest
from test.util import ClangTest
and any relevant context from other files:
# Path: test/util.py
# class ClangTest(unittest.TestCase):
# namespace = None
# text_output = None
# full_parsing_options = False
#
# def _gen(self, ofi, fname, flags=None, dlls=None):
# """Take a file input and generate the code.
# """
# cfg = config.CodegenConfig()
# flags = flags or []
# dlls = [Library(name, nm="nm") for name in dlls]
# # leave the new parser accessible for tests
# self.parser = clangparser.Clang_Parser(flags)
# if self.full_parsing_options:
# self.parser.activate_macros_parsing()
# self.parser.activate_comment_parsing()
# with open(fname):
# pass
# self.parser.parse(fname)
# items = self.parser.get_result()
# # gen code
# cfg.searched_dlls = dlls
# cfg.clang_opts = flags
# gen = codegenerator.Generator(ofi, cfg=cfg)
# gen.generate_headers(self.parser)
# gen.generate_code(items)
# return gen
#
# def gen(self, fname, flags=None, dlls=[], debug=False):
# """Take a file input and generate the code.
# """
# flags = flags or []
# dlls = dlls or []
# ofi = StringIO()
# gen = self._gen(ofi, fname, flags=flags, dlls=dlls)
# # load code
# namespace = {}
# # DEBUG
# # print ofi.getvalue()
# # DEBUG
# ofi.seek(0)
# ignore_coding = ofi.readline()
# # exec ofi.getvalue() in namespace
# output = ''.join(ofi.readlines())
# self.text_output = output
# try:
# # PY3 change
# exec(output, namespace)
# except Exception:
# print(output)
# raise
# # except NameError:
# # print(output)
# self.namespace = codegen_util.ADict(namespace)
# if debug:
# print(output)
# return
#
# def convert(self, src_code, flags=[], dlls=[], debug=False):
# """Take a string input, write it into a temp file and the code.
# """
# # This seems a bit redundant, when util.get_tu() exists.
# hfile = mktemp(".h")
# with open(hfile, "w") as f:
# f.write(src_code)
# try:
# self.gen(hfile, flags, dlls, debug)
# finally:
# os.unlink(hfile)
# return
#
# def _get_target_with_struct_hack(self, name):
# """ because we rename "struct x" to struct_x, we have to reverse that
# """
# target = codegen_util.get_cursor(self.parser.tu, name)
# if target is None:
# target = codegen_util.get_cursor(self.parser.tu, name.replace('struct_', ''))
# if target is None:
# target = codegen_util.get_cursor(self.parser.tu, name.replace('union_', ''))
# return target
#
# def assertSizes(self, name):
# """ Compare size of records using clang sizeof versus python sizeof."""
# target = self._get_target_with_struct_hack(name)
# self.assertTrue(
# target is not None,
# '%s was not found in source' %
# name)
# _clang = target.type.get_size()
# _python = ctypes.sizeof(getattr(self.namespace, name))
# self.assertEqual(_clang, _python,
# 'Sizes for target: %s Clang:%d Python:%d flags:%s' % (name, _clang,
# _python, self.parser.flags))
# return
#
# def assertOffsets(self, name):
# """ Compare offset of records' fields using clang offsets versus
# python offsets.
# name: the name of the structure.
# The findings and offset comparaison of members fields is automatic.
# """
# target = self._get_target_with_struct_hack(name)
# target = target.type.get_declaration()
# self.assertTrue(
# target is not None,
# '%s was not found in source' %
# name)
# members = [(c.displayname, c) for c in target.type.get_fields()]
# _clang_type = target.type
# _python_type = getattr(self.namespace, name)
# # let'shandle bitfield - precalculate offsets
# fields_offsets = dict()
# for field_desc in _python_type._fields_:
# _n = field_desc[0]
# _f = getattr(_python_type, _n)
# bfield_bits = _f.size >> 16
# if bfield_bits:
# ofs = 8 * _f.offset + _f.size & 0xFFFF
# else:
# ofs = 8 * _f.offset
# # base offset
# fields_offsets[_n] = ofs
# # now use that
# for i, (membername, field) in enumerate(members):
# # anonymous fields
# if membername == '':
# membername = '_%d' % i
# # _c_offset = _clang_type.get_offset(member)
# _c_offset = field.get_field_offsetof()
# # _p_offset = 8*getattr(_python_type, member).offset
# _p_offset = fields_offsets[membername]
# self.assertEqual(_c_offset, _p_offset,
# 'Offsets for target: %s.%s Clang:%d Python:%d flags:%s' % (
# name, membername, _c_offset, _p_offset, self.parser.flags))
# return
. Output only the next line. | char zero = 0; |
Next line prediction: <|code_start|> # include source file location in comments
generate_locations: bool = False
# do not include declaration defined outside of the source files
filter_location: bool = True
# dll to be loaded before all others (to resolve symbols)
preloaded_dlls: list = []
# kind of type descriptions to include
types: list = []
# the host's triplet
local_platform_triple: str = None
#
known_symbols: dict = {}
#
searched_dlls: list = []
# clang preprocessor options
clang_opts: list = []
def __init__(self):
self._init_types()
pass
def parse_options(self, options):
self.symbols = options.symbols
self.expressions = options.expressions
if options.expressions:
self.expressions = map(re.compile, options.expressions)
self.verbose = options.verbose
self.generate_comments = options.generate_comments
self.generate_docstrings = options.generate_docstrings
self.generate_locations = options.generate_locations
<|code_end|>
. Use current file imports:
(import re
from ctypeslib.library import Library
from ctypeslib.codegen import typedesc)
and context including class names, function names, or small code snippets from other files:
# Path: ctypeslib/library.py
# class Library(metaclass=LibraryMeta):
#
# def __init__(self, filepath, nm):
# self._filepath = filepath
# self._name = os.path.basename(self._filepath)
# self.__symbols = {}
# self._get_symbols(nm)
#
# # nm will print lines like this:
# # <addr> <kind> <name>
# def _get_symbols(self, nm):
# cmd = [nm, "--dynamic", "--defined-only", self._filepath]
# output = subprocess.check_output(cmd, universal_newlines=True)
# for line in output.split('\n'):
# fields = line.split(' ', 2)
# if len(fields) >= 3 and fields[1] in ("T", "D", "G", "R", "S"):
# self.__symbols[fields[2]] = fields[0]
#
# def __getattr__(self, name):
# try:
# return self.__symbols[name]
# except KeyError:
# pass
# raise AttributeError(name)
#
# Path: ctypeslib/codegen/typedesc.py
# class T(object):
# class Argument(T):
# class _HasArgs(T):
# class Alias(T):
# class Macro(T):
# class File(T):
# class Function(_HasArgs):
# class Ignored(_HasArgs):
# class OperatorFunction(_HasArgs):
# class FunctionType(_HasArgs):
# class Method(_HasArgs):
# class FundamentalType(T):
# class PointerType(T):
# class Typedef(T):
# class ArrayType(T):
# class StructureHead(T):
# class StructureBody(T):
# class _Struct_Union_Base(T):
# class Structure(_Struct_Union_Base):
# class Union(_Struct_Union_Base):
# class Field(T):
# class CvQualifiedType(T):
# class Enumeration(T):
# class EnumValue(T):
# class Variable(T):
# class UndefinedIdentifier(T):
# def __repr__(self):
# def __init__(self, name, _type):
# def __init__(self):
# def add_argument(self, arg):
# def iterArgTypes(self):
# def iterArgNames(self):
# def fixup_argtypes(self, cb):
# def __init__(self, name, alias, typ=None):
# def __init__(self, name, args, body):
# def __init__(self, name):
# def __init__(self, name, returns, attributes, extern):
# def __init__(self, name):
# def __init__(self, name, returns):
# def __init__(self, returns, attributes, name=''):
# def __init__(self, name, returns):
# def __init__(self, name, size, align):
# def __init__(self, typ, size, align):
# def __init__(self, name, typ):
# def __init__(self, typ, size):
# def __init__(self, struct):
# def name(self):
# def __init__(self, struct):
# def name(self):
# def get_body(self):
# def get_head(self):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, typ, offset, bits, is_bitfield=False,
# is_anonymous=False, is_padding=False):
# def __init__(self, typ, const, volatile):
# def __init__(self, name, size, align):
# def add_value(self, v):
# def __init__(self, name, value, enumeration):
# def __init__(self, name, typ, init=None, extern=False):
# def __init__(self, name):
# def __str__(self):
# def is_record(t):
. Output only the next line. | self.filter_location = not options.generate_includes |
Here is a snippet: <|code_start|>
class CodegenConfig:
# symbol to include, if empty, everything will be included
symbols: list = []
# regular expression for symbols to include
expressions: list = []
# verbose output
verbose: bool = False
# include source doxygen-style comments
generate_comments: bool = False
# include docstrings containing C prototype and source file location
generate_docstrings: bool = False
# include source file location in comments
generate_locations: bool = False
# do not include declaration defined outside of the source files
filter_location: bool = True
# dll to be loaded before all others (to resolve symbols)
preloaded_dlls: list = []
# kind of type descriptions to include
<|code_end|>
. Write the next line using the current file imports:
import re
from ctypeslib.library import Library
from ctypeslib.codegen import typedesc
and context from other files:
# Path: ctypeslib/library.py
# class Library(metaclass=LibraryMeta):
#
# def __init__(self, filepath, nm):
# self._filepath = filepath
# self._name = os.path.basename(self._filepath)
# self.__symbols = {}
# self._get_symbols(nm)
#
# # nm will print lines like this:
# # <addr> <kind> <name>
# def _get_symbols(self, nm):
# cmd = [nm, "--dynamic", "--defined-only", self._filepath]
# output = subprocess.check_output(cmd, universal_newlines=True)
# for line in output.split('\n'):
# fields = line.split(' ', 2)
# if len(fields) >= 3 and fields[1] in ("T", "D", "G", "R", "S"):
# self.__symbols[fields[2]] = fields[0]
#
# def __getattr__(self, name):
# try:
# return self.__symbols[name]
# except KeyError:
# pass
# raise AttributeError(name)
#
# Path: ctypeslib/codegen/typedesc.py
# class T(object):
# class Argument(T):
# class _HasArgs(T):
# class Alias(T):
# class Macro(T):
# class File(T):
# class Function(_HasArgs):
# class Ignored(_HasArgs):
# class OperatorFunction(_HasArgs):
# class FunctionType(_HasArgs):
# class Method(_HasArgs):
# class FundamentalType(T):
# class PointerType(T):
# class Typedef(T):
# class ArrayType(T):
# class StructureHead(T):
# class StructureBody(T):
# class _Struct_Union_Base(T):
# class Structure(_Struct_Union_Base):
# class Union(_Struct_Union_Base):
# class Field(T):
# class CvQualifiedType(T):
# class Enumeration(T):
# class EnumValue(T):
# class Variable(T):
# class UndefinedIdentifier(T):
# def __repr__(self):
# def __init__(self, name, _type):
# def __init__(self):
# def add_argument(self, arg):
# def iterArgTypes(self):
# def iterArgNames(self):
# def fixup_argtypes(self, cb):
# def __init__(self, name, alias, typ=None):
# def __init__(self, name, args, body):
# def __init__(self, name):
# def __init__(self, name, returns, attributes, extern):
# def __init__(self, name):
# def __init__(self, name, returns):
# def __init__(self, returns, attributes, name=''):
# def __init__(self, name, returns):
# def __init__(self, name, size, align):
# def __init__(self, typ, size, align):
# def __init__(self, name, typ):
# def __init__(self, typ, size):
# def __init__(self, struct):
# def name(self):
# def __init__(self, struct):
# def name(self):
# def get_body(self):
# def get_head(self):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, typ, offset, bits, is_bitfield=False,
# is_anonymous=False, is_padding=False):
# def __init__(self, typ, const, volatile):
# def __init__(self, name, size, align):
# def add_value(self, v):
# def __init__(self, name, value, enumeration):
# def __init__(self, name, typ, init=None, extern=False):
# def __init__(self, name):
# def __str__(self):
# def is_record(t):
, which may include functions, classes, or code. Output only the next line. | types: list = [] |
Predict the next line after this snippet: <|code_start|> int first;
int last;
};
struct example {
int argsz;
int flags;
int count;
struct example_detail details[2];
};
''')
self.assertIn("i", py_namespace)
self.assertIn("c2", py_namespace)
self.assertIn("struct_example_detail", py_namespace)
self.assertIn("struct_example", py_namespace)
self.assertEqual(py_namespace.i, 12)
self.assertEqual(py_namespace.c2, ['a', 'b', 'c'])
# import pprint
# pprint.pprint(py_namespace)
def test_basic_use_io(self):
input_io = io.StringIO('''
int i = 12;
char c2[3] = {'a','b','c'};
struct example_detail {
int first;
int last;
};
struct example {
<|code_end|>
using the current file's imports:
import unittest
import io
import ctypeslib
from ctypeslib.codegen import config
from ctypeslib.codegen import typedesc
and any relevant context from other files:
# Path: ctypeslib/codegen/config.py
# class CodegenConfig:
# def __init__(self):
# def parse_options(self, options):
# def _init_types(self, _default="cdefstu"):
# def _parse_options_types(self, options):
# def _parse_options_modules(self, options):
# def _parse_options_clang_opts(self, options):
# def cross_arch(self):
#
# Path: ctypeslib/codegen/typedesc.py
# class T(object):
# class Argument(T):
# class _HasArgs(T):
# class Alias(T):
# class Macro(T):
# class File(T):
# class Function(_HasArgs):
# class Ignored(_HasArgs):
# class OperatorFunction(_HasArgs):
# class FunctionType(_HasArgs):
# class Method(_HasArgs):
# class FundamentalType(T):
# class PointerType(T):
# class Typedef(T):
# class ArrayType(T):
# class StructureHead(T):
# class StructureBody(T):
# class _Struct_Union_Base(T):
# class Structure(_Struct_Union_Base):
# class Union(_Struct_Union_Base):
# class Field(T):
# class CvQualifiedType(T):
# class Enumeration(T):
# class EnumValue(T):
# class Variable(T):
# class UndefinedIdentifier(T):
# def __repr__(self):
# def __init__(self, name, _type):
# def __init__(self):
# def add_argument(self, arg):
# def iterArgTypes(self):
# def iterArgNames(self):
# def fixup_argtypes(self, cb):
# def __init__(self, name, alias, typ=None):
# def __init__(self, name, args, body):
# def __init__(self, name):
# def __init__(self, name, returns, attributes, extern):
# def __init__(self, name):
# def __init__(self, name, returns):
# def __init__(self, returns, attributes, name=''):
# def __init__(self, name, returns):
# def __init__(self, name, size, align):
# def __init__(self, typ, size, align):
# def __init__(self, name, typ):
# def __init__(self, typ, size):
# def __init__(self, struct):
# def name(self):
# def __init__(self, struct):
# def name(self):
# def get_body(self):
# def get_head(self):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, align, members, bases, size, artificial=None,
# packed=False):
# def __init__(self, name, typ, offset, bits, is_bitfield=False,
# is_anonymous=False, is_padding=False):
# def __init__(self, typ, const, volatile):
# def __init__(self, name, size, align):
# def add_value(self, v):
# def __init__(self, name, value, enumeration):
# def __init__(self, name, typ, init=None, extern=False):
# def __init__(self, name):
# def __str__(self):
# def is_record(t):
. Output only the next line. | int argsz; |
Based on the snippet: <|code_start|>
def run(args):
if hasattr(subprocess, 'run'):
p = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, stderr = p.stdout.decode(), p.stderr.decode()
return p, output, stderr
else:
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)
<|code_end|>
, predict the immediate next line with the help of imports:
import subprocess
import sys
import unittest
import ctypeslib
from test.util import ClangTest
from io import StringIO
from unittest.mock import patch
from ctypeslib import clang2py
from ctypeslib import clang2py
from ctypeslib import clang2py
from ctypeslib import clang2py
from ctypeslib import clang2py
from ctypeslib import clang2py
and context (classes, functions, sometimes code) from other files:
# Path: test/util.py
# class ClangTest(unittest.TestCase):
# namespace = None
# text_output = None
# full_parsing_options = False
#
# def _gen(self, ofi, fname, flags=None, dlls=None):
# """Take a file input and generate the code.
# """
# cfg = config.CodegenConfig()
# flags = flags or []
# dlls = [Library(name, nm="nm") for name in dlls]
# # leave the new parser accessible for tests
# self.parser = clangparser.Clang_Parser(flags)
# if self.full_parsing_options:
# self.parser.activate_macros_parsing()
# self.parser.activate_comment_parsing()
# with open(fname):
# pass
# self.parser.parse(fname)
# items = self.parser.get_result()
# # gen code
# cfg.searched_dlls = dlls
# cfg.clang_opts = flags
# gen = codegenerator.Generator(ofi, cfg=cfg)
# gen.generate_headers(self.parser)
# gen.generate_code(items)
# return gen
#
# def gen(self, fname, flags=None, dlls=[], debug=False):
# """Take a file input and generate the code.
# """
# flags = flags or []
# dlls = dlls or []
# ofi = StringIO()
# gen = self._gen(ofi, fname, flags=flags, dlls=dlls)
# # load code
# namespace = {}
# # DEBUG
# # print ofi.getvalue()
# # DEBUG
# ofi.seek(0)
# ignore_coding = ofi.readline()
# # exec ofi.getvalue() in namespace
# output = ''.join(ofi.readlines())
# self.text_output = output
# try:
# # PY3 change
# exec(output, namespace)
# except Exception:
# print(output)
# raise
# # except NameError:
# # print(output)
# self.namespace = codegen_util.ADict(namespace)
# if debug:
# print(output)
# return
#
# def convert(self, src_code, flags=[], dlls=[], debug=False):
# """Take a string input, write it into a temp file and the code.
# """
# # This seems a bit redundant, when util.get_tu() exists.
# hfile = mktemp(".h")
# with open(hfile, "w") as f:
# f.write(src_code)
# try:
# self.gen(hfile, flags, dlls, debug)
# finally:
# os.unlink(hfile)
# return
#
# def _get_target_with_struct_hack(self, name):
# """ because we rename "struct x" to struct_x, we have to reverse that
# """
# target = codegen_util.get_cursor(self.parser.tu, name)
# if target is None:
# target = codegen_util.get_cursor(self.parser.tu, name.replace('struct_', ''))
# if target is None:
# target = codegen_util.get_cursor(self.parser.tu, name.replace('union_', ''))
# return target
#
# def assertSizes(self, name):
# """ Compare size of records using clang sizeof versus python sizeof."""
# target = self._get_target_with_struct_hack(name)
# self.assertTrue(
# target is not None,
# '%s was not found in source' %
# name)
# _clang = target.type.get_size()
# _python = ctypes.sizeof(getattr(self.namespace, name))
# self.assertEqual(_clang, _python,
# 'Sizes for target: %s Clang:%d Python:%d flags:%s' % (name, _clang,
# _python, self.parser.flags))
# return
#
# def assertOffsets(self, name):
# """ Compare offset of records' fields using clang offsets versus
# python offsets.
# name: the name of the structure.
# The findings and offset comparaison of members fields is automatic.
# """
# target = self._get_target_with_struct_hack(name)
# target = target.type.get_declaration()
# self.assertTrue(
# target is not None,
# '%s was not found in source' %
# name)
# members = [(c.displayname, c) for c in target.type.get_fields()]
# _clang_type = target.type
# _python_type = getattr(self.namespace, name)
# # let'shandle bitfield - precalculate offsets
# fields_offsets = dict()
# for field_desc in _python_type._fields_:
# _n = field_desc[0]
# _f = getattr(_python_type, _n)
# bfield_bits = _f.size >> 16
# if bfield_bits:
# ofs = 8 * _f.offset + _f.size & 0xFFFF
# else:
# ofs = 8 * _f.offset
# # base offset
# fields_offsets[_n] = ofs
# # now use that
# for i, (membername, field) in enumerate(members):
# # anonymous fields
# if membername == '':
# membername = '_%d' % i
# # _c_offset = _clang_type.get_offset(member)
# _c_offset = field.get_field_offsetof()
# # _p_offset = 8*getattr(_python_type, member).offset
# _p_offset = fields_offsets[membername]
# self.assertEqual(_c_offset, _p_offset,
# 'Offsets for target: %s.%s Clang:%d Python:%d flags:%s' % (
# name, membername, _c_offset, _p_offset, self.parser.flags))
# return
. Output only the next line. | output, stderr = p.communicate() |
Using the snippet: <|code_start|> for _ in range(3):
for i in range(size*multiplier, size*(multiplier+1)):
self.assertEqual(time, func(i))
def test_on_purge(self):
test_index = 1
purges = []
@lru_cache(on_purge=lambda index: purges.append(index), maxsize=1)
def func(index):
return index
for _ in range(2):
func(test_index)
self.assertEqual(0, len(purges))
func(test_index + 1)
self.assertEqual(1, len(purges))
self.assertEqual(test_index, purges[0])
def test_clear(self):
size = 3
purges = []
@lru_cache(maxsize=size, on_purge=lambda index: purges.append(index))
def func(index):
return index
for i in range(size):
func(i)
self.assertEqual(0, len(purges))
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import collections
from cloudify.lru_cache import lru_cache
and context (class names, function names, or code) available:
# Path: cloudify/lru_cache.py
# def lru_cache(maxsize=100, on_purge=None):
# """Least-recently-used cache decorator.
#
# Arguments to the cached function must be hashable.
# Clear the cache with f.clear().
# """
# maxqueue = maxsize * 10
#
# def decorating_function(user_function):
# cache = {}
# queue = collections.deque()
# refcount = collections.defaultdict(int)
# sentinel = object()
# kwd_mark = object()
#
# # lookup optimizations (ugly but fast)
# queue_append, queue_popleft = queue.append, queue.popleft
# queue_appendleft, queue_pop = queue.appendleft, queue.pop
#
# @functools.wraps(user_function)
# def wrapper(*args, **kwargs):
# # cache key records both positional and keyword args
# key = args
# if kwargs:
# key += (kwd_mark,) + tuple(sorted(kwargs.items()))
#
# # record recent use of this key
# queue_append(key)
# refcount[key] += 1
#
# # get cache entry or compute if not found
# try:
# result = cache[key]
# except KeyError:
# result = user_function(*args, **kwargs)
# cache[key] = result
#
# # purge least recently used cache entry
# if len(cache) > maxsize:
# key = queue_popleft()
# refcount[key] -= 1
# while refcount[key]:
# key = queue_popleft()
# refcount[key] -= 1
# if on_purge:
# on_purge(cache[key])
# del cache[key], refcount[key]
#
# # periodically compact the queue by eliminating duplicate keys
# # while preserving order of most recent access
# if len(queue) > maxqueue:
# refcount.clear()
# queue_appendleft(sentinel)
# for key in ifilterfalse(refcount.__contains__,
# iter(queue_pop, sentinel)):
# queue_appendleft(key)
# refcount[key] = 1
# return result
#
# def clear():
# if on_purge:
# for value in cache.itervalues():
# on_purge(value)
# cache.clear()
# queue.clear()
# refcount.clear()
#
# wrapper._cache = cache
# wrapper.clear = clear
# return wrapper
# return decorating_function
. Output only the next line. | self.assertEqual(size, len(func._cache)) |
Predict the next line for this snippet: <|code_start|>########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
class TestLogs(testtools.TestCase):
def test_create_event_message_prefix(self):
test_event = {'type': 'cloudify_log',
<|code_end|>
with the help of current file imports:
import testtools
from cloudify import logs
and context from other files:
# Path: cloudify/logs.py
# EVENT_CLASS = _event.Event
# EVENT_VERBOSITY_LEVEL = _event.NO_VERBOSE
# def message_context_from_cloudify_context(ctx):
# def message_context_from_workflow_context(ctx):
# def message_context_from_sys_wide_wf_context(ctx):
# def message_context_from_workflow_node_instance_context(ctx):
# def __init__(self, ctx, out_func, message_context_builder):
# def flush(self):
# def emit(self, record):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def init_cloudify_logger(handler, logger_name,
# logging_level=logging.DEBUG):
# def send_workflow_event(ctx, event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_sys_wide_wf_event(ctx, event_type, message=None, args=None,
# additional_context=None, out_func=None):
# def send_workflow_node_event(ctx, event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_plugin_event(ctx,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_task_event(cloudify_context,
# event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def _send_event(ctx, context_type, event_type,
# message, args, additional_context,
# out_func):
# def populate_base_item(item, message_type):
# def amqp_event_out(event):
# def amqp_log_out(log):
# def stdout_event_out(event):
# def stdout_log_out(log):
# def create_event_message_prefix(event):
# def with_amqp_client(func):
# def wrapper(*args, **kwargs):
# def _publish_message(client, message, message_type, logger):
# def __init__(self, context, socket, fallback_logger):
# def emit(self, record):
# class CloudifyBaseLoggingHandler(logging.Handler):
# class CloudifyPluginLoggingHandler(CloudifyBaseLoggingHandler):
# class CloudifyWorkflowLoggingHandler(CloudifyBaseLoggingHandler):
# class SystemWideWorkflowLoggingHandler(CloudifyBaseLoggingHandler):
# class CloudifyWorkflowNodeLoggingHandler(CloudifyBaseLoggingHandler):
# class ZMQLoggingHandler(logging.Handler):
, which may contain function names, class names, or code. Output only the next line. | 'level': 'INFO', |
Given the following code snippet before the placeholder: <|code_start|>########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
class LocalCommandRunnerTest(unittest.TestCase):
runner = None
@classmethod
<|code_end|>
, predict the next line using imports from the current file:
import os
import mock
import logging
import tempfile
import unittest
from cloudify.exceptions import CommandExecutionException
from cloudify.utils import setup_logger, get_exec_tempdir, LocalCommandRunner
and context including class names, function names, and sometimes code from other files:
# Path: cloudify/exceptions.py
# class CommandExecutionException(Exception):
#
# """
# Indicates a command was executed, however some sort of error happened,
# resulting in a non-zero return value of the process.
#
# :param command: The command executed
# :param code: process exit code
# :param error: process stderr output
# :param output: process stdout output
# """
#
# def __init__(self, command, error, output, code):
# self.command = command
# self.error = error
# self.code = code
# self.output = output
# Exception.__init__(self, self.__str__())
#
# def __str__(self):
# return "Command '{0}' executed with an error." \
# "\ncode: {1}" \
# "\nerror: {2}" \
# "\noutput: {3}" \
# .format(self.command, self.code,
# self.error or None,
# self.output or None)
#
# Path: cloudify/utils.py
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# """
# :param logger_name: Name of the logger.
# :param logger_level: Level for the logger (not for specific handler).
# :param handlers: An optional list of handlers (formatter will be
# overridden); If None, only a StreamHandler for
# sys.stdout will be used.
# :param remove_existing_handlers: Determines whether to remove existing
# handlers before adding new ones
# :param logger_format: the format this logger will have.
# :param propagate: propagate the message the parent logger.
#
# :return: A logger instance.
# :rtype: logging.Logger
# """
# if logger_format is None:
# logger_format = '%(asctime)s [%(levelname)s] [%(name)s] %(message)s'
# logger = logging.getLogger(logger_name)
#
# if remove_existing_handlers:
# for handler in logger.handlers:
# logger.removeHandler(handler)
#
# if not handlers:
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# handlers = [handler]
#
# formatter = logging.Formatter(fmt=logger_format,
# datefmt='%H:%M:%S')
# for handler in handlers:
# handler.setFormatter(formatter)
# logger.addHandler(handler)
#
# logger.setLevel(logger_level)
# if not propagate:
# logger.propagate = False
# return logger
#
# def get_exec_tempdir():
# """
# Returns the directory to use for temporary files, when the intention
# is to place an executable file there.
# This is needed because some production systems disallow executions from
# the default temporary directory.
# """
# return os.environ.get(CFY_EXEC_TEMPDIR_ENVVAR) or tempfile.gettempdir()
#
# class LocalCommandRunner(object):
#
# def __init__(self, logger=None, host='localhost'):
#
# """
# :param logger: This logger will be used for
# printing the output and the command.
# """
#
# logger = logger or setup_logger('LocalCommandRunner')
# self.logger = logger
# self.host = host
#
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
#
# """
# Runs local commands.
#
# :param command: The command to execute.
# :param exit_on_failure: False to ignore failures.
# :param stdout_pipe: False to not pipe the standard output.
# :param stderr_pipe: False to not pipe the standard error.
# :param cwd: the working directory the command will run from.
# :param execution_env: dictionary of environment variables that will
# be present in the command scope.
#
# :return: A wrapper object for all valuable info from the execution.
# :rtype: cloudify.utils.CommandExecutionResponse
# """
#
# if isinstance(command, list):
# popen_args = command
# else:
# popen_args = _shlex_split(command)
# self.logger.debug('[{0}] run: {1}'.format(self.host, popen_args))
# stdout = subprocess.PIPE if stdout_pipe else None
# stderr = subprocess.PIPE if stderr_pipe else None
# command_env = os.environ.copy()
# command_env.update(execution_env or {})
# p = subprocess.Popen(args=popen_args, stdout=stdout,
# stderr=stderr, cwd=cwd, env=command_env)
# out, err = p.communicate()
# if out:
# out = out.rstrip()
# if err:
# err = err.rstrip()
#
# if p.returncode != 0:
# error = CommandExecutionException(
# command=command,
# error=err,
# output=out,
# code=p.returncode)
# if exit_on_failure:
# raise error
# else:
# self.logger.error(error)
#
# return CommandExecutionResponse(
# command=command,
# std_out=out,
# std_err=err,
# return_code=p.returncode)
. Output only the next line. | def setUpClass(cls): |
Next line prediction: <|code_start|> self.keeper = gate_keeper.GateKeeper(
with_gate_keeper=True,
gate_keeper_bucket_size=self.bucket_size,
worker=mock.Mock())
def tearDown(self):
for q in self.keeper._current.values():
self.assertTrue(q.empty())
for q in self.keeper._on_hold.values():
self.assertTrue(q.empty())
super(GateKeeperTest, self).tearDown()
def begin(self, task):
request = RequestMock(task, self)
self.keeper.task_received(request, request.handler)
return request
class Requests(object):
def __init__(self, test, deployment_id, task_func):
self.deployment_id = str(deployment_id)
self.task_func = task_func
self.test = test
self.requests = []
self.running_requests = []
self.next_index = 0
def begin_new_request(self):
request = self.test.begin(self.task_func(self.deployment_id))
<|code_end|>
. Use current file imports:
(import random
import mock
import testtools
from cloudify.celery import gate_keeper)
and context including class names, function names, or small code snippets from other files:
# Path: cloudify/celery/gate_keeper.py
# def configure_app(app):
# def _handle(self, request, callbacks):
# def handler():
# def __init__(self, task, app, consumer,
# info=logger.info,
# task_reserved=task_reserved,
# **kwargs):
# def __call__(self, message, body, ack, reject, callbacks, **kwargs):
# def _build_request(self, message, body, ack, reject):
# def _send_event(self, request):
# def __init__(self, worker,
# with_gate_keeper=False,
# gate_keeper_bucket_size=5, **kwargs):
# def _noop(self, worker):
# def info(self, worker):
# def start(self, worker):
# def task_received(self, request, handler, socket_url=None):
# def task_ended(self, bucket_key):
# def _clear_first_current_task(self, bucket_key):
# def _try_get_on_hold_task(self, bucket_key):
# def _hold_task(self, bucket_key, handler):
# def _add_task(self, bucket_key):
# def _patch_request(self, bucket_key, request):
# def on_success(*args, **kwargs):
# def _extract_bucket_key_and_augment_request(request, socket_url):
# class GateKeeperStrategy(object):
# class GateKeeper(bootsteps.StartStopStep):
. Output only the next line. | self.requests.append(request) |
Based on the snippet: <|code_start|>
def test_put_new_property_twice(self):
node = NodeInstance('instance_id', 'node_id')
node.put('key', 'value')
node.put('key', 'v')
self.assertEqual('v', node.get('key'))
props = node.runtime_properties
self.assertEqual(1, len(props))
self.assertEqual('v', props['key'])
def test_delete_property(self):
node = NodeInstance('instance_id', 'node_id')
node.put('key', 'value')
self.assertEquals('value', node.get('key'))
node.delete('key')
self.assertNotIn('key', node)
def test_delete_property_sugared_syntax(self):
node = NodeInstance('instance_id', 'node_id')
node.put('key', 'value')
self.assertEquals('value', node.get('key'))
del(node['key'])
self.assertNotIn('key', node)
def test_delete_nonexistent_property(self):
node = NodeInstance('instance_id', 'node_id')
self.assertRaises(KeyError, node.delete, 'key')
def test_delete_makes_properties_dirty(self):
node = NodeInstance('instance_id', 'node_id',
<|code_end|>
, predict the immediate next line with the help of imports:
import testtools
from cloudify import exceptions
from cloudify.manager import NodeInstance
and context (classes, functions, sometimes code) from other files:
# Path: cloudify/exceptions.py
# class NonRecoverableError(Exception):
# class RecoverableError(Exception):
# class OperationRetry(RecoverableError):
# class HttpException(NonRecoverableError):
# class CommandExecutionError(RuntimeError):
# class CommandExecutionException(Exception):
# class TimeoutException(Exception):
# class ProcessExecutionError(RuntimeError):
# class ClosedAMQPClientException(Exception):
# def __init__(self, *args, **kwargs):
# def __init__(self, message='', retry_after=None, causes=None, **kwargs):
# def __init__(self, url, code, message, causes=None, **kwargs):
# def __str__(self):
# def __init__(self, command, error=None):
# def __str__(self):
# def __init__(self, command, error, output, code):
# def __str__(self):
# def __init__(self, message, error_type=None, traceback=None, causes=None,
# **kwargs):
# def __str__(self):
#
# Path: cloudify/manager.py
# class NodeInstance(object):
# """
# Represents a deployment node instance.
# An instance of this class contains runtime information retrieved
# from Cloudify's runtime storage as well as the node's state.
# """
# def __init__(self,
# node_instance_id,
# node_id,
# runtime_properties=None,
# state=None,
# version=None,
# host_id=None,
# relationships=None):
# self.id = node_instance_id
# self._node_id = node_id
# self._runtime_properties = \
# DirtyTrackingDict((runtime_properties or {}).copy())
# self._state = state
# self._version = version
# self._host_id = host_id
# self._relationships = relationships
#
# def get(self, key):
# return self._runtime_properties.get(key)
#
# def put(self, key, value):
# self._runtime_properties[key] = value
#
# def delete(self, key):
# del(self._runtime_properties[key])
#
# __setitem__ = put
#
# __getitem__ = get
#
# __delitem__ = delete
#
# def __contains__(self, key):
# return key in self._runtime_properties
#
# @property
# def runtime_properties(self):
# """
# The node instance runtime properties.
#
# To update the properties, make changes on the returned dict and call
# ``update_node_instance`` with the modified instance.
# """
# return self._runtime_properties
#
# @runtime_properties.setter
# def runtime_properties(self, new_properties):
# # notify the old object of the changes - trigger a .modifiable check
# self._runtime_properties._set_changed()
#
# self._runtime_properties = DirtyTrackingDict(new_properties)
# self._runtime_properties._set_changed()
#
# @property
# def version(self):
# return self._version
#
# @property
# def state(self):
# """
# The node instance state.
#
# To update the node instance state, change this property value and
# call ``update_node_instance`` with the modified instance.
# """
# return self._state
#
# @state.setter
# def state(self, value):
# self._state = value
#
# @property
# def dirty(self):
# return self._runtime_properties.dirty
#
# @property
# def host_id(self):
# return self._host_id
#
# @property
# def node_id(self):
# return self._node_id
#
# @property
# def relationships(self):
# return self._relationships
. Output only the next line. | runtime_properties={'preexisting-key': 'val'}) |
Given the code snippet: <|code_start|> node = NodeInstance('instance_id', 'node_id')
node.put('key', 'value')
node.put('key', 'v')
self.assertEqual('v', node.get('key'))
props = node.runtime_properties
self.assertEqual(1, len(props))
self.assertEqual('v', props['key'])
def test_delete_property(self):
node = NodeInstance('instance_id', 'node_id')
node.put('key', 'value')
self.assertEquals('value', node.get('key'))
node.delete('key')
self.assertNotIn('key', node)
def test_delete_property_sugared_syntax(self):
node = NodeInstance('instance_id', 'node_id')
node.put('key', 'value')
self.assertEquals('value', node.get('key'))
del(node['key'])
self.assertNotIn('key', node)
def test_delete_nonexistent_property(self):
node = NodeInstance('instance_id', 'node_id')
self.assertRaises(KeyError, node.delete, 'key')
def test_delete_makes_properties_dirty(self):
node = NodeInstance('instance_id', 'node_id',
runtime_properties={'preexisting-key': 'val'})
self.assertFalse(node.dirty)
<|code_end|>
, generate the next line using the imports in this file:
import testtools
from cloudify import exceptions
from cloudify.manager import NodeInstance
and context (functions, classes, or occasionally code) from other files:
# Path: cloudify/exceptions.py
# class NonRecoverableError(Exception):
# class RecoverableError(Exception):
# class OperationRetry(RecoverableError):
# class HttpException(NonRecoverableError):
# class CommandExecutionError(RuntimeError):
# class CommandExecutionException(Exception):
# class TimeoutException(Exception):
# class ProcessExecutionError(RuntimeError):
# class ClosedAMQPClientException(Exception):
# def __init__(self, *args, **kwargs):
# def __init__(self, message='', retry_after=None, causes=None, **kwargs):
# def __init__(self, url, code, message, causes=None, **kwargs):
# def __str__(self):
# def __init__(self, command, error=None):
# def __str__(self):
# def __init__(self, command, error, output, code):
# def __str__(self):
# def __init__(self, message, error_type=None, traceback=None, causes=None,
# **kwargs):
# def __str__(self):
#
# Path: cloudify/manager.py
# class NodeInstance(object):
# """
# Represents a deployment node instance.
# An instance of this class contains runtime information retrieved
# from Cloudify's runtime storage as well as the node's state.
# """
# def __init__(self,
# node_instance_id,
# node_id,
# runtime_properties=None,
# state=None,
# version=None,
# host_id=None,
# relationships=None):
# self.id = node_instance_id
# self._node_id = node_id
# self._runtime_properties = \
# DirtyTrackingDict((runtime_properties or {}).copy())
# self._state = state
# self._version = version
# self._host_id = host_id
# self._relationships = relationships
#
# def get(self, key):
# return self._runtime_properties.get(key)
#
# def put(self, key, value):
# self._runtime_properties[key] = value
#
# def delete(self, key):
# del(self._runtime_properties[key])
#
# __setitem__ = put
#
# __getitem__ = get
#
# __delitem__ = delete
#
# def __contains__(self, key):
# return key in self._runtime_properties
#
# @property
# def runtime_properties(self):
# """
# The node instance runtime properties.
#
# To update the properties, make changes on the returned dict and call
# ``update_node_instance`` with the modified instance.
# """
# return self._runtime_properties
#
# @runtime_properties.setter
# def runtime_properties(self, new_properties):
# # notify the old object of the changes - trigger a .modifiable check
# self._runtime_properties._set_changed()
#
# self._runtime_properties = DirtyTrackingDict(new_properties)
# self._runtime_properties._set_changed()
#
# @property
# def version(self):
# return self._version
#
# @property
# def state(self):
# """
# The node instance state.
#
# To update the node instance state, change this property value and
# call ``update_node_instance`` with the modified instance.
# """
# return self._state
#
# @state.setter
# def state(self, value):
# self._state = value
#
# @property
# def dirty(self):
# return self._runtime_properties.dirty
#
# @property
# def host_id(self):
# return self._host_id
#
# @property
# def node_id(self):
# return self._node_id
#
# @property
# def relationships(self):
# return self._relationships
. Output only the next line. | del(node['preexisting-key']) |
Based on the snippet: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
class TestLoggingServer(testtools.TestCase):
HANDLER_CONTEXT = 'logger'
def setUp(self):
self.worker = mock.Mock()
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import logging.handlers
import os
import shutil
import tempfile
import time
import mock
import testtools
import zmq
from mock import patch
from cloudify import logs
from cloudify.celery import logging_server
and context (classes, functions, sometimes code) from other files:
# Path: cloudify/logs.py
# EVENT_CLASS = _event.Event
# EVENT_VERBOSITY_LEVEL = _event.NO_VERBOSE
# def message_context_from_cloudify_context(ctx):
# def message_context_from_workflow_context(ctx):
# def message_context_from_sys_wide_wf_context(ctx):
# def message_context_from_workflow_node_instance_context(ctx):
# def __init__(self, ctx, out_func, message_context_builder):
# def flush(self):
# def emit(self, record):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def init_cloudify_logger(handler, logger_name,
# logging_level=logging.DEBUG):
# def send_workflow_event(ctx, event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_sys_wide_wf_event(ctx, event_type, message=None, args=None,
# additional_context=None, out_func=None):
# def send_workflow_node_event(ctx, event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_plugin_event(ctx,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_task_event(cloudify_context,
# event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def _send_event(ctx, context_type, event_type,
# message, args, additional_context,
# out_func):
# def populate_base_item(item, message_type):
# def amqp_event_out(event):
# def amqp_log_out(log):
# def stdout_event_out(event):
# def stdout_log_out(log):
# def create_event_message_prefix(event):
# def with_amqp_client(func):
# def wrapper(*args, **kwargs):
# def _publish_message(client, message, message_type, logger):
# def __init__(self, context, socket, fallback_logger):
# def emit(self, record):
# class CloudifyBaseLoggingHandler(logging.Handler):
# class CloudifyPluginLoggingHandler(CloudifyBaseLoggingHandler):
# class CloudifyWorkflowLoggingHandler(CloudifyBaseLoggingHandler):
# class SystemWideWorkflowLoggingHandler(CloudifyBaseLoggingHandler):
# class CloudifyWorkflowNodeLoggingHandler(CloudifyBaseLoggingHandler):
# class ZMQLoggingHandler(logging.Handler):
#
# Path: cloudify/celery/logging_server.py
# LOGFILE_SIZE_BYTES = 5 * 1024 * 1024
# LOGFILE_BACKUP_COUNT = 5
# def configure_app(app):
# def __init__(self, worker,
# with_logging_server=False,
# logging_server_logdir=None,
# logging_server_handler_cache_size=100,
# **kwargs):
# def info(self, worker):
# def start(self, worker):
# def _stop_logging_server(self, worker):
# def __init__(self, logdir, socket_url, cache_size):
# def start(self):
# def close(self):
# def _process(self, entry):
# def _get_handler(self, handler_context):
# def __init__(self, message):
# def format(record):
# class ZMQLoggingServerBootstep(bootsteps.StartStopStep):
# class ZMQLoggingServer(object):
# class Record(object):
# class Formatter(object):
. Output only the next line. | super(TestLoggingServer, self).setUp() |
Using the snippet: <|code_start|> def test_disabled(self):
server = self._start_server(enable=False)
self.assertIsNone(server.logging_server)
self.assertIsNone(server.socket_url)
def test_handler_cache_size(self):
num_loggers = 7
cache_size = 3
server = self._start_server(cache_size=cache_size)
get_handler = server.logging_server._get_handler
get_handler_cache = get_handler._cache
logger_names = ['logger{0}'.format(i) for i in range(num_loggers)]
for i in range(num_loggers):
logger_name = logger_names[i]
logger = self._logger(server, logger_name)
logger.info(logger_name)
self._assert_in_log(logger_name, logger_name)
self.assertEqual(min(i+1, cache_size), len(get_handler_cache))
actual_handler = get_handler_cache[(logger_name,)]
expected_handler = get_handler(logger_name)
self.assertEqual(expected_handler, actual_handler)
for j in range(max(0, i-2), i+1):
self.assertIn((logger_names[j],), get_handler_cache)
def test_stop(self):
server, logger = self.test_basic()
logger.handlers[0]._socket.close()
handler_cache = server.logging_server._get_handler._cache
self.assertEqual(1, len(handler_cache))
server_handler = next(handler_cache.itervalues())
<|code_end|>
, determine the next line of code. You have imports:
import logging
import logging.handlers
import os
import shutil
import tempfile
import time
import mock
import testtools
import zmq
from mock import patch
from cloudify import logs
from cloudify.celery import logging_server
and context (class names, function names, or code) available:
# Path: cloudify/logs.py
# EVENT_CLASS = _event.Event
# EVENT_VERBOSITY_LEVEL = _event.NO_VERBOSE
# def message_context_from_cloudify_context(ctx):
# def message_context_from_workflow_context(ctx):
# def message_context_from_sys_wide_wf_context(ctx):
# def message_context_from_workflow_node_instance_context(ctx):
# def __init__(self, ctx, out_func, message_context_builder):
# def flush(self):
# def emit(self, record):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def __init__(self, ctx, out_func=None):
# def init_cloudify_logger(handler, logger_name,
# logging_level=logging.DEBUG):
# def send_workflow_event(ctx, event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_sys_wide_wf_event(ctx, event_type, message=None, args=None,
# additional_context=None, out_func=None):
# def send_workflow_node_event(ctx, event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_plugin_event(ctx,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def send_task_event(cloudify_context,
# event_type,
# message=None,
# args=None,
# additional_context=None,
# out_func=None):
# def _send_event(ctx, context_type, event_type,
# message, args, additional_context,
# out_func):
# def populate_base_item(item, message_type):
# def amqp_event_out(event):
# def amqp_log_out(log):
# def stdout_event_out(event):
# def stdout_log_out(log):
# def create_event_message_prefix(event):
# def with_amqp_client(func):
# def wrapper(*args, **kwargs):
# def _publish_message(client, message, message_type, logger):
# def __init__(self, context, socket, fallback_logger):
# def emit(self, record):
# class CloudifyBaseLoggingHandler(logging.Handler):
# class CloudifyPluginLoggingHandler(CloudifyBaseLoggingHandler):
# class CloudifyWorkflowLoggingHandler(CloudifyBaseLoggingHandler):
# class SystemWideWorkflowLoggingHandler(CloudifyBaseLoggingHandler):
# class CloudifyWorkflowNodeLoggingHandler(CloudifyBaseLoggingHandler):
# class ZMQLoggingHandler(logging.Handler):
#
# Path: cloudify/celery/logging_server.py
# LOGFILE_SIZE_BYTES = 5 * 1024 * 1024
# LOGFILE_BACKUP_COUNT = 5
# def configure_app(app):
# def __init__(self, worker,
# with_logging_server=False,
# logging_server_logdir=None,
# logging_server_handler_cache_size=100,
# **kwargs):
# def info(self, worker):
# def start(self, worker):
# def _stop_logging_server(self, worker):
# def __init__(self, logdir, socket_url, cache_size):
# def start(self):
# def close(self):
# def _process(self, entry):
# def _get_handler(self, handler_context):
# def __init__(self, message):
# def format(record):
# class ZMQLoggingServerBootstep(bootsteps.StartStopStep):
# class ZMQLoggingServer(object):
# class Record(object):
# class Formatter(object):
. Output only the next line. | self.assertIsNotNone(server_handler.stream) |
Predict the next line after this snippet: <|code_start|> raise NotImplementedError()
def get_resource(self, resource_path):
with open(os.path.join(self.resources_root, resource_path)) as f:
return f.read()
def download_resource(self, resource_path, target_path=None):
if not target_path:
suffix = '-{0}'.format(os.path.basename(resource_path))
target_path = tempfile.mktemp(suffix=suffix)
resource = self.get_resource(resource_path)
with open(target_path, 'wb') as f:
f.write(resource)
return target_path
def update_node_instance(self,
node_instance_id,
version,
runtime_properties=None,
state=None):
with self._lock(node_instance_id):
instance = self._get_node_instance(node_instance_id)
if state is None and version != instance['version']:
raise StorageConflictError('version {0} does not match '
'current version of '
'node instance {1} which is {2}'
.format(version,
node_instance_id,
instance['version']))
else:
<|code_end|>
using the current file's imports:
import os
import tempfile
import copy
import importlib
import shutil
import uuid
import json
import threading
from StringIO import StringIO
from contextlib import contextmanager
from cloudify_rest_client.nodes import Node
from cloudify_rest_client.node_instances import NodeInstance
from cloudify import dispatch
from cloudify.workflows.workflow_context import (
DEFAULT_LOCAL_TASK_THREAD_POOL_SIZE)
from dsl_parser.constants import HOST_TYPE
from dsl_parser import parser as dsl_parser, tasks as dsl_tasks
from dsl_parser import functions as dsl_functions
and any relevant context from other files:
# Path: cloudify/dispatch.py
# @task
# def dispatch(__cloudify_context, *args, **kwargs):
# dispatch_type = __cloudify_context['type']
# dispatch_handler_cls = TASK_HANDLERS.get(dispatch_type)
# if not dispatch_handler_cls:
# raise exceptions.NonRecoverableError('No handler for task type: {0}'
# .format(dispatch_type))
# handler = dispatch_handler_cls(cloudify_context=__cloudify_context,
# args=args,
# kwargs=kwargs)
# return handler.handle_or_dispatch_to_subprocess_if_remote()
#
# Path: cloudify/workflows/workflow_context.py
# DEFAULT_LOCAL_TASK_THREAD_POOL_SIZE = 1
. Output only the next line. | instance['version'] += 1 |
Next line prediction: <|code_start|> workflow, workflow_name, parameters, allow_custom_parameters)
return dispatch.dispatch(__cloudify_context=ctx, **merged_parameters)
def init_env(blueprint_path,
name='local',
inputs=None,
storage=None,
ignored_modules=None,
provider_context=None,
resolver=None,
validate_version=True):
if storage is None:
storage = InMemoryStorage()
return _Environment(storage=storage,
blueprint_path=blueprint_path,
name=name,
inputs=inputs,
load_existing=False,
ignored_modules=ignored_modules,
provider_context=provider_context,
resolver=resolver,
validate_version=validate_version)
def load_env(name, storage, resolver=None):
return _Environment(storage=storage,
name=name,
load_existing=True,
<|code_end|>
. Use current file imports:
(import os
import tempfile
import copy
import importlib
import shutil
import uuid
import json
import threading
from StringIO import StringIO
from contextlib import contextmanager
from cloudify_rest_client.nodes import Node
from cloudify_rest_client.node_instances import NodeInstance
from cloudify import dispatch
from cloudify.workflows.workflow_context import (
DEFAULT_LOCAL_TASK_THREAD_POOL_SIZE)
from dsl_parser.constants import HOST_TYPE
from dsl_parser import parser as dsl_parser, tasks as dsl_tasks
from dsl_parser import functions as dsl_functions)
and context including class names, function names, or small code snippets from other files:
# Path: cloudify/dispatch.py
# @task
# def dispatch(__cloudify_context, *args, **kwargs):
# dispatch_type = __cloudify_context['type']
# dispatch_handler_cls = TASK_HANDLERS.get(dispatch_type)
# if not dispatch_handler_cls:
# raise exceptions.NonRecoverableError('No handler for task type: {0}'
# .format(dispatch_type))
# handler = dispatch_handler_cls(cloudify_context=__cloudify_context,
# args=args,
# kwargs=kwargs)
# return handler.handle_or_dispatch_to_subprocess_if_remote()
#
# Path: cloudify/workflows/workflow_context.py
# DEFAULT_LOCAL_TASK_THREAD_POOL_SIZE = 1
. Output only the next line. | resolver=resolver) |
Predict the next line after this snippet: <|code_start|> if not self.closed:
logger.warning('Error raised during record processing',
exc_info=True)
def close(self):
if not self.closed:
self.closed = True
self.socket.close()
self.zmq_context.term()
self._get_handler.clear()
def _process(self, entry):
handler = self._get_handler(entry['context'])
handler.emit(Record(entry['message']))
def _get_handler(self, handler_context):
logfile = os.path.join(self.logdir, '{0}.log'.format(handler_context))
handler = self.handler_func(logfile)
handler.setFormatter(Formatter)
return handler
class Record(object):
def __init__(self, message):
self.message = message
filename = None
lineno = None
class Formatter(object):
<|code_end|>
using the current file's imports:
import functools
import json
import logging
import logging.handlers
import os
import random
import threading
import tempfile
import zmq
from celery import bootsteps
from celery.bin import Option
from celery.utils.log import get_logger
from cloudify.proxy import server
from cloudify.lru_cache import lru_cache
and any relevant context from other files:
# Path: cloudify/proxy/server.py
# class CtxProxy(object):
# class HTTPCtxProxy(CtxProxy):
# class BottleServerAdapter(bottle.ServerAdapter):
# class Server(WSGIServer):
# class Handler(WSGIRequestHandler):
# class ZMQCtxProxy(CtxProxy):
# class UnixCtxProxy(ZMQCtxProxy):
# class TCPCtxProxy(ZMQCtxProxy):
# class StubCtxProxy(object):
# class PathDictAccess(object):
# def __init__(self, ctx, socket_url):
# def process(self, request):
# def close(self):
# def __init__(self, ctx, port=None):
# def _start_server(self):
# def run(self, app):
# def handle_error(self, request, client_address):
# def address_string(self):
# def log_request(*args, **kwargs):
# def serve():
# def close(self):
# def _request_handler(self):
# def __init__(self, ctx, socket_url):
# def poll_and_process(self, timeout=1):
# def close(self):
# def __init__(self, ctx, socket_path=None):
# def __init__(self, ctx, ip='127.0.0.1', port=None):
# def close(self):
# def process_ctx_request(ctx, args):
# def _desugar_attr(obj, attr):
# def __init__(self, obj):
# def set(self, prop_path, value):
# def get(self, prop_path):
# def _get_object_by_path(self, prop_path, fail_on_missing=True):
# def _get_parent_obj_prop_name_by_path(self, prop_path):
# def _raise_illegal(prop_path):
# def get_unused_port():
#
# Path: cloudify/lru_cache.py
# def lru_cache(maxsize=100, on_purge=None):
# """Least-recently-used cache decorator.
#
# Arguments to the cached function must be hashable.
# Clear the cache with f.clear().
# """
# maxqueue = maxsize * 10
#
# def decorating_function(user_function):
# cache = {}
# queue = collections.deque()
# refcount = collections.defaultdict(int)
# sentinel = object()
# kwd_mark = object()
#
# # lookup optimizations (ugly but fast)
# queue_append, queue_popleft = queue.append, queue.popleft
# queue_appendleft, queue_pop = queue.appendleft, queue.pop
#
# @functools.wraps(user_function)
# def wrapper(*args, **kwargs):
# # cache key records both positional and keyword args
# key = args
# if kwargs:
# key += (kwd_mark,) + tuple(sorted(kwargs.items()))
#
# # record recent use of this key
# queue_append(key)
# refcount[key] += 1
#
# # get cache entry or compute if not found
# try:
# result = cache[key]
# except KeyError:
# result = user_function(*args, **kwargs)
# cache[key] = result
#
# # purge least recently used cache entry
# if len(cache) > maxsize:
# key = queue_popleft()
# refcount[key] -= 1
# while refcount[key]:
# key = queue_popleft()
# refcount[key] -= 1
# if on_purge:
# on_purge(cache[key])
# del cache[key], refcount[key]
#
# # periodically compact the queue by eliminating duplicate keys
# # while preserving order of most recent access
# if len(queue) > maxqueue:
# refcount.clear()
# queue_appendleft(sentinel)
# for key in ifilterfalse(refcount.__contains__,
# iter(queue_pop, sentinel)):
# queue_appendleft(key)
# refcount[key] = 1
# return result
#
# def clear():
# if on_purge:
# for value in cache.itervalues():
# on_purge(value)
# cache.clear()
# queue.clear()
# refcount.clear()
#
# wrapper._cache = cache
# wrapper.clear = clear
# return wrapper
# return decorating_function
. Output only the next line. | @staticmethod |
Continue the code snippet: <|code_start|> if not self.closed:
logger.warning('Error raised during record processing',
exc_info=True)
def close(self):
if not self.closed:
self.closed = True
self.socket.close()
self.zmq_context.term()
self._get_handler.clear()
def _process(self, entry):
handler = self._get_handler(entry['context'])
handler.emit(Record(entry['message']))
def _get_handler(self, handler_context):
logfile = os.path.join(self.logdir, '{0}.log'.format(handler_context))
handler = self.handler_func(logfile)
handler.setFormatter(Formatter)
return handler
class Record(object):
def __init__(self, message):
self.message = message
filename = None
lineno = None
class Formatter(object):
<|code_end|>
. Use current file imports:
import functools
import json
import logging
import logging.handlers
import os
import random
import threading
import tempfile
import zmq
from celery import bootsteps
from celery.bin import Option
from celery.utils.log import get_logger
from cloudify.proxy import server
from cloudify.lru_cache import lru_cache
and context (classes, functions, or code) from other files:
# Path: cloudify/proxy/server.py
# class CtxProxy(object):
# class HTTPCtxProxy(CtxProxy):
# class BottleServerAdapter(bottle.ServerAdapter):
# class Server(WSGIServer):
# class Handler(WSGIRequestHandler):
# class ZMQCtxProxy(CtxProxy):
# class UnixCtxProxy(ZMQCtxProxy):
# class TCPCtxProxy(ZMQCtxProxy):
# class StubCtxProxy(object):
# class PathDictAccess(object):
# def __init__(self, ctx, socket_url):
# def process(self, request):
# def close(self):
# def __init__(self, ctx, port=None):
# def _start_server(self):
# def run(self, app):
# def handle_error(self, request, client_address):
# def address_string(self):
# def log_request(*args, **kwargs):
# def serve():
# def close(self):
# def _request_handler(self):
# def __init__(self, ctx, socket_url):
# def poll_and_process(self, timeout=1):
# def close(self):
# def __init__(self, ctx, socket_path=None):
# def __init__(self, ctx, ip='127.0.0.1', port=None):
# def close(self):
# def process_ctx_request(ctx, args):
# def _desugar_attr(obj, attr):
# def __init__(self, obj):
# def set(self, prop_path, value):
# def get(self, prop_path):
# def _get_object_by_path(self, prop_path, fail_on_missing=True):
# def _get_parent_obj_prop_name_by_path(self, prop_path):
# def _raise_illegal(prop_path):
# def get_unused_port():
#
# Path: cloudify/lru_cache.py
# def lru_cache(maxsize=100, on_purge=None):
# """Least-recently-used cache decorator.
#
# Arguments to the cached function must be hashable.
# Clear the cache with f.clear().
# """
# maxqueue = maxsize * 10
#
# def decorating_function(user_function):
# cache = {}
# queue = collections.deque()
# refcount = collections.defaultdict(int)
# sentinel = object()
# kwd_mark = object()
#
# # lookup optimizations (ugly but fast)
# queue_append, queue_popleft = queue.append, queue.popleft
# queue_appendleft, queue_pop = queue.appendleft, queue.pop
#
# @functools.wraps(user_function)
# def wrapper(*args, **kwargs):
# # cache key records both positional and keyword args
# key = args
# if kwargs:
# key += (kwd_mark,) + tuple(sorted(kwargs.items()))
#
# # record recent use of this key
# queue_append(key)
# refcount[key] += 1
#
# # get cache entry or compute if not found
# try:
# result = cache[key]
# except KeyError:
# result = user_function(*args, **kwargs)
# cache[key] = result
#
# # purge least recently used cache entry
# if len(cache) > maxsize:
# key = queue_popleft()
# refcount[key] -= 1
# while refcount[key]:
# key = queue_popleft()
# refcount[key] -= 1
# if on_purge:
# on_purge(cache[key])
# del cache[key], refcount[key]
#
# # periodically compact the queue by eliminating duplicate keys
# # while preserving order of most recent access
# if len(queue) > maxqueue:
# refcount.clear()
# queue_appendleft(sentinel)
# for key in ifilterfalse(refcount.__contains__,
# iter(queue_pop, sentinel)):
# queue_appendleft(key)
# refcount[key] = 1
# return result
#
# def clear():
# if on_purge:
# for value in cache.itervalues():
# on_purge(value)
# cache.clear()
# queue.clear()
# refcount.clear()
#
# wrapper._cache = cache
# wrapper.clear = clear
# return wrapper
# return decorating_function
. Output only the next line. | @staticmethod |
Predict the next line for this snippet: <|code_start|># 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.
def _get_cluster_settings_file(filename=None):
if filename is None \
and constants.CLUSTER_SETTINGS_PATH_KEY not in os.environ:
return None
return filename or os.environ[constants.CLUSTER_SETTINGS_PATH_KEY]
def get_cluster_settings(filename=None):
filename = _get_cluster_settings_file(filename=filename)
if not filename:
return None
try:
with open(filename) as f:
return json.load(f)
except (IOError, ValueError):
<|code_end|>
with the help of current file imports:
import os
import json
import pika
import types
import requests
import itertools
from cloudify import constants
from cloudify_rest_client import CloudifyClient
from cloudify_rest_client.client import HTTPClient
from cloudify_rest_client.exceptions import (CloudifyClientError,
NotClusterMaster)
and context from other files:
# Path: cloudify/constants.py
# REST_HOST_KEY = 'REST_HOST'
# REST_PORT_KEY = 'REST_PORT'
# CELERY_WORK_DIR_KEY = 'CELERY_WORK_DIR'
# MANAGER_FILE_SERVER_URL_KEY = 'MANAGER_FILE_SERVER_URL'
# MANAGER_FILE_SERVER_ROOT_KEY = 'MANAGER_FILE_SERVER_ROOT'
# FILE_SERVER_RESOURCES_FOLDER = 'resources'
# FILE_SERVER_BLUEPRINTS_FOLDER = 'blueprints'
# FILE_SERVER_DEPLOYMENTS_FOLDER = 'deployments'
# FILE_SERVER_UPLOADED_BLUEPRINTS_FOLDER = 'uploaded-blueprints'
# FILE_SERVER_SNAPSHOTS_FOLDER = 'snapshots'
# FILE_SERVER_PLUGINS_FOLDER = 'plugins'
# FILE_SERVER_GLOBAL_RESOURCES_FOLDER = 'global-resources'
# FILE_SERVER_TENANT_RESOURCES_FOLDER = 'tenant-resources'
# FILE_SERVER_AUTHENTICATORS_FOLDER = 'authenticators'
# AGENT_INSTALL_METHOD_NONE = 'none'
# AGENT_INSTALL_METHOD_REMOTE = 'remote'
# AGENT_INSTALL_METHOD_INIT_SCRIPT = 'init_script'
# AGENT_INSTALL_METHOD_PROVIDED = 'provided'
# AGENT_INSTALL_METHOD_PLUGIN = 'plugin'
# AGENT_INSTALL_METHODS = [
# AGENT_INSTALL_METHOD_NONE,
# AGENT_INSTALL_METHOD_REMOTE,
# AGENT_INSTALL_METHOD_INIT_SCRIPT,
# AGENT_INSTALL_METHOD_PROVIDED,
# AGENT_INSTALL_METHOD_PLUGIN
# ]
# AGENT_INSTALL_METHODS_SCRIPTS = [
# AGENT_INSTALL_METHOD_INIT_SCRIPT,
# AGENT_INSTALL_METHOD_PROVIDED,
# AGENT_INSTALL_METHOD_PLUGIN
# ]
# COMPUTE_NODE_TYPE = 'cloudify.nodes.Compute'
# BROKER_PORT_NO_SSL = 5672
# BROKER_PORT_SSL = 5671
# CELERY_TASK_RESULT_EXPIRES = 600
# CLOUDIFY_TOKEN_AUTHENTICATION_HEADER = 'Authentication-Token'
# LOCAL_REST_CERT_FILE_KEY = 'LOCAL_REST_CERT_FILE'
# SECURED_PROTOCOL = 'https'
# BROKER_SSL_CERT_PATH = 'BROKER_SSL_CERT_PATH'
# BYPASS_MAINTENANCE = 'BYPASS_MAINTENANCE'
# LOGGING_CONFIG_FILE = '/etc/cloudify/logging.conf'
# CLUSTER_SETTINGS_PATH_KEY = 'CLOUDIFY_CLUSTER_SETTINGS_PATH'
# MGMTWORKER_QUEUE = 'cloudify.management'
# DEPLOYMENT = 'deployment'
# NODE_INSTANCE = 'node-instance'
# RELATIONSHIP_INSTANCE = 'relationship-instance'
# DEFAULT_NETWORK_NAME = 'default'
, which may contain function names, class names, or code. Output only the next line. | return None |
Given snippet: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
# AMQP broker configuration for agents and manager
# Primarily used by celery, so provided with variables it understands
from __future__ import absolute_import
workdir_path = os.getenv('CELERY_WORK_DIR')
if workdir_path is None:
# We are not in an appropriately configured celery environment
config = {}
else:
conf_file_path = os.path.join(workdir_path, 'broker_config.json')
if os.path.isfile(conf_file_path):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os
import ssl
from cloudify.constants import BROKER_PORT_SSL, BROKER_PORT_NO_SSL
and context:
# Path: cloudify/constants.py
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
which might include code, classes, or functions. Output only the next line. | with open(conf_file_path) as conf_handle: |
Using the snippet: <|code_start|> options = ''
# BROKER_URL is held in the config to avoid the password appearing
# in ps listings
URL_TEMPLATE = \
'amqp://{username}:{password}@{hostname}:{port}/{vhost}{options}'
if config.get('cluster'):
BROKER_URL = ';'.join(URL_TEMPLATE.format(username=broker_username,
password=broker_password,
hostname=node_ip,
port=broker_port,
vhost=broker_vhost,
options=options)
for node_ip in config['cluster'])
else:
BROKER_URL = URL_TEMPLATE.format(
username=broker_username,
password=broker_password,
hostname=broker_hostname,
port=broker_port,
vhost=broker_vhost,
options=options
)
# celery will not use the failover strategy if there is only one broker url;
# we need it to try and failover even with one initial manager, because
# another node might've been added dynamically, while the worker was already
# running; we add an empty broker url so that celery always sees at least two -
# the failover strategy we're using (defined in cloudify_agent.app) filters out
# the empty one
<|code_end|>
, determine the next line of code. You have imports:
import json
import os
import ssl
from cloudify.constants import BROKER_PORT_SSL, BROKER_PORT_NO_SSL
and context (class names, function names, or code) available:
# Path: cloudify/constants.py
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
. Output only the next line. | BROKER_URL += ';' |
Predict the next line after this snippet: <|code_start|> self.sock.bind(self.socket_url)
self.poller = zmq.Poller()
self.poller.register(self.sock, zmq.POLLIN)
def poll_and_process(self, timeout=1):
state = dict(self.poller.poll(1000 * timeout)).get(self.sock)
if not state == zmq.POLLIN:
return False
request = self.sock.recv()
response = self.process(request)
self.sock.send(response)
return True
def close(self):
self.sock.close()
self.z_context.term()
class UnixCtxProxy(ZMQCtxProxy):
def __init__(self, ctx, socket_path=None):
if not socket_path:
socket_path = tempfile.mktemp(prefix='ctx-', suffix='.socket')
socket_url = 'ipc://{0}'.format(socket_path)
super(UnixCtxProxy, self).__init__(ctx, socket_url)
class TCPCtxProxy(ZMQCtxProxy):
def __init__(self, ctx, ip='127.0.0.1', port=None):
<|code_end|>
using the current file's imports:
import traceback
import tempfile
import re
import collections
import json
import threading
import socket
import bottle
import zmq
import zmq
from Queue import Queue
from StringIO import StringIO
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
from wsgiref.simple_server import make_server as make_wsgi_server
from cloudify.proxy.client import ScriptException
from cloudify.state import current_ctx
and any relevant context from other files:
# Path: cloudify/proxy/client.py
# class ScriptException(Exception):
# def __init__(self, message=None, retry=False):
# super(Exception, self).__init__(message)
# self.retry = retry
#
# Path: cloudify/state.py
# class NotInContext(RuntimeError):
# class CtxParameters(dict):
# class CurrentContext(threading.local):
# def __init__(self, parameters):
# def __getattr__(self, attr):
# def set(self, ctx, parameters=None):
# def get_ctx(self):
# def get_parameters(self):
# def _get(self, attribute):
# def clear(self):
# def push(self, ctx, parameters=None):
# def ctx():
# def ctx_parameters():
# def workflow_ctx():
# def workflow_parameters():
. Output only the next line. | port = port or get_unused_port() |
Given the following code snippet before the placeholder: <|code_start|>
class PathDictAccess(object):
pattern = re.compile("(.+)\[(\d+)\]")
def __init__(self, obj):
self.obj = obj
def set(self, prop_path, value):
obj, prop_name = self._get_parent_obj_prop_name_by_path(prop_path)
obj[prop_name] = value
def get(self, prop_path):
value = self._get_object_by_path(prop_path)
return value
def _get_object_by_path(self, prop_path, fail_on_missing=True):
# when setting a nested object, make sure to also set all the
# intermediate path objects
current = self.obj
for prop_segment in prop_path.split('.'):
match = self.pattern.match(prop_segment)
if match:
index = int(match.group(2))
property_name = match.group(1)
if property_name not in current:
self._raise_illegal(prop_path)
if type(current[property_name]) != list:
self._raise_illegal(prop_path)
<|code_end|>
, predict the next line using imports from the current file:
import traceback
import tempfile
import re
import collections
import json
import threading
import socket
import bottle
import zmq
import zmq
from Queue import Queue
from StringIO import StringIO
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
from wsgiref.simple_server import make_server as make_wsgi_server
from cloudify.proxy.client import ScriptException
from cloudify.state import current_ctx
and context including class names, function names, and sometimes code from other files:
# Path: cloudify/proxy/client.py
# class ScriptException(Exception):
# def __init__(self, message=None, retry=False):
# super(Exception, self).__init__(message)
# self.retry = retry
#
# Path: cloudify/state.py
# class NotInContext(RuntimeError):
# class CtxParameters(dict):
# class CurrentContext(threading.local):
# def __init__(self, parameters):
# def __getattr__(self, attr):
# def set(self, ctx, parameters=None):
# def get_ctx(self):
# def get_parameters(self):
# def _get(self, attribute):
# def clear(self):
# def push(self, ctx, parameters=None):
# def ctx():
# def ctx_parameters():
# def workflow_ctx():
# def workflow_parameters():
. Output only the next line. | current = current[property_name][index] |
Continue the code snippet: <|code_start|> test_event = _event('cloudify_log', level='DEBUG')
self.assertFalse(test_event.has_output)
test_event = _event('cloudify_log', level='DEBUG',
verbosity_level=event.MEDIUM_VERBOSE)
self.assertTrue(test_event.has_output)
def test_task_failure_causes(self):
message = 'test_message'
test_event = _event('cloudify_event',
event_type='task_failed',
message=message)
self.assertEqual(test_event.text, message)
causes = []
test_event = _event('cloudify_event',
event_type='task_failed',
message=message,
causes=causes)
self.assertEqual(test_event.text, message)
try:
raise RuntimeError()
except RuntimeError:
_, ex, tb = sys.exc_info()
causes = [utils.exception_to_error_cause(ex, tb)]
test_event = _event('cloudify_event',
event_type='task_failed',
message=message,
causes=causes)
self.assertEqual(test_event.text, message)
test_event = _event('cloudify_event',
event_type='task_failed',
<|code_end|>
. Use current file imports:
import sys
import testtools
from cloudify import utils
from cloudify import event
and context (classes, functions, or code) from other files:
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/event.py
# HIGH_VERBOSE = 3
# MEDIUM_VERBOSE = 2
# LOW_VERBOSE = 1
# NO_VERBOSE = 0
# class Event(object):
# def __init__(self, event, verbosity_level=None):
# def __str__(self):
# def has_output(self):
# def operation_info(self):
# def text(self):
# def log_level(self):
# def timestamp(self):
# def printable_timestamp(self):
# def event_type_indicator(self):
# def operation(self):
# def node_id(self):
# def source_id(self):
# def target_id(self):
# def deployment_id(self):
# def event_type(self):
# def is_log_message(self):
. Output only the next line. | message=message, |
Given the code snippet: <|code_start|> self.assertEqual(test_event.text, message)
causes = []
test_event = _event('cloudify_event',
event_type='task_failed',
message=message,
causes=causes)
self.assertEqual(test_event.text, message)
try:
raise RuntimeError()
except RuntimeError:
_, ex, tb = sys.exc_info()
causes = [utils.exception_to_error_cause(ex, tb)]
test_event = _event('cloudify_event',
event_type='task_failed',
message=message,
causes=causes)
self.assertEqual(test_event.text, message)
test_event = _event('cloudify_event',
event_type='task_failed',
message=message,
causes=causes,
verbosity_level=event.LOW_VERBOSE)
text = test_event.text
self.assertIn(message, text)
self.assertNotIn('Causes (most recent cause last):', text)
self.assertEqual(1, text.count(causes[0]['traceback']))
causes = causes + causes
test_event = _event('cloudify_event',
event_type='task_failed',
message=message,
<|code_end|>
, generate the next line using the imports in this file:
import sys
import testtools
from cloudify import utils
from cloudify import event
and context (functions, classes, or occasionally code) from other files:
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/event.py
# HIGH_VERBOSE = 3
# MEDIUM_VERBOSE = 2
# LOW_VERBOSE = 1
# NO_VERBOSE = 0
# class Event(object):
# def __init__(self, event, verbosity_level=None):
# def __str__(self):
# def has_output(self):
# def operation_info(self):
# def text(self):
# def log_level(self):
# def timestamp(self):
# def printable_timestamp(self):
# def event_type_indicator(self):
# def operation(self):
# def node_id(self):
# def source_id(self):
# def target_id(self):
# def deployment_id(self):
# def event_type(self):
# def is_log_message(self):
. Output only the next line. | causes=causes, |
Continue the code snippet: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
def get_celery_app(broker_url=None,
broker_ssl_cert_path=None,
broker_ssl_enabled=None,
max_retries=3,
tenant=None,
<|code_end|>
. Use current file imports:
from cloudify import broker_config
from cloudify.utils import internal
from cloudify.constants import (CELERY_TASK_RESULT_EXPIRES,
MGMTWORKER_QUEUE,
BROKER_PORT_SSL,
BROKER_PORT_NO_SSL)
from celery import Celery
and context (classes, functions, or code) from other files:
# Path: cloudify/broker_config.py
# DEFAULT_HEARTBEAT = 30
# BROKER_USE_SSL = {
# 'ca_certs': broker_cert_path,
# 'cert_reqs': ssl.CERT_REQUIRED,
# }
# URL_TEMPLATE = \
# 'amqp://{username}:{password}@{hostname}:{port}/{vhost}{options}'
# BROKER_URL = ';'.join(URL_TEMPLATE.format(username=broker_username,
# password=broker_password,
# hostname=node_ip,
# port=broker_port,
# vhost=broker_vhost,
# options=options)
# for node_ip in config['cluster'])
# BROKER_URL = URL_TEMPLATE.format(
# username=broker_username,
# password=broker_password,
# hostname=broker_hostname,
# port=broker_port,
# vhost=broker_vhost,
# options=options
# )
# CELERY_RESULT_BACKEND = BROKER_URL
# CELERY_TASK_RESULT_EXPIRES = 600
# CELERYD_PREFETCH_MULTIPLIER = 1
# CELERY_ACKS_LATE = False
#
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/constants.py
# CELERY_TASK_RESULT_EXPIRES = 600
#
# MGMTWORKER_QUEUE = 'cloudify.management'
#
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
. Output only the next line. | target=None): |
Predict the next line for this snippet: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
def get_celery_app(broker_url=None,
broker_ssl_cert_path=None,
broker_ssl_enabled=None,
max_retries=3,
<|code_end|>
with the help of current file imports:
from cloudify import broker_config
from cloudify.utils import internal
from cloudify.constants import (CELERY_TASK_RESULT_EXPIRES,
MGMTWORKER_QUEUE,
BROKER_PORT_SSL,
BROKER_PORT_NO_SSL)
from celery import Celery
and context from other files:
# Path: cloudify/broker_config.py
# DEFAULT_HEARTBEAT = 30
# BROKER_USE_SSL = {
# 'ca_certs': broker_cert_path,
# 'cert_reqs': ssl.CERT_REQUIRED,
# }
# URL_TEMPLATE = \
# 'amqp://{username}:{password}@{hostname}:{port}/{vhost}{options}'
# BROKER_URL = ';'.join(URL_TEMPLATE.format(username=broker_username,
# password=broker_password,
# hostname=node_ip,
# port=broker_port,
# vhost=broker_vhost,
# options=options)
# for node_ip in config['cluster'])
# BROKER_URL = URL_TEMPLATE.format(
# username=broker_username,
# password=broker_password,
# hostname=broker_hostname,
# port=broker_port,
# vhost=broker_vhost,
# options=options
# )
# CELERY_RESULT_BACKEND = BROKER_URL
# CELERY_TASK_RESULT_EXPIRES = 600
# CELERYD_PREFETCH_MULTIPLIER = 1
# CELERY_ACKS_LATE = False
#
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/constants.py
# CELERY_TASK_RESULT_EXPIRES = 600
#
# MGMTWORKER_QUEUE = 'cloudify.management'
#
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
, which may contain function names, class names, or code. Output only the next line. | tenant=None, |
Next line prediction: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
def get_celery_app(broker_url=None,
broker_ssl_cert_path=None,
broker_ssl_enabled=None,
<|code_end|>
. Use current file imports:
(from cloudify import broker_config
from cloudify.utils import internal
from cloudify.constants import (CELERY_TASK_RESULT_EXPIRES,
MGMTWORKER_QUEUE,
BROKER_PORT_SSL,
BROKER_PORT_NO_SSL)
from celery import Celery)
and context including class names, function names, or small code snippets from other files:
# Path: cloudify/broker_config.py
# DEFAULT_HEARTBEAT = 30
# BROKER_USE_SSL = {
# 'ca_certs': broker_cert_path,
# 'cert_reqs': ssl.CERT_REQUIRED,
# }
# URL_TEMPLATE = \
# 'amqp://{username}:{password}@{hostname}:{port}/{vhost}{options}'
# BROKER_URL = ';'.join(URL_TEMPLATE.format(username=broker_username,
# password=broker_password,
# hostname=node_ip,
# port=broker_port,
# vhost=broker_vhost,
# options=options)
# for node_ip in config['cluster'])
# BROKER_URL = URL_TEMPLATE.format(
# username=broker_username,
# password=broker_password,
# hostname=broker_hostname,
# port=broker_port,
# vhost=broker_vhost,
# options=options
# )
# CELERY_RESULT_BACKEND = BROKER_URL
# CELERY_TASK_RESULT_EXPIRES = 600
# CELERYD_PREFETCH_MULTIPLIER = 1
# CELERY_ACKS_LATE = False
#
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/constants.py
# CELERY_TASK_RESULT_EXPIRES = 600
#
# MGMTWORKER_QUEUE = 'cloudify.management'
#
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
. Output only the next line. | max_retries=3, |
Based on the snippet: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
def get_celery_app(broker_url=None,
broker_ssl_cert_path=None,
broker_ssl_enabled=None,
max_retries=3,
<|code_end|>
, predict the immediate next line with the help of imports:
from cloudify import broker_config
from cloudify.utils import internal
from cloudify.constants import (CELERY_TASK_RESULT_EXPIRES,
MGMTWORKER_QUEUE,
BROKER_PORT_SSL,
BROKER_PORT_NO_SSL)
from celery import Celery
and context (classes, functions, sometimes code) from other files:
# Path: cloudify/broker_config.py
# DEFAULT_HEARTBEAT = 30
# BROKER_USE_SSL = {
# 'ca_certs': broker_cert_path,
# 'cert_reqs': ssl.CERT_REQUIRED,
# }
# URL_TEMPLATE = \
# 'amqp://{username}:{password}@{hostname}:{port}/{vhost}{options}'
# BROKER_URL = ';'.join(URL_TEMPLATE.format(username=broker_username,
# password=broker_password,
# hostname=node_ip,
# port=broker_port,
# vhost=broker_vhost,
# options=options)
# for node_ip in config['cluster'])
# BROKER_URL = URL_TEMPLATE.format(
# username=broker_username,
# password=broker_password,
# hostname=broker_hostname,
# port=broker_port,
# vhost=broker_vhost,
# options=options
# )
# CELERY_RESULT_BACKEND = BROKER_URL
# CELERY_TASK_RESULT_EXPIRES = 600
# CELERYD_PREFETCH_MULTIPLIER = 1
# CELERY_ACKS_LATE = False
#
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/constants.py
# CELERY_TASK_RESULT_EXPIRES = 600
#
# MGMTWORKER_QUEUE = 'cloudify.management'
#
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
. Output only the next line. | tenant=None, |
Predict the next line after this snippet: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
def get_celery_app(broker_url=None,
broker_ssl_cert_path=None,
broker_ssl_enabled=None,
<|code_end|>
using the current file's imports:
from cloudify import broker_config
from cloudify.utils import internal
from cloudify.constants import (CELERY_TASK_RESULT_EXPIRES,
MGMTWORKER_QUEUE,
BROKER_PORT_SSL,
BROKER_PORT_NO_SSL)
from celery import Celery
and any relevant context from other files:
# Path: cloudify/broker_config.py
# DEFAULT_HEARTBEAT = 30
# BROKER_USE_SSL = {
# 'ca_certs': broker_cert_path,
# 'cert_reqs': ssl.CERT_REQUIRED,
# }
# URL_TEMPLATE = \
# 'amqp://{username}:{password}@{hostname}:{port}/{vhost}{options}'
# BROKER_URL = ';'.join(URL_TEMPLATE.format(username=broker_username,
# password=broker_password,
# hostname=node_ip,
# port=broker_port,
# vhost=broker_vhost,
# options=options)
# for node_ip in config['cluster'])
# BROKER_URL = URL_TEMPLATE.format(
# username=broker_username,
# password=broker_password,
# hostname=broker_hostname,
# port=broker_port,
# vhost=broker_vhost,
# options=options
# )
# CELERY_RESULT_BACKEND = BROKER_URL
# CELERY_TASK_RESULT_EXPIRES = 600
# CELERYD_PREFETCH_MULTIPLIER = 1
# CELERY_ACKS_LATE = False
#
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/constants.py
# CELERY_TASK_RESULT_EXPIRES = 600
#
# MGMTWORKER_QUEUE = 'cloudify.management'
#
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
. Output only the next line. | max_retries=3, |
Given the following code snippet before the placeholder: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.
def get_celery_app(broker_url=None,
broker_ssl_cert_path=None,
broker_ssl_enabled=None,
max_retries=3,
<|code_end|>
, predict the next line using imports from the current file:
from cloudify import broker_config
from cloudify.utils import internal
from cloudify.constants import (CELERY_TASK_RESULT_EXPIRES,
MGMTWORKER_QUEUE,
BROKER_PORT_SSL,
BROKER_PORT_NO_SSL)
from celery import Celery
and context including class names, function names, and sometimes code from other files:
# Path: cloudify/broker_config.py
# DEFAULT_HEARTBEAT = 30
# BROKER_USE_SSL = {
# 'ca_certs': broker_cert_path,
# 'cert_reqs': ssl.CERT_REQUIRED,
# }
# URL_TEMPLATE = \
# 'amqp://{username}:{password}@{hostname}:{port}/{vhost}{options}'
# BROKER_URL = ';'.join(URL_TEMPLATE.format(username=broker_username,
# password=broker_password,
# hostname=node_ip,
# port=broker_port,
# vhost=broker_vhost,
# options=options)
# for node_ip in config['cluster'])
# BROKER_URL = URL_TEMPLATE.format(
# username=broker_username,
# password=broker_password,
# hostname=broker_hostname,
# port=broker_port,
# vhost=broker_vhost,
# options=options
# )
# CELERY_RESULT_BACKEND = BROKER_URL
# CELERY_TASK_RESULT_EXPIRES = 600
# CELERYD_PREFETCH_MULTIPLIER = 1
# CELERY_ACKS_LATE = False
#
# Path: cloudify/utils.py
# CFY_EXEC_TEMPDIR_ENVVAR = 'CFY_EXEC_TEMP'
# class ManagerVersion(object):
# class LocalCommandRunner(object):
# class CommandExecutionResponse(object):
# class Internal(object):
# def __init__(self, raw_version):
# def greater_than(self, other):
# def equals(self, other):
# def __str__(self):
# def __eq__(self, other):
# def __gt__(self, other):
# def __lt__(self, other):
# def __ge__(self, other):
# def __le__(self, other):
# def __ne__(self, other):
# def setup_logger(logger_name,
# logger_level=logging.INFO,
# handlers=None,
# remove_existing_handlers=True,
# logger_format=None,
# propagate=True):
# def format_exception(e):
# def get_manager_file_server_url():
# def get_manager_file_server_root():
# def get_manager_rest_service_host():
# def get_broker_ssl_cert_path():
# def get_manager_rest_service_port():
# def get_local_rest_certificate():
# def _get_current_context():
# def get_rest_token():
# def get_tenant():
# def get_tenant_name():
# def get_is_bypass_maintenance():
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# def get_exec_tempdir():
# def create_temp_folder():
# def exception_to_error_cause(exception, tb):
# def __init__(self, logger=None, host='localhost'):
# def run(self, command,
# exit_on_failure=True,
# stdout_pipe=True,
# stderr_pipe=True,
# cwd=None,
# execution_env=None):
# def __init__(self, command, std_out, std_err, return_code):
# def _shlex_split(command):
# def get_install_method(properties):
# def get_broker_ssl_options(ssl_enabled, cert_path):
# def get_broker_credentials(cloudify_agent):
# def _get_package_version(plugins_dir, package_name):
# def plugin_prefix(package_name=None, package_version=None,
# deployment_id=None, plugin_name=None, tenant_name=None,
# sys_prefix_fallback=True):
# def _change_tenant(ctx, tenant):
#
# Path: cloudify/constants.py
# CELERY_TASK_RESULT_EXPIRES = 600
#
# MGMTWORKER_QUEUE = 'cloudify.management'
#
# BROKER_PORT_SSL = 5671
#
# BROKER_PORT_NO_SSL = 5672
. Output only the next line. | tenant=None, |
Predict the next line for this snippet: <|code_start|>
# from slugify import slugify_url
TOPIC_ID = "topic"
LINK_ID = "link"
class Topic(Object, RenderedTextMixin):
__mapper_args__ = {
'polymorphic_identity': TOPIC_ID
<|code_end|>
with the help of current file imports:
from beavy.models.object import Object
from beavy.common.rendered_text_mixin import RenderedTextMixin
from beavy.common.payload_property import PayloadProperty
and context from other files:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/common/rendered_text_mixin.py
# class RenderedTextMixin(object):
# # to be used on activity or object models
#
# raw = PayloadProperty('raw', 'text')
# chopped = PayloadProperty('chopped', 'text')
# cooked = PayloadProperty('cooked', 'text')
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
, which may contain function names, class names, or code. Output only the next line. | } |
Given the following code snippet before the placeholder: <|code_start|>
# from slugify import slugify_url
TOPIC_ID = "topic"
LINK_ID = "link"
class Topic(Object, RenderedTextMixin):
__mapper_args__ = {
<|code_end|>
, predict the next line using imports from the current file:
from beavy.models.object import Object
from beavy.common.rendered_text_mixin import RenderedTextMixin
from beavy.common.payload_property import PayloadProperty
and context including class names, function names, and sometimes code from other files:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/common/rendered_text_mixin.py
# class RenderedTextMixin(object):
# # to be used on activity or object models
#
# raw = PayloadProperty('raw', 'text')
# chopped = PayloadProperty('chopped', 'text')
# cooked = PayloadProperty('cooked', 'text')
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
. Output only the next line. | 'polymorphic_identity': TOPIC_ID |
Using the snippet: <|code_start|>
# from slugify import slugify_url
TOPIC_ID = "topic"
LINK_ID = "link"
class Topic(Object, RenderedTextMixin):
__mapper_args__ = {
'polymorphic_identity': TOPIC_ID
}
title = PayloadProperty('title')
text = PayloadProperty('text')
CAPABILITIES = [Object.Capabilities.listed, Object.Capabilities.searchable]
class Link(Object):
<|code_end|>
, determine the next line of code. You have imports:
from beavy.models.object import Object
from beavy.common.rendered_text_mixin import RenderedTextMixin
from beavy.common.payload_property import PayloadProperty
and context (class names, function names, or code) available:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/common/rendered_text_mixin.py
# class RenderedTextMixin(object):
# # to be used on activity or object models
#
# raw = PayloadProperty('raw', 'text')
# chopped = PayloadProperty('chopped', 'text')
# cooked = PayloadProperty('cooked', 'text')
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
. Output only the next line. | __mapper_args__ = { |
Next line prediction: <|code_start|>
def before_scenario(context, scenario):
benv.before_scenario(context, scenario)
context.personas = ensure_personas()
def after_scenario(context, scenario):
if getattr(context, "browser", None):
has_warnings = False
for entry in context.browser.driver.get_log('browser'):
if entry["level"] not in ["WARNING", "ERROR"]:
continue
try:
msg = json.loads(entry["message"])["message"]
except (ValueError, KeyError):
pass
else:
# in chrome we can extract much more info!
if msg["level"] in ["warn", "error"] and \
msg.get("source") == "console-api":
entry = dict(level=msg["level"],
timestamp=entry["timestamp"],
message=msg["text"])
else:
continue
<|code_end|>
. Use current file imports:
(from behaving import environment as benv
from beavy.app import app
from .database import ensure_personas, mixer
from pprint import pprint
import logging
import json
import os
import ipdb as pdb
import pdb)
and context including class names, function names, or small code snippets from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/testing/database.py
# def ensure_personas():
. Output only the next line. | has_warnings = True |
Predict the next line after this snippet: <|code_start|># import os
log = logging.Logger(__name__)
BEHAVE_DEBUG_ON_ERROR = not os.getenv("CI", False)
BEHAVE_ERROR_ON_BROWSER_WARNINGS = os.getenv("BEHAVE_ERROR_ON_BROWSER_WARNINGS", not BEHAVE_DEBUG_ON_ERROR) # noqa
def before_all(context):
context.default_browser = os.getenv("BEHAVE_DEFAULT_BROWSER", 'chrome')
<|code_end|>
using the current file's imports:
from behaving import environment as benv
from beavy.app import app
from .database import ensure_personas, mixer
from pprint import pprint
import logging
import json
import os
import ipdb as pdb
import pdb
and any relevant context from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/testing/database.py
# def ensure_personas():
. Output only the next line. | context.default_browser_size = (1280, 1024) |
Here is a snippet: <|code_start|># import os
log = logging.Logger(__name__)
BEHAVE_DEBUG_ON_ERROR = not os.getenv("CI", False)
BEHAVE_ERROR_ON_BROWSER_WARNINGS = os.getenv("BEHAVE_ERROR_ON_BROWSER_WARNINGS", not BEHAVE_DEBUG_ON_ERROR) # noqa
def before_all(context):
context.default_browser = os.getenv("BEHAVE_DEFAULT_BROWSER", 'chrome')
context.default_browser_size = (1280, 1024)
port = "2992" if app.config.get("DEBUG", False) else "5000"
default_url = "http://localhost:{}".format(port)
context.base_url = os.getenv("BEHAVE_BASE_URL", default_url)
benv.before_all(context)
mixer.init_app(app)
<|code_end|>
. Write the next line using the current file imports:
from behaving import environment as benv
from beavy.app import app
from .database import ensure_personas, mixer
from pprint import pprint
import logging
import json
import os
import ipdb as pdb
import pdb
and context from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
#
# Path: beavy/testing/database.py
# def ensure_personas():
, which may include functions, classes, or code. Output only the next line. | def after_all(context): |
Using the snippet: <|code_start|># , Schema, fields
class PrivateMessageSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
<|code_end|>
, determine the next line of code. You have imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import PM_ID
and context (class names, function names, or code) available:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_modules/private_messaging/models.py
# PM_ID = "private_message"
. Output only the next line. | title = fields.String() |
Using the snippet: <|code_start|># , Schema, fields
class PrivateMessageSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
title = fields.String()
type = fields.String(attribute="discriminator")
<|code_end|>
, determine the next line of code. You have imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import PM_ID
and context (class names, function names, or code) available:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_modules/private_messaging/models.py
# PM_ID = "private_message"
. Output only the next line. | class Meta: |
Given snippet: <|code_start|>
COMMENT_ID = "comment"
class CommentObject(Object, RenderedTextMixin):
__mapper_args__ = {
'polymorphic_identity': COMMENT_ID
}
CAPABILITIES = [Object.Capabilities.listed_for_activity]
in_reply_to_id = db.Column(db.Integer, db.ForeignKey("objects.id"),
nullable=True)
# in_reply_to = db.relationship(Object, backref=db.backref('replies'))
def filter_comments_for_view(cls, method):
if not current_user or current_user.is_anonymous:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from beavy.models.object import Object
from flask_security.core import current_user
from sqlalchemy.sql import and_
from beavy.common.rendered_text_mixin import RenderedTextMixin
from beavy.app import db
and context:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/common/rendered_text_mixin.py
# class RenderedTextMixin(object):
# # to be used on activity or object models
#
# raw = PayloadProperty('raw', 'text')
# chopped = PayloadProperty('chopped', 'text')
# cooked = PayloadProperty('cooked', 'text')
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
which might include code, classes, or functions. Output only the next line. | return |
Given the code snippet: <|code_start|>
COMMENT_ID = "comment"
class CommentObject(Object, RenderedTextMixin):
__mapper_args__ = {
'polymorphic_identity': COMMENT_ID
}
CAPABILITIES = [Object.Capabilities.listed_for_activity]
in_reply_to_id = db.Column(db.Integer, db.ForeignKey("objects.id"),
<|code_end|>
, generate the next line using the imports in this file:
from beavy.models.object import Object
from flask_security.core import current_user
from sqlalchemy.sql import and_
from beavy.common.rendered_text_mixin import RenderedTextMixin
from beavy.app import db
and context (functions, classes, or occasionally code) from other files:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/common/rendered_text_mixin.py
# class RenderedTextMixin(object):
# # to be used on activity or object models
#
# raw = PayloadProperty('raw', 'text')
# chopped = PayloadProperty('chopped', 'text')
# cooked = PayloadProperty('cooked', 'text')
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | nullable=True) |
Using the snippet: <|code_start|>
COMMENT_ID = "comment"
class CommentObject(Object, RenderedTextMixin):
__mapper_args__ = {
'polymorphic_identity': COMMENT_ID
}
CAPABILITIES = [Object.Capabilities.listed_for_activity]
in_reply_to_id = db.Column(db.Integer, db.ForeignKey("objects.id"),
nullable=True)
# in_reply_to = db.relationship(Object, backref=db.backref('replies'))
def filter_comments_for_view(cls, method):
if not current_user or current_user.is_anonymous:
return
return and_(cls.discriminator == COMMENT_ID,
<|code_end|>
, determine the next line of code. You have imports:
from beavy.models.object import Object
from flask_security.core import current_user
from sqlalchemy.sql import and_
from beavy.common.rendered_text_mixin import RenderedTextMixin
from beavy.app import db
and context (class names, function names, or code) available:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/common/rendered_text_mixin.py
# class RenderedTextMixin(object):
# # to be used on activity or object models
#
# raw = PayloadProperty('raw', 'text')
# chopped = PayloadProperty('chopped', 'text')
# cooked = PayloadProperty('cooked', 'text')
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | cls.owner_id == current_user.id) |
Predict the next line for this snippet: <|code_start|># from marshmallow import Schema, fields
# class BaseLike(Schema):
# subject = fields.Nested(BaseUser)
# created_at = fields.DateTime()
# ActivityField.registry['like'] = BaseLike
class UserLike(Schema):
id = fields.Integer()
created_at = fields.DateTime()
TUPLE_KEY = 'Like'
REMAP_TUPLE_KEYS = ('Object', )
class Meta:
type_ = "like"
@pre_dump
def extract_items(self, item):
if isinstance(item, tuple):
tup = item
item = getattr(item, self.TUPLE_KEY)
for key in self.REMAP_TUPLE_KEYS:
setattr(item, key.lower(), getattr(tup, key))
<|code_end|>
with the help of current file imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from beavy.schemas.object import ObjectField
from marshmallow_jsonapi import Schema, fields
from marshmallow import pre_dump
and context from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
, which may contain function names, class names, or code. Output only the next line. | return item |
Predict the next line for this snippet: <|code_start|># from marshmallow import Schema, fields
# class BaseLike(Schema):
# subject = fields.Nested(BaseUser)
# created_at = fields.DateTime()
# ActivityField.registry['like'] = BaseLike
class UserLike(Schema):
id = fields.Integer()
created_at = fields.DateTime()
TUPLE_KEY = 'Like'
REMAP_TUPLE_KEYS = ('Object', )
class Meta:
type_ = "like"
@pre_dump
def extract_items(self, item):
if isinstance(item, tuple):
tup = item
item = getattr(item, self.TUPLE_KEY)
<|code_end|>
with the help of current file imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from beavy.schemas.object import ObjectField
from marshmallow_jsonapi import Schema, fields
from marshmallow import pre_dump
and context from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
, which may contain function names, class names, or code. Output only the next line. | for key in self.REMAP_TUPLE_KEYS: |
Given the code snippet: <|code_start|># , Schema, fields
class CommentSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
text = fields.String(attribute='cooked')
belongs_to_id = fields.Integer()
in_reply_to_id = fields.Integer()
class Meta:
type_ = COMMENT_ID # Required
author = IncludingHyperlinkRelated(BaseUser,
'/users/{user_id}',
<|code_end|>
, generate the next line using the imports in this file:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import COMMENT_ID
and context (functions, classes, or occasionally code) from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_modules/comments/models.py
# COMMENT_ID = "comment"
. Output only the next line. | url_kwargs={'user_id': '<owner_id>'}, |
Here is a snippet: <|code_start|># , Schema, fields
class CommentSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
text = fields.String(attribute='cooked')
belongs_to_id = fields.Integer()
in_reply_to_id = fields.Integer()
class Meta:
type_ = COMMENT_ID # Required
author = IncludingHyperlinkRelated(BaseUser,
'/users/{user_id}',
url_kwargs={'user_id': '<owner_id>'},
many=False, include_data=True,
type_='user')
<|code_end|>
. Write the next line using the current file imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import COMMENT_ID
and context from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_modules/comments/models.py
# COMMENT_ID = "comment"
, which may include functions, classes, or code. Output only the next line. | comment = CommentSchema() |
Given snippet: <|code_start|># , Schema, fields
class CommentSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
text = fields.String(attribute='cooked')
belongs_to_id = fields.Integer()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import COMMENT_ID
and context:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_modules/comments/models.py
# COMMENT_ID = "comment"
which might include code, classes, or functions. Output only the next line. | in_reply_to_id = fields.Integer() |
Given snippet: <|code_start|># , Schema, fields
class CommentSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import COMMENT_ID
and context:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_modules/comments/models.py
# COMMENT_ID = "comment"
which might include code, classes, or functions. Output only the next line. | text = fields.String(attribute='cooked') |
Using the snippet: <|code_start|>
class TopicSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
title = fields.String(attribute='title')
slug = fields.String(attribute='slug')
text = fields.String(attribute='cooked')
class Meta:
type_ = TOPIC_ID # Required
author = IncludingHyperlinkRelated(BaseUser,
'/users/{user_id}',
url_kwargs={'user_id': '<owner_id>'},
many=False, include_data=True,
type_='user')
topic = TopicSchema()
topic_paged = makePaginationSchema(TopicSchema)()
ObjectField.registry[TOPIC_ID] = TopicSchema
class LinkSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
<|code_end|>
, determine the next line of code. You have imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import TOPIC_ID, LINK_ID
and context (class names, function names, or code) available:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_apps/hacker_news/models.py
# TOPIC_ID = "topic"
#
# LINK_ID = "link"
. Output only the next line. | type = fields.String(attribute="discriminator") |
Predict the next line for this snippet: <|code_start|># , Schema, fields
class TopicSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
title = fields.String(attribute='title')
slug = fields.String(attribute='slug')
text = fields.String(attribute='cooked')
<|code_end|>
with the help of current file imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import TOPIC_ID, LINK_ID
and context from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_apps/hacker_news/models.py
# TOPIC_ID = "topic"
#
# LINK_ID = "link"
, which may contain function names, class names, or code. Output only the next line. | class Meta: |
Based on the snippet: <|code_start|># , Schema, fields
class TopicSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
title = fields.String(attribute='title')
slug = fields.String(attribute='slug')
text = fields.String(attribute='cooked')
class Meta:
type_ = TOPIC_ID # Required
author = IncludingHyperlinkRelated(BaseUser,
'/users/{user_id}',
url_kwargs={'user_id': '<owner_id>'},
many=False, include_data=True,
<|code_end|>
, predict the immediate next line with the help of imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import TOPIC_ID, LINK_ID
and context (classes, functions, sometimes code) from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_apps/hacker_news/models.py
# TOPIC_ID = "topic"
#
# LINK_ID = "link"
. Output only the next line. | type_='user') |
Using the snippet: <|code_start|>class TopicSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
title = fields.String(attribute='title')
slug = fields.String(attribute='slug')
text = fields.String(attribute='cooked')
class Meta:
type_ = TOPIC_ID # Required
author = IncludingHyperlinkRelated(BaseUser,
'/users/{user_id}',
url_kwargs={'user_id': '<owner_id>'},
many=False, include_data=True,
type_='user')
topic = TopicSchema()
topic_paged = makePaginationSchema(TopicSchema)()
ObjectField.registry[TOPIC_ID] = TopicSchema
class LinkSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
title = fields.String(attribute='title')
<|code_end|>
, determine the next line of code. You have imports:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import TOPIC_ID, LINK_ID
and context (class names, function names, or code) available:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_apps/hacker_news/models.py
# TOPIC_ID = "topic"
#
# LINK_ID = "link"
. Output only the next line. | slug = fields.String(attribute='slug') |
Given the code snippet: <|code_start|># , Schema, fields
class TopicSchema(Schema):
id = fields.Integer()
created_at = fields.DateTime()
owner_id = fields.Integer()
type = fields.String(attribute="discriminator")
title = fields.String(attribute='title')
slug = fields.String(attribute='slug')
text = fields.String(attribute='cooked')
<|code_end|>
, generate the next line using the imports in this file:
from beavy.common.paging_schema import makePaginationSchema
from beavy.schemas.object import ObjectField
from beavy.common.including_hyperlink_related import IncludingHyperlinkRelated
from marshmallow_jsonapi import Schema, fields
from beavy.schemas.user import BaseUser
from .models import TOPIC_ID, LINK_ID
and context (functions, classes, or occasionally code) from other files:
# Path: beavy/common/paging_schema.py
# def makePaginationSchema(itemsCls, field_cls=fields.Nested):
# return type("{}Paging".format(itemsCls.__class__.__name__),
# (BasePaging, ), dict(items=field_cls(itemsCls, many=True)))
#
# Path: beavy/schemas/object.py
# class ObjectField(MorphingSchema):
# FALLBACK = BaseObject
# registry = {}
#
# Path: beavy/common/including_hyperlink_related.py
# class IncludingHyperlinkRelated(Relationship):
#
# def __init__(self, nestedObj, *args, **kwargs):
# if callable(nestedObj):
# nestedObj = nestedObj(many=False)
# self.nestedObj = nestedObj
# kwargs['type_'] = " "
# kwargs['include_data'] = True
# super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
#
# def add_resource_linkage(self, value):
# def render(item):
# attributes = self._extract_attributes(item)
# type_ = attributes.pop('type', self.type_)
# return {'type': type_,
# 'id': get_value_or_raise(self.id_field, item),
# 'attributes': attributes}
# if self.many:
# included_data = [render(each) for each in value]
# else:
# included_data = render(value)
# return included_data
#
# def _extract_attributes(self, value):
# sub = self.nestedObj.dump(value).data
# try:
# return sub["data"]["attributes"]
# except (KeyError, TypeError):
# # we are a classic type
# pass
# return sub
#
# Path: beavy/schemas/user.py
# class BaseUser(Schema):
# class Meta:
# type_ = "user"
#
# id = fields.Function(lambda obj: obj.__LOOKUP_ATTRS__ and
# getattr(obj, obj.__LOOKUP_ATTRS__[0]) or
# obj.id)
# beavyId = fields.Integer(attribute="id")
# name = fields.String()
# active = fields.Boolean()
# created_at = fields.DateTime()
# language_preference = fields.String()
#
# Path: beavy_apps/hacker_news/models.py
# TOPIC_ID = "topic"
#
# LINK_ID = "link"
. Output only the next line. | class Meta: |
Based on the snippet: <|code_start|>
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id',
db.Integer(),
db.ForeignKey('user.id'),
<|code_end|>
, predict the immediate next line with the help of imports:
from flask.ext.security import UserMixin
from flask_security.forms import ConfirmRegisterForm, RegisterForm, StringField
from sqlalchemy import func
from beavy.app import db
and context (classes, functions, sometimes code) from other files:
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | nullable=False), |
Given the code snippet: <|code_start|>
class ObjectQuery(AccessQuery):
def by_capability(self, aborting=True, abort_code=404, *caps):
caps = set(chain.from_iterable(map(lambda c:
getattr(Object.TypesForCapability,
getattr(c, 'value', c), []),
caps)))
if not caps:
# No types found, break right here.
if aborting:
raise abort(abort_code)
return self.filter("1=0")
return self.filter(Object.discriminator.in_(caps))
def with_my_activities(self):
if not current_user or not current_user.is_authenticated:
return self
<|code_end|>
, generate the next line using the imports in this file:
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import contains_eager, aliased
from enum import Enum, unique
from sqlalchemy import func
from flask.ext.security import current_user
from beavy.common.access_query import AccessQuery
from itertools import chain
from flask import abort
from .user import User
from beavy.app import db
from collections import defaultdict
from .activity import Activity
and context (functions, classes, or occasionally code) from other files:
# Path: beavy/common/access_query.py
# class AccessQuery(BaseQuery):
#
# def _gen_filters(self, class_, fltr):
# return [x for x in filter(lambda x: x is not None, [
# t(class_, fltr)
# # weirdly class_.__access_filters fails on us
# # probably some sqlalchemy magic
# for t in getattr(class_, "__access_filters")[fltr]]
# )
# ]
#
# def filter_visible(self, attr, remoteAttr):
# filters = self._gen_filters(remoteAttr.class_, 'view')
# if not filters:
# return self.filter(False)
#
# return self.filter(attr.in_(
# remoteAttr.class_.query.filter(or_(*filters))
# .with_entities(remoteAttr)
# .subquery()
# )
# )
#
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
# __LOOKUP_ATTRS__ = []
# id = db.Column(db.Integer, primary_key=True)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# email = db.Column(db.String(255), unique=True, nullable=False)
# name = db.Column(db.String(255))
# password = db.Column(db.String(255))
# active = db.Column(db.Boolean())
# confirmed_at = db.Column(db.DateTime())
#
# last_login_at = db.Column(db.DateTime())
# current_login_at = db.Column(db.DateTime())
# last_login_ip = db.Column(db.String(255))
# current_login_ip = db.Column(db.String(255))
# login_count = db.Column(db.Integer())
# language_preference = db.Column(db.String(2))
#
# roles = db.relationship('Role', secondary=roles_users,
# backref=db.backref('users', lazy='dynamic'))
#
# def __str__(self):
# return "<User #{} '{}' ({})>".format(self.id,
# self.name or "",
# self.email)
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | my_activities = aliased(Activity.query.filter( |
Given the following code snippet before the placeholder: <|code_start|>
class ObjectQuery(AccessQuery):
def by_capability(self, aborting=True, abort_code=404, *caps):
caps = set(chain.from_iterable(map(lambda c:
getattr(Object.TypesForCapability,
getattr(c, 'value', c), []),
caps)))
if not caps:
# No types found, break right here.
<|code_end|>
, predict the next line using imports from the current file:
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import contains_eager, aliased
from enum import Enum, unique
from sqlalchemy import func
from flask.ext.security import current_user
from beavy.common.access_query import AccessQuery
from itertools import chain
from flask import abort
from .user import User
from beavy.app import db
from collections import defaultdict
from .activity import Activity
and context including class names, function names, and sometimes code from other files:
# Path: beavy/common/access_query.py
# class AccessQuery(BaseQuery):
#
# def _gen_filters(self, class_, fltr):
# return [x for x in filter(lambda x: x is not None, [
# t(class_, fltr)
# # weirdly class_.__access_filters fails on us
# # probably some sqlalchemy magic
# for t in getattr(class_, "__access_filters")[fltr]]
# )
# ]
#
# def filter_visible(self, attr, remoteAttr):
# filters = self._gen_filters(remoteAttr.class_, 'view')
# if not filters:
# return self.filter(False)
#
# return self.filter(attr.in_(
# remoteAttr.class_.query.filter(or_(*filters))
# .with_entities(remoteAttr)
# .subquery()
# )
# )
#
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
# __LOOKUP_ATTRS__ = []
# id = db.Column(db.Integer, primary_key=True)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# email = db.Column(db.String(255), unique=True, nullable=False)
# name = db.Column(db.String(255))
# password = db.Column(db.String(255))
# active = db.Column(db.Boolean())
# confirmed_at = db.Column(db.DateTime())
#
# last_login_at = db.Column(db.DateTime())
# current_login_at = db.Column(db.DateTime())
# last_login_ip = db.Column(db.String(255))
# current_login_ip = db.Column(db.String(255))
# login_count = db.Column(db.Integer())
# language_preference = db.Column(db.String(2))
#
# roles = db.relationship('Role', secondary=roles_users,
# backref=db.backref('users', lazy='dynamic'))
#
# def __str__(self):
# return "<User #{} '{}' ({})>".format(self.id,
# self.name or "",
# self.email)
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | if aborting: |
Given snippet: <|code_start|>
PM_ID = "private_message"
# Define models
PMParticipants = db.Table('{}_participants'.format(PM_ID),
db.Column('user_id',
db.Integer(),
db.ForeignKey(User.id),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from beavy.models.object import Object
from beavy.models.object import User
from beavy.common.payload_property import PayloadProperty
from beavy.utils.url_converters import ModelConverter
from beavy.app import db
and context:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/models/object.py
# class ObjectQuery(AccessQuery):
# class Object(db.Model):
# class Capabilities(Enum):
# def by_capability(self, aborting=True, abort_code=404, *caps):
# def with_my_activities(self):
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
#
# Path: beavy/utils/url_converters.py
# class ModelConverter(BaseConverter):
# __OBJECTS__ = {
# 'user': User,
# 'object': Object,
# 'activity': Activity
# }
#
# def __init__(self, url_map, obj="object"):
# super(ModelConverter, self).__init__(url_map)
# # match ID or string
# self.regex = '-?\d+|\S+'
# self.cls = self.__OBJECTS__[obj]
#
# def to_python(self, value):
# cls = self.cls
# try:
# return cls.query.get_or_404(int(value))
# except ValueError:
# pass
#
# if not getattr(cls, "__LOOKUP_ATTRS__", False):
# abort(404)
#
# return cls.query.filter(or_(*[getattr(cls, key) == value
# for key in cls.__LOOKUP_ATTRS__])
# ).first_or_404()
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
which might include code, classes, or functions. Output only the next line. | nullable=False), |
Predict the next line for this snippet: <|code_start|>
PM_ID = "private_message"
# Define models
PMParticipants = db.Table('{}_participants'.format(PM_ID),
db.Column('user_id',
db.Integer(),
db.ForeignKey(User.id),
nullable=False),
db.Column('pm_id',
db.Integer(),
db.ForeignKey("objects.id"),
nullable=False))
class PrivateMessage(Object):
__mapper_args__ = {
'polymorphic_identity': PM_ID
}
title = PayloadProperty('title')
# db.Column(db.String(255), nullable=False)
participants = db.relationship('User', secondary=PMParticipants,
backref=db.backref('{}s'.format(PM_ID),
<|code_end|>
with the help of current file imports:
from beavy.models.object import Object
from beavy.models.object import User
from beavy.common.payload_property import PayloadProperty
from beavy.utils.url_converters import ModelConverter
from beavy.app import db
and context from other files:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/models/object.py
# class ObjectQuery(AccessQuery):
# class Object(db.Model):
# class Capabilities(Enum):
# def by_capability(self, aborting=True, abort_code=404, *caps):
# def with_my_activities(self):
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
#
# Path: beavy/utils/url_converters.py
# class ModelConverter(BaseConverter):
# __OBJECTS__ = {
# 'user': User,
# 'object': Object,
# 'activity': Activity
# }
#
# def __init__(self, url_map, obj="object"):
# super(ModelConverter, self).__init__(url_map)
# # match ID or string
# self.regex = '-?\d+|\S+'
# self.cls = self.__OBJECTS__[obj]
#
# def to_python(self, value):
# cls = self.cls
# try:
# return cls.query.get_or_404(int(value))
# except ValueError:
# pass
#
# if not getattr(cls, "__LOOKUP_ATTRS__", False):
# abort(404)
#
# return cls.query.filter(or_(*[getattr(cls, key) == value
# for key in cls.__LOOKUP_ATTRS__])
# ).first_or_404()
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
, which may contain function names, class names, or code. Output only the next line. | lazy='dynamic')) |
Next line prediction: <|code_start|>
PM_ID = "private_message"
# Define models
PMParticipants = db.Table('{}_participants'.format(PM_ID),
db.Column('user_id',
db.Integer(),
db.ForeignKey(User.id),
nullable=False),
db.Column('pm_id',
db.Integer(),
db.ForeignKey("objects.id"),
<|code_end|>
. Use current file imports:
(from beavy.models.object import Object
from beavy.models.object import User
from beavy.common.payload_property import PayloadProperty
from beavy.utils.url_converters import ModelConverter
from beavy.app import db)
and context including class names, function names, or small code snippets from other files:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/models/object.py
# class ObjectQuery(AccessQuery):
# class Object(db.Model):
# class Capabilities(Enum):
# def by_capability(self, aborting=True, abort_code=404, *caps):
# def with_my_activities(self):
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
#
# Path: beavy/utils/url_converters.py
# class ModelConverter(BaseConverter):
# __OBJECTS__ = {
# 'user': User,
# 'object': Object,
# 'activity': Activity
# }
#
# def __init__(self, url_map, obj="object"):
# super(ModelConverter, self).__init__(url_map)
# # match ID or string
# self.regex = '-?\d+|\S+'
# self.cls = self.__OBJECTS__[obj]
#
# def to_python(self, value):
# cls = self.cls
# try:
# return cls.query.get_or_404(int(value))
# except ValueError:
# pass
#
# if not getattr(cls, "__LOOKUP_ATTRS__", False):
# abort(404)
#
# return cls.query.filter(or_(*[getattr(cls, key) == value
# for key in cls.__LOOKUP_ATTRS__])
# ).first_or_404()
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | nullable=False)) |
Based on the snippet: <|code_start|>
PM_ID = "private_message"
# Define models
PMParticipants = db.Table('{}_participants'.format(PM_ID),
db.Column('user_id',
db.Integer(),
db.ForeignKey(User.id),
<|code_end|>
, predict the immediate next line with the help of imports:
from beavy.models.object import Object
from beavy.models.object import User
from beavy.common.payload_property import PayloadProperty
from beavy.utils.url_converters import ModelConverter
from beavy.app import db
and context (classes, functions, sometimes code) from other files:
# Path: beavy/models/object.py
# class Object(db.Model):
# """
# This is the primary base class for all kind of objects
# we know of inside the system
# """
# @unique
# class Capabilities(Enum):
# # This type is to be shown in default lists
# # like 'top', 'latest' etc
# listed = 'listed'
#
# # If the type isn't listed but has `listed_for_activity`
# # it can show up in lists about activitys, for example
# # when an object got liked
# listed_for_activity = 'a_listable'
#
# # This can be searched for
# searchable = 'searchable'
#
# __tablename__ = "objects"
# query_class = ObjectQuery
#
# id = db.Column(db.Integer, primary_key=True)
# discriminator = db.Column('type', db.String(100), nullable=False)
# created_at = db.Column('created_at', db.DateTime(), nullable=False,
# server_default=func.now())
# payload = db.Column('payload', JSONB, nullable=True)
# owner_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
# belongs_to = db.Column(db.Integer, db.ForeignKey("objects.id"),
# nullable=True)
# # children = db.relationship("Object", backref=db.backref('belongs_to',
# # remote_side=id))
#
# __mapper_args__ = {'polymorphic_on': discriminator}
#
# owner = db.relationship(User, backref=db.backref('objects'))
#
# Path: beavy/models/object.py
# class ObjectQuery(AccessQuery):
# class Object(db.Model):
# class Capabilities(Enum):
# def by_capability(self, aborting=True, abort_code=404, *caps):
# def with_my_activities(self):
#
# Path: beavy/common/payload_property.py
# class PayloadProperty(object):
#
# def __init__(self, key, path=[], attribute='payload', force=True):
# self.key = key
# self.attribute = attribute
# self.force = force
# self.path = isinstance(path, str) and path.split('.') or path
# self.flag_modified = sa_flag_modified
#
# def _findBase(self, obj):
# base = getattr(obj, self.attribute)
# if base is None and self.force:
# base = {}
# setattr(obj, self.attribute, base)
# self.flag_modified(obj, self.attribute)
#
# items = self.path[:]
# while items:
# cur = items.pop(0)
# try:
# base = base[cur]
# except KeyError:
# base[cur] = {}
# base = base[cur]
# while items:
# cur = items.pop(0)
# base[cur] = {}
# base = base[cur]
#
# self.flag_modified(obj, self.attribute)
# break
#
# return base
#
# def __get__(self, obj, _):
# if not obj:
# # someone asked on the class
# return self
# base = self._findBase(obj)
# key = self.key
#
# return base.get(key, None)
#
# def __set__(self, obj, value):
# self._findBase(obj)[self.key] = value
# self.flag_modified(obj, self.attribute)
#
# def __delete__(self, obj):
# raise NotImplemented()
#
# Path: beavy/utils/url_converters.py
# class ModelConverter(BaseConverter):
# __OBJECTS__ = {
# 'user': User,
# 'object': Object,
# 'activity': Activity
# }
#
# def __init__(self, url_map, obj="object"):
# super(ModelConverter, self).__init__(url_map)
# # match ID or string
# self.regex = '-?\d+|\S+'
# self.cls = self.__OBJECTS__[obj]
#
# def to_python(self, value):
# cls = self.cls
# try:
# return cls.query.get_or_404(int(value))
# except ValueError:
# pass
#
# if not getattr(cls, "__LOOKUP_ATTRS__", False):
# abort(404)
#
# return cls.query.filter(or_(*[getattr(cls, key) == value
# for key in cls.__LOOKUP_ATTRS__])
# ).first_or_404()
#
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
# _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
# def injnect_manifest():
# def make_celery(app):
# def __call__(self, *args, **kwargs):
# def login_failed_redirect(self, profile, provider):
# def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
# def ensure_users():
# def print_routes():
# class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):
. Output only the next line. | nullable=False), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.