Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'VIPeR.v1.0.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
print("Using downloaded file: " + fpath)
else:
print("Downloading {} to {}".format(self.url, fpath))
urllib.request.urlretrieve(self.url, fpath)
# Extract the file
exdir = osp.join(raw_dir, 'VIPeR')
if not osp.isdir(exdir):
print("Extracting zip file")
with ZipFile(fpath) as z:
z.extractall(path=raw_dir)
# Format
images_dir = osp.join(self.root, 'images')
mkdir_if_missing(images_dir)
cameras = [sorted(glob(osp.join(exdir, 'cam_a', '*.bmp'))),
sorted(glob(osp.join(exdir, 'cam_b', '*.bmp')))]
assert len(cameras[0]) == len(cameras[1])
identities = []
for pid, (cam1, cam2) in enumerate(zip(*cameras)):
images = []
# view-0
<|code_end|>
. Use current file imports:
(import os.path as osp
import numpy as np
import hashlib
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from scipy.misc import imsave, imread
from six.moves import urllib
from zipfile import ZipFile)
and context including class names, function names, or small code snippets from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | fname = '{:08d}_{:02d}_{:04d}.jpg'.format(pid, 0, 0) |
Given the following code snippet before the placeholder: <|code_start|> url = 'http://users.soe.ucsc.edu/~manduchi/VIPeR.v1.0.zip'
md5 = '1c2d9fc1cc800332567a0da25a1ce68c'
def __init__(self, root, split_id=0, num_val=100, download=True):
super(VIPeR, self).__init__(root, split_id=split_id)
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. " +
"You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
print("Files already downloaded and verified")
return
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'VIPeR.v1.0.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
print("Using downloaded file: " + fpath)
else:
<|code_end|>
, predict the next line using imports from the current file:
import os.path as osp
import numpy as np
import hashlib
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from scipy.misc import imsave, imread
from six.moves import urllib
from zipfile import ZipFile
and context including class names, function names, and sometimes code from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | print("Downloading {} to {}".format(self.url, fpath)) |
Predict the next line after this snippet: <|code_start|>class CUHK03(Dataset):
url = 'https://docs.google.com/spreadsheet/viewform?usp=drive_web&formkey=dHRkMkFVSUFvbTJIRkRDLWRwZWpONnc6MA#gid=0'
md5 = '728939e58ad9f0ff53e521857dd8fb43'
def __init__(self, root, split_id=0, num_val=100, download=True):
super(CUHK03, self).__init__(root, split_id=split_id)
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. " +
"You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
print("Files already downloaded and verified")
return
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'cuhk03_release.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
print("Using downloaded file: " + fpath)
<|code_end|>
using the current file's imports:
import os.path as osp
import numpy as np
import h5py
import hashlib
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from scipy.misc import imsave
from zipfile import ZipFile
and any relevant context from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | else: |
Using the snippet: <|code_start|>
class CUHK03(Dataset):
url = 'https://docs.google.com/spreadsheet/viewform?usp=drive_web&formkey=dHRkMkFVSUFvbTJIRkRDLWRwZWpONnc6MA#gid=0'
md5 = '728939e58ad9f0ff53e521857dd8fb43'
def __init__(self, root, split_id=0, num_val=100, download=True):
super(CUHK03, self).__init__(root, split_id=split_id)
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. " +
"You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
print("Files already downloaded and verified")
return
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'cuhk03_release.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
<|code_end|>
, determine the next line of code. You have imports:
import os.path as osp
import numpy as np
import h5py
import hashlib
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from scipy.misc import imsave
from zipfile import ZipFile
and context (class names, function names, or code) available:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | print("Using downloaded file: " + fpath) |
Next line prediction: <|code_start|>from __future__ import absolute_import
class Logger(object):
def __init__(self, fpath=None):
self.console = sys.stdout
self.file = None
if fpath is not None:
mkdir_if_missing(os.path.dirname(fpath))
self.file = open(fpath, 'w')
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
self.close()
def write(self, msg):
<|code_end|>
. Use current file imports:
(import os
import sys
from .osutils import mkdir_if_missing)
and context including class names, function names, or small code snippets from other files:
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | self.console.write(msg) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
# 上传策略,参数规格详见
# https://developer.qiniu.com/kodo/manual/1206/put-policy
_policy_fields = set([
'callbackUrl', # 回调URL
'callbackBody', # 回调Body
'callbackHost', # 回调URL指定的Host
'callbackBodyType', # 回调Body的Content-Type
'callbackFetchKey', # 回调FetchKey模式开关
'returnUrl', # 上传端的303跳转URL
'returnBody', # 上传端简单反馈获取的Body
'endUser', # 回调时上传端标识
'saveKey', # 自定义资源名
'forceSaveKey', # saveKey的优先级设置。为 true 时,saveKey不能为空,会忽略客户端指定的key,强制使用saveKey进行文件命名。参数不设置时,默认值为false
'insertOnly', # 插入模式开关
'detectMime', # MimeType侦测开关
'mimeLimit', # MimeType限制
'fsizeLimit', # 上传文件大小限制
'fsizeMin', # 上传文件最少字节数
'keylimit', # 设置允许上传的key列表,字符串数组类型,数组长度不可超过20个,如果设置了这个字段,上传时必须提供key
'persistentOps', # 持久化处理操作
'persistentNotifyUrl', # 持久化处理结果通知URL
'persistentPipeline', # 持久化处理独享队列
'deleteAfterDays', # 文件多少天后自动删除
<|code_end|>
, predict the immediate next line with the help of imports:
import base64
import hmac
import time
from hashlib import sha1
from requests.auth import AuthBase
from .compat import urlparse, json, b
from .utils import urlsafe_base64_encode
and context (classes, functions, sometimes code) from other files:
# Path: qiniu/utils.py
# def urlsafe_base64_encode(data):
# """urlsafe的base64编码:
#
# 对提供的数据进行urlsafe的base64编码。规格参考:
# https://developer.qiniu.com/kodo/manual/1231/appendix#1
#
# Args:
# data: 待编码的数据,一般为字符串
#
# Returns:
# 编码后的字符串
# """
# ret = urlsafe_b64encode(b(data))
# return s(ret)
. Output only the next line. | 'fileType', # 文件的存储类型,0为普通存储,1为低频存储 |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
def urlencode(str):
if is_py2:
return urllib2.quote(str)
elif is_py3:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from qiniu import http
from qiniu.compat import is_py2
from qiniu.compat import is_py3
import json
import hashlib
import urllib2
import urllib.parse
and context:
# Path: qiniu/http.py
# USER_AGENT = 'QiniuPython/{0} ({1}; ) Python/{2}'.format(
# __version__, _sys_info, _python_ver)
# def __return_wrapper(resp):
# def _init():
# def _post(url, data, files, auth, headers=None):
# def _put(url, data, files, auth, headers=None):
# def _get(url, params, auth, headers=None):
# def __init__(self, token):
# def __call__(self, r):
# def _post_with_token(url, data, token):
# def _post_with_token_and_headers(url, data, token, headers):
# def _post_file(url, data, files):
# def _post_with_auth(url, data, auth):
# def _get_with_auth(url, data, auth):
# def _post_with_auth_and_headers(url, data, auth, headers):
# def _get_with_auth_and_headers(url, data, auth, headers):
# def _post_with_qiniu_mac_and_headers(url, data, auth, headers):
# def _put_with_auth(url, data, auth):
# def _put_with_token_and_headers(url, data, auth, headers):
# def _put_with_auth_and_headers(url, data, auth, headers):
# def _put_with_qiniu_mac_and_headers(url, data, auth, headers):
# def _post_with_qiniu_mac(url, data, auth):
# def _get_with_qiniu_mac(url, params, auth):
# def _get_with_qiniu_mac_and_headers(url, params, auth, headers):
# def _delete_with_qiniu_mac(url, params, auth):
# def _delete_with_qiniu_mac_and_headers(url, params, auth, headers):
# def __init__(self, response, exception=None):
# def ok(self):
# def need_retry(self):
# def connect_failed(self):
# def __str__(self):
# def __repr__(self):
# def __check_json(self, reponse):
# class _TokenAuth(AuthBase):
# class ResponseInfo(object):
which might include code, classes, or functions. Output only the next line. | return urllib.parse.quote(str) |
Given the code snippet: <|code_start|>
class TestCase_Transformations(unittest.TestCase):
def test_something(self):
t = FieldTransformation()
t.field_name = 'id'
t.new_step('lower({fld})')
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pyelt.mappings.transformations import FieldTransformation
and context (functions, classes, or occasionally code) from other files:
# Path: pyelt/mappings/transformations.py
# class FieldTransformation():
# def __init__(self, name: str = '', sql: str = '') -> None:
# self.name = name #type: str
# self.field_name = 'id' #type: str
# self.table = ''
# self.descr = '' #type: str
# self.filter = '' #type: str
# # self.type = FieldTransformationType.INLINE #type: str
# self.steps = {} #type: Dict[int, FieldTransformStep]
# if sql:
# # self.parse_sql(sql)
# step = self.new_step(sql)
#
# def get_table(self):
# return self.table
#
# def parse_sql(self, sql: str):
# pos_start = sql.find('(')
# pos_end = sql.rfind(')')
# func_name = sql[:pos_start]
# func_inner = sql[pos_start + 1:pos_end]
# step = self.new_step(func_inner)
# self.steps[step.sort_order] = step
#
# def new_step(self, sql: str) -> 'FieldTransformStep':
# step = FieldTransformStep(sql=sql)
# step.sort_order = len(self.steps) + 1
# self.steps[step.sort_order] = step
# return step
#
# def get_sql(self, alias: str='')->str:
# sql = ''
# index = 0
# steps = sorted(self.steps.values(), key = lambda x: x.sort_order)
# for step in steps:
# # step_sql = step.sql
# step_sql = step.get_sql(alias)
# step_sql = step_sql.replace(self.field_name, "{fld}")
# if (index > 0):
# if '{fld}' in step_sql:
# sql = step_sql.replace("{fld}", sql)
# else:
# sql = step_sql.replace("{step" + str(index) + "}", sql)
# else:
# sql = step_sql
# sql = sql.replace("{fld}", self.field_name)
# index += 1
# return sql
#
# def __repr__(self):
# return self.get_sql('')
. Output only the next line. | t.new_step("concat({fld}, '01')") |
Given the code snippet: <|code_start|> def __init__(self, huisnummer=''):
super().__init__()
param1 = DbFunctionParameter('huisnummer_input', 'text', huisnummer)
self.func_params.append(param1)
self.sql_body = """DECLARE
pos_split INT := 0;
huisnummer_deel TEXT := '';
huisnummer INT;
huisnummer_toevoeging TEXT;
chars CHAR[];
chr CHAR;
BEGIN
--TESTS:
--select sor_timeff.split_huisnummer('10a');
--select sor_timeff.split_huisnummer('10 a');
--select sor_timeff.split_huisnummer('10-a');
--select sor_timeff.split_huisnummer('10-1hoog');
--select sor_timeff.split_huisnummer('10');
--select sor_timeff.split_huisnummer('a');
--select sor_timeff.split_huisnummer('');
--select sor_timeff.split_huisnummer(NULL);
--select sor_timeff.split_huisnummer(' 10 a ' );
--select sor_timeff.split_huisnummer(' 10 - a ');
huisnummer_input := coalesce(huisnummer_input, '');
huisnummer_input := trim(both ' ' from huisnummer_input);
chars := regexp_split_to_array(huisnummer_input, '');
FOREACH chr IN ARRAY chars
LOOP
<|code_end|>
, generate the next line using the imports in this file:
from pyelt.datalayers.database import DbFunction, DbFunctionParameter
and context (functions, classes, or occasionally code) from other files:
# Path: pyelt/datalayers/database.py
# class DbFunction:
# def __init__(self, *args):
# self.name = camelcase_to_underscores(self.__class__.__name__)
# self.func_params = []
# for arg in args:
# self.func_params.append(arg)
# self.sql_body = ''
# self.return_type = ''
# self.schema = None
# self.lang = 'PLPGSQL'
#
# def get_complete_name(self):
# func_args = ''
# for func_param in self.func_params:
# func_args += '{} {}, '.format(func_param.name, func_param.type)
# func_args = func_args[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'args': func_args}
# return '{schema}.{name}({args})'.format(**params)
#
# def to_create_sql(self):
# func_params = ''
# for func_param in self.func_params:
# func_params += '{} {}, '.format(func_param.name, func_param.type)
# func_params = func_params[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'params': func_params, 'return_type': self.return_type, 'sql_body': self.sql_body, 'lang': self.lang}
#
# sql = """CREATE OR REPLACE FUNCTION {schema}.{name}({params})
# RETURNS {return_type}
# AS
# $BODY$
# {sql_body}
# $BODY$
# LANGUAGE {lang} VOLATILE;""".format(**params)
# return sql
#
# def get_sql(self, alias=''):
# params = self.__dict__
# fields = ''
# for param in self.func_params:
# if alias:
# fields += '{}.{},'.format(alias, param.calling_field)
# else:
# fields += '{},'.format(param.calling_field)
# fields = fields[:-1]
# params['fields'] = fields
# sql = "{schema}.{name}({fields})".format(**params)
# return sql
#
# def parse_args(self, args_str):
# args = args_str.split(',')
# self.func_params = []
# for arg in args:
# arg = arg.strip()
# arg_name = arg.split(' ')[0]
# arg_type = arg.split(' ')[1]
# self.func_params.append(DbFunctionParameter(arg_name, arg_type))
#
# def parse_sql_body(self, sql_body=''):
# start = sql_body.find('$function$') + len('$function$')
# end = sql_body.rfind('$function$')
# body = sql_body[start:end]
# self.sql_body = body
#
# def get_stripped_body(self):
# body = self.sql_body
# body = body.replace(' ', '')
# body = body.replace(' ', '')
# body = body.replace('\t', '')
# body = body.replace('\r\n', '')
# body = body.replace('\n', '')
# if not body.startswith('DECLARE'):
# body = 'DECLARE' + body
# return body
#
# class DbFunctionParameter:
# def __init__(self, name='', type='', calling_field=''):
# self.name = name
# self.type = type
# self.calling_field = calling_field
. Output only the next line. | IF chr >= '0' and chr <= '9' THEN |
Given snippet: <|code_start|> self.schema = 'sor_test_system'
class SplitHuisnummer(DbFunction):
def __init__(self, huisnummer=''):
super().__init__()
param1 = DbFunctionParameter('huisnummer_input', 'text', huisnummer)
self.func_params.append(param1)
self.sql_body = """DECLARE
pos_split INT := 0;
huisnummer_deel TEXT := '';
huisnummer INT;
huisnummer_toevoeging TEXT;
chars CHAR[];
chr CHAR;
BEGIN
--TESTS:
--select sor_timeff.split_huisnummer('10a');
--select sor_timeff.split_huisnummer('10 a');
--select sor_timeff.split_huisnummer('10-a');
--select sor_timeff.split_huisnummer('10-1hoog');
--select sor_timeff.split_huisnummer('10');
--select sor_timeff.split_huisnummer('a');
--select sor_timeff.split_huisnummer('');
--select sor_timeff.split_huisnummer(NULL);
--select sor_timeff.split_huisnummer(' 10 a ' );
--select sor_timeff.split_huisnummer(' 10 - a ');
huisnummer_input := coalesce(huisnummer_input, '');
huisnummer_input := trim(both ' ' from huisnummer_input);
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyelt.datalayers.database import DbFunction, DbFunctionParameter
and context:
# Path: pyelt/datalayers/database.py
# class DbFunction:
# def __init__(self, *args):
# self.name = camelcase_to_underscores(self.__class__.__name__)
# self.func_params = []
# for arg in args:
# self.func_params.append(arg)
# self.sql_body = ''
# self.return_type = ''
# self.schema = None
# self.lang = 'PLPGSQL'
#
# def get_complete_name(self):
# func_args = ''
# for func_param in self.func_params:
# func_args += '{} {}, '.format(func_param.name, func_param.type)
# func_args = func_args[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'args': func_args}
# return '{schema}.{name}({args})'.format(**params)
#
# def to_create_sql(self):
# func_params = ''
# for func_param in self.func_params:
# func_params += '{} {}, '.format(func_param.name, func_param.type)
# func_params = func_params[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'params': func_params, 'return_type': self.return_type, 'sql_body': self.sql_body, 'lang': self.lang}
#
# sql = """CREATE OR REPLACE FUNCTION {schema}.{name}({params})
# RETURNS {return_type}
# AS
# $BODY$
# {sql_body}
# $BODY$
# LANGUAGE {lang} VOLATILE;""".format(**params)
# return sql
#
# def get_sql(self, alias=''):
# params = self.__dict__
# fields = ''
# for param in self.func_params:
# if alias:
# fields += '{}.{},'.format(alias, param.calling_field)
# else:
# fields += '{},'.format(param.calling_field)
# fields = fields[:-1]
# params['fields'] = fields
# sql = "{schema}.{name}({fields})".format(**params)
# return sql
#
# def parse_args(self, args_str):
# args = args_str.split(',')
# self.func_params = []
# for arg in args:
# arg = arg.strip()
# arg_name = arg.split(' ')[0]
# arg_type = arg.split(' ')[1]
# self.func_params.append(DbFunctionParameter(arg_name, arg_type))
#
# def parse_sql_body(self, sql_body=''):
# start = sql_body.find('$function$') + len('$function$')
# end = sql_body.rfind('$function$')
# body = sql_body[start:end]
# self.sql_body = body
#
# def get_stripped_body(self):
# body = self.sql_body
# body = body.replace(' ', '')
# body = body.replace(' ', '')
# body = body.replace('\t', '')
# body = body.replace('\r\n', '')
# body = body.replace('\n', '')
# if not body.startswith('DECLARE'):
# body = 'DECLARE' + body
# return body
#
# class DbFunctionParameter:
# def __init__(self, name='', type='', calling_field=''):
# self.name = name
# self.type = type
# self.calling_field = calling_field
which might include code, classes, or functions. Output only the next line. | chars := regexp_split_to_array(huisnummer_input, ''); |
Given snippet: <|code_start|>
class QueryMaker():
def __init__(self, name = ''):
self.name = name
self.__elements = {}
def append(self, elm, alias = ''):
if isinstance(elm, Column):
if not alias:
alias = elm.name
else:
if not alias:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyelt.datalayers.database import *
from pyelt.datalayers.dv import *
from pyelt.mappings.transformations import FieldTransformation
and context:
# Path: pyelt/mappings/transformations.py
# class FieldTransformation():
# def __init__(self, name: str = '', sql: str = '') -> None:
# self.name = name #type: str
# self.field_name = 'id' #type: str
# self.table = ''
# self.descr = '' #type: str
# self.filter = '' #type: str
# # self.type = FieldTransformationType.INLINE #type: str
# self.steps = {} #type: Dict[int, FieldTransformStep]
# if sql:
# # self.parse_sql(sql)
# step = self.new_step(sql)
#
# def get_table(self):
# return self.table
#
# def parse_sql(self, sql: str):
# pos_start = sql.find('(')
# pos_end = sql.rfind(')')
# func_name = sql[:pos_start]
# func_inner = sql[pos_start + 1:pos_end]
# step = self.new_step(func_inner)
# self.steps[step.sort_order] = step
#
# def new_step(self, sql: str) -> 'FieldTransformStep':
# step = FieldTransformStep(sql=sql)
# step.sort_order = len(self.steps) + 1
# self.steps[step.sort_order] = step
# return step
#
# def get_sql(self, alias: str='')->str:
# sql = ''
# index = 0
# steps = sorted(self.steps.values(), key = lambda x: x.sort_order)
# for step in steps:
# # step_sql = step.sql
# step_sql = step.get_sql(alias)
# step_sql = step_sql.replace(self.field_name, "{fld}")
# if (index > 0):
# if '{fld}' in step_sql:
# sql = step_sql.replace("{fld}", sql)
# else:
# sql = step_sql.replace("{step" + str(index) + "}", sql)
# else:
# sql = step_sql
# sql = sql.replace("{fld}", self.field_name)
# index += 1
# return sql
#
# def __repr__(self):
# return self.get_sql('')
which might include code, classes, or functions. Output only the next line. | alias = elm.__dbname__ |
Using the snippet: <|code_start|>--select sor_timeff.split_huisnummer('10-1hoog');
--select sor_timeff.split_huisnummer('10');
--select sor_timeff.split_huisnummer('a');
--select sor_timeff.split_huisnummer('');
--select sor_timeff.split_huisnummer(NULL);
--select sor_timeff.split_huisnummer(' 10 a ' );
--select sor_timeff.split_huisnummer(' 10 - a ');
huisnummer_input := coalesce(huisnummer_input, '');
huisnummer_input := trim(both ' ' from huisnummer_input);
chars := regexp_split_to_array(huisnummer_input, '');
FOREACH chr IN ARRAY chars
LOOP
IF chr >= '0' and chr <= '9' THEN
huisnummer_deel := huisnummer_deel || chr;
-- RAISE NOTICE 'test%', pos_split;
ELSE
exit;
END IF;
pos_split := pos_split + 1;
END LOOP;
-- RAISE NOTICE 'split at %', pos_split;
huisnummer_toevoeging := substring(huisnummer_input from pos_split + 1);
huisnummer_toevoeging := trim(both ' ' from huisnummer_toevoeging);
huisnummer_toevoeging := trim(leading '-' from huisnummer_toevoeging);
huisnummer_toevoeging := trim(both ' ' from huisnummer_toevoeging);
IF huisnummer_deel != '' THEN
huisnummer := huisnummer_deel::integer;
<|code_end|>
, determine the next line of code. You have imports:
from pyelt.datalayers.database import DbFunction, DbFunctionParameter
and context (class names, function names, or code) available:
# Path: pyelt/datalayers/database.py
# class DbFunction:
# def __init__(self, *args):
# self.name = camelcase_to_underscores(self.__class__.__name__)
# self.func_params = []
# for arg in args:
# self.func_params.append(arg)
# self.sql_body = ''
# self.return_type = ''
# self.schema = None
# self.lang = 'PLPGSQL'
#
# def get_complete_name(self):
# func_args = ''
# for func_param in self.func_params:
# func_args += '{} {}, '.format(func_param.name, func_param.type)
# func_args = func_args[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'args': func_args}
# return '{schema}.{name}({args})'.format(**params)
#
# def to_create_sql(self):
# func_params = ''
# for func_param in self.func_params:
# func_params += '{} {}, '.format(func_param.name, func_param.type)
# func_params = func_params[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'params': func_params, 'return_type': self.return_type, 'sql_body': self.sql_body, 'lang': self.lang}
#
# sql = """CREATE OR REPLACE FUNCTION {schema}.{name}({params})
# RETURNS {return_type}
# AS
# $BODY$
# {sql_body}
# $BODY$
# LANGUAGE {lang} VOLATILE;""".format(**params)
# return sql
#
# def get_sql(self, alias=''):
# params = self.__dict__
# fields = ''
# for param in self.func_params:
# if alias:
# fields += '{}.{},'.format(alias, param.calling_field)
# else:
# fields += '{},'.format(param.calling_field)
# fields = fields[:-1]
# params['fields'] = fields
# sql = "{schema}.{name}({fields})".format(**params)
# return sql
#
# def parse_args(self, args_str):
# args = args_str.split(',')
# self.func_params = []
# for arg in args:
# arg = arg.strip()
# arg_name = arg.split(' ')[0]
# arg_type = arg.split(' ')[1]
# self.func_params.append(DbFunctionParameter(arg_name, arg_type))
#
# def parse_sql_body(self, sql_body=''):
# start = sql_body.find('$function$') + len('$function$')
# end = sql_body.rfind('$function$')
# body = sql_body[start:end]
# self.sql_body = body
#
# def get_stripped_body(self):
# body = self.sql_body
# body = body.replace(' ', '')
# body = body.replace(' ', '')
# body = body.replace('\t', '')
# body = body.replace('\r\n', '')
# body = body.replace('\n', '')
# if not body.startswith('DECLARE'):
# body = 'DECLARE' + body
# return body
#
# class DbFunctionParameter:
# def __init__(self, name='', type='', calling_field=''):
# self.name = name
# self.type = type
# self.calling_field = calling_field
. Output only the next line. | END IF; |
Given the following code snippet before the placeholder: <|code_start|> self.func_params.append(param1)
self.func_params.append(param2)
self.sql_body = """DECLARE
pos_split INT := 0;
huisnummer_deel TEXT := '';
huisnummer INT;
huisnummer_toevoeging TEXT;
chars CHAR[];
chr CHAR;
BEGIN
--TESTS:
--select sor_timeff.split_huisnummer('10a');
--select sor_timeff.split_huisnummer('10 a');
--select sor_timeff.split_huisnummer('10-a');
--select sor_timeff.split_huisnummer('10-1hoog');
--select sor_timeff.split_huisnummer('10');
--select sor_timeff.split_huisnummer('a');
--select sor_timeff.split_huisnummer('');
--select sor_timeff.split_huisnummer(NULL);
--select sor_timeff.split_huisnummer(' 10 a ' );
--select sor_timeff.split_huisnummer(' 10 - a ');
huisnummer_input := coalesce(huisnummer_input, '');
huisnummer_input := trim(both ' ' from huisnummer_input);
chars := regexp_split_to_array(huisnummer_input, '');
FOREACH chr IN ARRAY chars
LOOP
IF chr >= '0' and chr <= '9' THEN
huisnummer_deel := huisnummer_deel || chr;
<|code_end|>
, predict the next line using imports from the current file:
from pyelt.datalayers.database import DbFunction, DbFunctionParameter
and context including class names, function names, and sometimes code from other files:
# Path: pyelt/datalayers/database.py
# class DbFunction:
# def __init__(self, *args):
# self.name = camelcase_to_underscores(self.__class__.__name__)
# self.func_params = []
# for arg in args:
# self.func_params.append(arg)
# self.sql_body = ''
# self.return_type = ''
# self.schema = None
# self.lang = 'PLPGSQL'
#
# def get_complete_name(self):
# func_args = ''
# for func_param in self.func_params:
# func_args += '{} {}, '.format(func_param.name, func_param.type)
# func_args = func_args[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'args': func_args}
# return '{schema}.{name}({args})'.format(**params)
#
# def to_create_sql(self):
# func_params = ''
# for func_param in self.func_params:
# func_params += '{} {}, '.format(func_param.name, func_param.type)
# func_params = func_params[:-2]
# params = {'schema': self.schema.name, 'name': self.name, 'params': func_params, 'return_type': self.return_type, 'sql_body': self.sql_body, 'lang': self.lang}
#
# sql = """CREATE OR REPLACE FUNCTION {schema}.{name}({params})
# RETURNS {return_type}
# AS
# $BODY$
# {sql_body}
# $BODY$
# LANGUAGE {lang} VOLATILE;""".format(**params)
# return sql
#
# def get_sql(self, alias=''):
# params = self.__dict__
# fields = ''
# for param in self.func_params:
# if alias:
# fields += '{}.{},'.format(alias, param.calling_field)
# else:
# fields += '{},'.format(param.calling_field)
# fields = fields[:-1]
# params['fields'] = fields
# sql = "{schema}.{name}({fields})".format(**params)
# return sql
#
# def parse_args(self, args_str):
# args = args_str.split(',')
# self.func_params = []
# for arg in args:
# arg = arg.strip()
# arg_name = arg.split(' ')[0]
# arg_type = arg.split(' ')[1]
# self.func_params.append(DbFunctionParameter(arg_name, arg_type))
#
# def parse_sql_body(self, sql_body=''):
# start = sql_body.find('$function$') + len('$function$')
# end = sql_body.rfind('$function$')
# body = sql_body[start:end]
# self.sql_body = body
#
# def get_stripped_body(self):
# body = self.sql_body
# body = body.replace(' ', '')
# body = body.replace(' ', '')
# body = body.replace('\t', '')
# body = body.replace('\r\n', '')
# body = body.replace('\n', '')
# if not body.startswith('DECLARE'):
# body = 'DECLARE' + body
# return body
#
# class DbFunctionParameter:
# def __init__(self, name='', type='', calling_field=''):
# self.name = name
# self.type = type
# self.calling_field = calling_field
. Output only the next line. | -- RAISE NOTICE 'test%', pos_split; |
Given the code snippet: <|code_start|>
def init_test_valueset_mappings():
mappings = []
mapping = SorToValueSetMapping('patient_hstage', Valueset)
mapping.map_field("target_valueset", Valueset.valueset_naam)
mapping.map_field("target_code", Valueset.code)
mapping.map_field("target_descr", Valueset.omschrijving)
mappings.append(mapping)
return mappings
class TestCase_Mappings(unittest.TestCase):
def setUp(self):
self.pipeline = get_global_test_pipeline()
self.pipe = self.pipeline.get_or_create_pipe('test_system')
def test(self):
mappings = init_test_valueset_mappings()
valuset_mapping = mappings[0]
self.assertEqual(valuset_mapping.name, 'patient_hstage -> valueset')
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from tests.unit_tests_basic._domainmodel import Valueset
from tests.unit_tests_basic.global_test_suite import *
from pyelt.mappings.sor_to_dv_mappings import SorToValueSetMapping
and context (functions, classes, or occasionally code) from other files:
# Path: tests/unit_tests_basic/_domainmodel.py
# class Valueset(DvValueset):
# valueset_naam = Columns.TextColumn()
# code = Columns.TextColumn()
# omschrijving = Columns.TextColumn()
#
# Path: pyelt/mappings/sor_to_dv_mappings.py
# class SorToValueSetMapping(BaseTableMapping):
# def __init__(self, source: str, target: DvValueset, sor: Schema = None ) -> None:
# if isinstance(source, str) and 'SELECT' in source.upper() and ' ' in source:
# source = SorQuery(source, sor)
# elif isinstance(source, str):
# source = SorTable(source, sor)
# super().__init__(source, target)
# self.sor_table = source
# self.valueset = target
#
# def get_source_fields(self, alias: str = '')-> str:
# if not alias: alias = 'hstg'
# fields = '' # type: List[str]
# target_json_dict = OrderedDict()
# for field_map in self.field_mappings:
# if field_map.target.type == 'jsonb':
# if field_map.target.name not in target_json_dict:
# target_json_dict[field_map.target.name] = []
# target_json_dict[field_map.target.name].append(field_map)
# elif isinstance(field_map.source, ConstantValue):
# field = '{},'.format(field_map.source)
# elif isinstance(field_map.source, FieldTransformation):
# # field = '{},'.format(field_map.source.get_sql(alias))
# field = '{},'.format(field_map.source.get_sql())
# elif isinstance(field_map.source, DbFunction):
# # field = '{},'.format(field_map.source.get_sql(alias))
# field = '{},'.format(field_map.source.get_sql(alias))
# elif not alias:
# field = '{},'.format(field_map.source)
# else:
# field = '{}.{},'.format(alias, field_map.source)
# if '[]' in field_map.target.type:
# #array velden
# #eerst komma eraf halen
# field = field[:-1]
# field = "'{" + field + "}',"
# # voorkom eventuele dubbele veldnamen bij hybrid sats
# if field not in fields:
# fields += field
#
# for name, value in target_json_dict.items():
# sql_snippet = """json_build_object("""
# for field_map in value:
# sql_snippet += """'{0}', {0}, """.format(field_map.source.name)
# sql_snippet = sql_snippet[:-2] + ')::jsonb,'
# fields += sql_snippet
# fields = fields[:-1]
# return fields
#
# def get_target_fields(self) -> str:
# fields = []
# #json velden willen we helemaal als laatste omdat ze in get_source_fields ook als laatste komen te staan
# json_fields = []
# for field_map in self.field_mappings:
# field = '{}'.format(field_map.target)
# if field_map.target.type == 'jsonb':
# if field not in json_fields:
# json_fields.append(field)
# elif field not in fields:
# fields.append(field)
# return_sql = ','.join(fields)
# if json_fields:
# return_sql += "," + ','.join(json_fields)
# return return_sql
. Output only the next line. | self.assertEqual(len(valuset_mapping.field_mappings), 3) |
Predict the next line for this snippet: <|code_start|>
def init_test_valueset_mappings():
mappings = []
mapping = SorToValueSetMapping('patient_hstage', Valueset)
mapping.map_field("target_valueset", Valueset.valueset_naam)
mapping.map_field("target_code", Valueset.code)
mapping.map_field("target_descr", Valueset.omschrijving)
mappings.append(mapping)
return mappings
class TestCase_Mappings(unittest.TestCase):
def setUp(self):
self.pipeline = get_global_test_pipeline()
self.pipe = self.pipeline.get_or_create_pipe('test_system')
def test(self):
mappings = init_test_valueset_mappings()
valuset_mapping = mappings[0]
self.assertEqual(valuset_mapping.name, 'patient_hstage -> valueset')
<|code_end|>
with the help of current file imports:
import unittest
from tests.unit_tests_basic._domainmodel import Valueset
from tests.unit_tests_basic.global_test_suite import *
from pyelt.mappings.sor_to_dv_mappings import SorToValueSetMapping
and context from other files:
# Path: tests/unit_tests_basic/_domainmodel.py
# class Valueset(DvValueset):
# valueset_naam = Columns.TextColumn()
# code = Columns.TextColumn()
# omschrijving = Columns.TextColumn()
#
# Path: pyelt/mappings/sor_to_dv_mappings.py
# class SorToValueSetMapping(BaseTableMapping):
# def __init__(self, source: str, target: DvValueset, sor: Schema = None ) -> None:
# if isinstance(source, str) and 'SELECT' in source.upper() and ' ' in source:
# source = SorQuery(source, sor)
# elif isinstance(source, str):
# source = SorTable(source, sor)
# super().__init__(source, target)
# self.sor_table = source
# self.valueset = target
#
# def get_source_fields(self, alias: str = '')-> str:
# if not alias: alias = 'hstg'
# fields = '' # type: List[str]
# target_json_dict = OrderedDict()
# for field_map in self.field_mappings:
# if field_map.target.type == 'jsonb':
# if field_map.target.name not in target_json_dict:
# target_json_dict[field_map.target.name] = []
# target_json_dict[field_map.target.name].append(field_map)
# elif isinstance(field_map.source, ConstantValue):
# field = '{},'.format(field_map.source)
# elif isinstance(field_map.source, FieldTransformation):
# # field = '{},'.format(field_map.source.get_sql(alias))
# field = '{},'.format(field_map.source.get_sql())
# elif isinstance(field_map.source, DbFunction):
# # field = '{},'.format(field_map.source.get_sql(alias))
# field = '{},'.format(field_map.source.get_sql(alias))
# elif not alias:
# field = '{},'.format(field_map.source)
# else:
# field = '{}.{},'.format(alias, field_map.source)
# if '[]' in field_map.target.type:
# #array velden
# #eerst komma eraf halen
# field = field[:-1]
# field = "'{" + field + "}',"
# # voorkom eventuele dubbele veldnamen bij hybrid sats
# if field not in fields:
# fields += field
#
# for name, value in target_json_dict.items():
# sql_snippet = """json_build_object("""
# for field_map in value:
# sql_snippet += """'{0}', {0}, """.format(field_map.source.name)
# sql_snippet = sql_snippet[:-2] + ')::jsonb,'
# fields += sql_snippet
# fields = fields[:-1]
# return fields
#
# def get_target_fields(self) -> str:
# fields = []
# #json velden willen we helemaal als laatste omdat ze in get_source_fields ook als laatste komen te staan
# json_fields = []
# for field_map in self.field_mappings:
# field = '{}'.format(field_map.target)
# if field_map.target.type == 'jsonb':
# if field not in json_fields:
# json_fields.append(field)
# elif field not in fields:
# fields.append(field)
# return_sql = ','.join(fields)
# if json_fields:
# return_sql += "," + ','.join(json_fields)
# return return_sql
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(len(valuset_mapping.field_mappings), 3) |
Using the snippet: <|code_start|>
def delete_all_logs(folder):
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception as e:
print(e)
def delete_all_ddl_logs(folder):
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
<|code_end|>
, determine the next line of code. You have imports:
import os
from datetime import datetime
from main import get_root_path
and context (class names, function names, or code) available:
# Path: main.py
# def get_root_path():
# """
#
# :rtype : object
# """
# import os
# path = os.path.dirname(__file__)
# path = path.replace('\\', '/')
# path = path[0: path.rfind('/')]
# return path
. Output only the next line. | if 'DDL' in the_file: |
Using the snippet: <|code_start|>
config = {
'log_path': '/logs/',
'ddl_log_path': '/logs/ddl/',
'sql_log_path': '/logs/sql/',
'conn_dwh': 'postgresql://postgres:' + SimpleEncrypt.decode('pwd', 'wrTCrMOGw4DCtcKzwr3ClsKjwoF4e2k=')+ '@localhost:5432/dwh',
'debug': True, # Zet debug op true om een gelimiteerd aantal rijen op te halen
'datatransfer_path': '/tmp/pyelt/datatransfer', # voor linux server: datatransfer pad mag niet in /home folder zijn, want anders kan postgres er niet bij
'on_errors': 'log',
# vul 'throw' in als je wilt dat het programma stopt zodra er een error optreedt, zodat je die kunt afvangen. Kies log voor als je wilt dat de error gelogt wordt en doorgaat met de volgende stap
'datatransfer_path': 'c:/tmp/',
'data_root': '/',
'ask_confirm_on_db_changes': False
}
source_config = {
<|code_end|>
, determine the next line of code. You have imports:
from pyelt.helpers.encrypt import SimpleEncrypt
and context (class names, function names, or code) available:
# Path: pyelt/helpers/encrypt.py
# class SimpleEncrypt():
# @staticmethod
# def encode(key, clear):
# key = SimpleEncrypt.__get_key() + key
# enc = []
# for i in range(len(clear)):
# key_c = key[i % len(key)]
# enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
# enc.append(enc_c)
# # return "".join(enc)
# bytes = "".join(enc).encode('utf-8')
# b64 = base64.urlsafe_b64encode(bytes)
# return b64.decode("utf-8")
# return "".join(enc).encode('utf-8').decode('cp1251')
#
# # return str(base64.urlsafe_b64encode("".join(enc)))
#
# @staticmethod
# def decode(key, enc):
# key = SimpleEncrypt.__get_key() + key
# dec = []
# enc_bytes = enc.encode("utf-8")
# bytes = base64.urlsafe_b64decode(enc_bytes)
# enc = bytes.decode('utf-8')
# # enc = base64.urlsafe_b64decode(bytes)
# for i in range(len(enc)):
# key_c = key[i % len(key)]
# dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
# dec.append(dec_c)
# return "".join(dec)
#
# @staticmethod
# def __get_key():
# import socket
# return socket.gethostname()
. Output only the next line. | 'sor_schema': 'sor_sample', |
Given snippet: <|code_start|> # result = get_field_value_from_dv_table('landcode','zorgverlener','contactgegevens','455',['_active = True', """type = 'mobiel'"""])
sql = """select a.land from pyelt_unittests.dv.adres_sat a
inner join pyelt_unittests.dv.zorgverlener_adres_link za
on a._id = za.fk_adres_hub
inner join pyelt_unittests.dv.zorgverlener_hub z
on za.fk_zorgverlener_hub = z._id
where z.bk = '455' and za.type = 'bezoek' and a._active = True"""
result = execute_sql(sql)
result = result[0][0]
self.assertEqual(result,'Australia','ik verwachte dat deze waarde van Nederland naar Australia aangepast was')
def test06_update_dv_field_null_to_value(self):
sql = """select a.straat from pyelt_unittests.dv.adres_sat a
inner join pyelt_unittests.dv.zorgverlener_adres_link za
on a._id = za.fk_adres_hub
inner join pyelt_unittests.dv.zorgverlener_hub z
on za.fk_zorgverlener_hub = z._id
where z.bk = '448' and za.type = 'bezoek' and a._active = True"""
result = execute_sql(sql)
result = result[0][0]
self.assertEqual(result,'Dalstraat','ik verwachte dat deze waarde van Null naar Daalstraat aangepast was')
def test07_update_dv_field_value_to_null(self):
# print("test07_update_dv_field_value_to_null:")
sql = """select a._active from pyelt_unittests.dv.adres_sat a
inner join pyelt_unittests.dv.zorgverlener_adres_link za
on a._id = za.fk_adres_hub
inner join pyelt_unittests.dv.zorgverlener_hub z
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from tests.unit_tests_rob import _domain_rob
from tests.unit_tests_rob.global_test_suite import test_system_config, get_global_test_pipeline, execute_sql, init_db
from tests.unit_tests_rob.mappings_rob_hybridlinks import init_source_to_sor_mappings, init_sor_to_dv_mappings
from tests.unit_tests_rob.test05r_process import test_row_count, get_field_value_from_table, \
get_field_value_from_dv_table
from main import get_root_path
and context:
# Path: main.py
# def get_root_path():
# """
#
# :rtype : object
# """
# import os
# path = os.path.dirname(__file__)
# path = path.replace('\\', '/')
# path = path[0: path.rfind('/')]
# return path
which might include code, classes, or functions. Output only the next line. | on za.fk_zorgverlener_hub = z._id |
Given the following code snippet before the placeholder: <|code_start|> new_hub.bk = 'ajshdgashdg4'
pat_hub.save()
Patient.cls_init()
sat = Patient.Naamgegevens()
rows = sat.load()
for row in rows.values():
print(row._id, row._runid, row._revision, row.geslachtsnaam)
new_hub = pat_hub.new()
new_hub.bk = 'ajshdgashdg11'
pat_hub.save()
print(new_hub._id)
new_sat = sat.new()
new_sat.geslachtsnaam = 'Reenen5'
new_sat._id = new_hub._id
sat.save()
pat_ent = Patient()
# regel hieronder laad de hub van de entity en zet in elke regel een sat-definitie
# sat is dan nog niet geladen
# op moment dat je vraagt om de sat wordt de data van de hele in __get_attr van de entity geladen
rows = pat_ent.load()
for row in rows.values():
print(row._id, row.bk)
# na aanroep van row.naamgegevens wordt die al geladen
print(row.naamgegevens.db_status)
print(row.naamgegevens.initialen)
print(row.naamgegevens.db_status)
<|code_end|>
, predict the next line using imports from the current file:
from sample_domains.role_domain import Patient
from pipelines.clinics.clinics_configs import general_config
from pyelt.orm.dv_objects import DbSession
and context including class names, function names, and sometimes code from other files:
# Path: pyelt/orm/dv_objects.py
# class DbSession():
# _instance = None
#
# def __new__(cls, *args, **kwargs):
# """ returns cls._instance
# """
# if not cls._instance and (args or kwargs):
# # singleton implementatie
# cls._instance = super(DbSession, cls).__new__(
# cls)
# if args:
# config = args[0]
# runid = args[1]
# else:
# config = kwargs['config']
# runid = kwargs['runid']
#
# cls._instance.config = config #: pyelt_config
# cls._instance.dwh = Dwh(config)
# cls._instance.runid = runid # type: float
# return cls._instance
. Output only the next line. | print('--------') |
Continue the code snippet: <|code_start|>
def test10_dv_view_updated(self):
pass
#todo[rob]: test de hybrid-links
def test_row_count(unittest, table_name, count):
test_sql = "SELECT * FROM " + table_name
result = execute_sql(test_sql)
unittest.assertEqual(len(result), count, table_name)
def get_field_value_from_table(fieldname, table_name, sql_condition):
sql = """select {0} from {1} where {2}""".format(fieldname, table_name, sql_condition)
result = execute_sql(sql)
return result
def get_field_value_from_dv_table(fieldname, entity_name, sat_name, bk, sql_conditions_list):
if sat_name != '':
sat_name2 = '_{}'.format(sat_name)
else:
sat_name2 = ''
if sql_conditions_list == []:
sql_condition = ''
else:
sql_condition = ''
for i in sql_conditions_list:
sql_condition = sql_condition + ' AND s.{}'.format(i)
<|code_end|>
. Use current file imports:
import unittest
from tests.unit_tests_rob import _domain_rob
from tests.unit_tests_rob._domain_rob import Zorgverlener
from tests.unit_tests_rob.global_test_suite import test_system_config, get_global_test_pipeline, execute_sql, init_db
from tests.unit_tests_rob._mappings_rob import init_source_to_sor_mappings, init_sor_to_dv_mappings
from main import get_root_path
and context (classes, functions, or code) from other files:
# Path: main.py
# def get_root_path():
# """
#
# :rtype : object
# """
# import os
# path = os.path.dirname(__file__)
# path = path.replace('\\', '/')
# path = path[0: path.rfind('/')]
# return path
. Output only the next line. | sql = """select s.{1} |
Continue the code snippet: <|code_start|> self.log(sql)
start = time.time()
connection = self.engine.raw_connection()
cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(sql)
result = cursor.fetchall()
self.log('-- duur: ' + str(time.time() - start) + '; aantal rijen:' + str(cursor.rowcount))
self.log('-- =============================================================')
cursor.close()
return result
def confirm_execute(self, sql: str, log_message: str='', ask_confirm = True) -> None:
"""Vraagt de gebruiker via cmd prompt om een wijziging in de db te confirmen.
Toets j of y voor bevestiging"""
if ask_confirm:
sql_sliced = sql
if len(sql) > 50:
sql_sliced = sql[:50] + '...'
else:
sql_sliced = sql
result = input('{}\r\nWil je de volgende wijzigingen aanbrengen in de database?\r\n{}\r\n'.format(log_message.upper(), sql_sliced))
if result.strip().lower()[:1] == 'j' or result.strip().lower()[:1] == 'y':
self.execute(sql, log_message)
else:
raise Exception('afgebroken')
else:
self.execute(sql, log_message)
<|code_end|>
. Use current file imports:
from typing import Dict, List, Union, Any
from sqlalchemy import create_engine, MetaData
from sqlalchemy.engine import reflection
from sqlalchemy.sql.sqltypes import NullType
from pyelt.helpers.global_helper_functions import camelcase_to_underscores
import time
import psycopg2
import psycopg2.extras
and context (classes, functions, or code) from other files:
# Path: pyelt/helpers/global_helper_functions.py
# def camelcase_to_underscores(string):
# """# example = 'CamelCase_Example'
# # example2 = 'CamelCase_Example_AdditionalUnderscore'"""
# string = string[0].lower() + string[1:len(string)]
#
# for i in string:
# if i.isupper():
# string = string.replace(i, '_' + i)
# string = string.lower().replace('__', '_')
#
# return string
. Output only the next line. | def log(self, msg: str) -> None: |
Continue the code snippet: <|code_start|> self.file_kwargs = {}
self.csv_kwargs = {}
self.csv_kwargs['delimiter'] = self.delimiter
for k,v in kwargs.items():
if k == 'encoding':
self.file_kwargs[k] = v
if v == 'utf-8-sig':
v = 'utf8'
self.encoding = v
elif k == 'delimiter':
self.csv_kwargs[k] = v
self.delimiter = v
elif k == 'quote':
self.quote = v
self.kwargs = kwargs
def reflect(self):
# lees eerste regel
with open(self.file_name, 'r', **self.file_kwargs) as csvfile:
reader = csv.reader(csvfile, **self.csv_kwargs)
column_names = next(reader, None)
for name in column_names:
name = Column.clear_name(name)
col = Column(name.lower())
self.columns.append(col)
self.is_reflected = True
class FixedLengthFile(File):
def __init__(self, file_name, import_def):
<|code_end|>
. Use current file imports:
import csv
from pyelt.datalayers.database import Column
and context (classes, functions, or code) from other files:
# Path: pyelt/datalayers/database.py
# class Column():
# def __init__(self, name: str, type: str = 'text', tbl: 'Table' = None, default_value = '', pk = False, unique = False, indexed = False, nullable = True, fhir_name = '') -> None:
# name = name.strip()
# self.name = name.strip().lower()
# if not isinstance(type, str):
# if type == 23:
# type = 'integer'
# else:
# type = 'text'
# self.type = type.strip()
# #todo length
# self.length = ''
# self.table = tbl
# self.is_key = pk
# self.is_unique = unique
# self.is_indexed = indexed
# self.nullable = nullable
# self.default_value = default_value
# self.fhir_name = fhir_name
#
# def __str__(self) -> str:
# return self.name.lower()
#
# def __repr__(self) -> str:
# return "{} ({})".format(self.name.lower(), self.type.lower())
#
# @staticmethod
# def clear_name(name: str) -> str:
# name = name.replace('(', '').replace(')', '')
# name = name.replace('?', '')
# name = name.replace('-', '')
# name = name.replace(',', '')
# name = name.replace('.', '')
# name = name.replace(':', '')
# name = name.replace('"', '')
# name = name.replace(' ', '_')
# name = name.replace('/', '_')
# name = name.lower()
# return name
#
# def get_table(self):
# return self.table
#
# def __eq__(self, other):
# # zet om in sql
# return Condition(self.name, '=', other, table=self.table)
#
# def __ne__(self, other):
# # zet om in sql
# return Condition(self.name, '!=', other, table=self.table)
# # return Condition('({} != {})'.format(self.name,other))
#
# def __gt__(self, other):
# # zet om in sql
# return Condition(self.name, '>', other, table=self.table)
# # return Condition('({} > {})'.format(self.name,other))
#
# def __ge__(self, other):
# # zet om in sql
# return Condition(self.name, '>=', other, table=self.table)
# # return Condition('({} >= {})'.format(self.name,other))
#
# def __lt__(self, other):
# # zet om in sql
# return Condition(self.name, '<', other, table=self.table)
# # return Condition('({} < {})'.format(self.name,other))
#
# def __le__(self, other):
# # zet om in sql
# return Condition(self.name, '<=', other, table=self.table)
# # return Condition('({} <= {})'.format(self.name,other))
#
# def is_in(self, item):
# return Condition(self.name, 'in', item, table=self.table)
#
# def between(self, item1, item2):
# item = '{} AND {}'.format(item1, item2)
# return Condition(self.name, 'between', item, table=self.table)
#
# def join(self, item):
# sql = self.name + '||' + item.name
# if isinstance(item, (list, tuple)):
# sql = self.name + '||' + '||'.join(item)
# return SqlSnippet(sql, table=self.table)
. Output only the next line. | super().__init__(file_name ) |
Given the code snippet: <|code_start|>
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^login/', login, name='login'),
url(r'^logout/', logout, {'next_page': '/'}, name='logout'),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib.auth.views import logout
from testproject.views import login
and context (functions, classes, or occasionally code) from other files:
# Path: testproject/views.py
# def login(request):
# try:
# user = User.objects.get()
# except User.DoesNotExist:
# messages.error(request, 'User not found!')
# else:
# user.backend = 'django.contrib.auth.backends.ModelBackend'
# user = auth.login(request, user)
# return redirect(reverse('fpr_index'))
. Output only the next line. | url(r'^', include('fpr.urls')), |
Here is a snippet: <|code_start|># Django core, alphabetical
# External dependencies, alphabetical
# This project, alphabetical
# ########## FORMATS ############
class FormatForm(forms.ModelForm):
group = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'form-control'}),
choices=fprmodels.FormatGroup.objects.all()
)
def __init__(self, *args, **kwargs):
super(FormatForm, self).__init__(*args, **kwargs)
# add 'create' option to the FormatGroup dropdown
choices = [(f.uuid, f.description) for f in fprmodels.FormatGroup.objects.all()]
choices.insert(0, ('', '---------'))
choices.append(('new', _('Create New')))
self.fields['group'].choices = choices
if hasattr(self.instance, 'group') and self.instance.group:
self.fields['group'].initial = self.instance.group.uuid
# add Bootstrap class to description field
self.fields['description'].widget.attrs['class'] = 'form-control'
class Meta:
model = fprmodels.Format
<|code_end|>
. Write the next line using the current file imports:
from django import forms
from django.utils.translation import ugettext_lazy as _
from fpr import models as fprmodels
and context from other files:
# Path: fpr/models.py
# class Enabled(models.Manager):
# class VersionedModel(models.Model):
# class Meta:
# class FormatManager(models.Manager):
# class Format(models.Model):
# class Meta:
# class FormatGroup(models.Model):
# class Meta:
# class FormatVersion(VersionedModel, models.Model):
# class Meta:
# class IDCommand(VersionedModel, models.Model):
# class Meta:
# class IDRule(VersionedModel, models.Model):
# class Meta:
# class IDTool(models.Model):
# class Meta:
# class FPRule(VersionedModel, models.Model):
# class Meta:
# class FPCommand(VersionedModel, models.Model):
# class Meta:
# class FPTool(models.Model):
# class Meta:
# class Agent(models.Model):
# class Meta:
# class CommandType(models.Model):
# class Meta:
# class Command(models.Model):
# class Meta:
# class CommandsSupportedBy(models.Model):
# class Meta:
# class FileIDType(models.Model):
# class Meta:
# class FileID(models.Model):
# class Meta:
# class CommandClassification(models.Model):
# class Meta:
# class CommandRelationship(models.Model):
# class Meta:
# class FileIDsBySingleID(models.Model):
# class Meta:
# def get_queryset(self):
# def get_query_set(self):
# def save(self, replacing=None, *args, **kwargs):
# def get_full_list(self):
# def __unicode__(self):
# def __unicode__(self):
# def validate_unique(self, *args, **kwargs):
# def __unicode__(self):
# def __unicode__(self):
# def save(self, *args, **kwargs):
# def validate_unique(self, *args, **kwargs):
# def __unicode__(self):
# def long_name(self):
# def __unicode__(self):
# def _slug(self):
# def __unicode__(self):
# def long_name(self):
# def __unicode__(self):
# def __unicode__(self):
# def _slug(self):
# def __unicode__(self):
# CONFIG_CHOICES = (
# ('PUID', _('PUID')),
# ('MIME', _('MIME type')),
# ('ext', _('File extension'))
# )
# SCRIPT_TYPE_CHOICES = (
# ('bashScript', _('Bash script')),
# ('pythonScript', _('Python script')),
# ('command', _('Command line')),
# ('as_is', _('No shebang needed'))
# )
# ACCESS = 'access'
# CHARACTERIZATION = 'characterization'
# EXTRACTION = 'extract'
# PRESERVATION = 'preservation'
# THUMBNAIL = 'thumbnail'
# TRANSCRIPTION = 'transcription'
# VALIDATION = 'validation'
# POLICY = 'policy_check'
# DEFAULT_ACCESS = 'default_access'
# DEFAULT_CHARACTERIZATION = 'default_characterization'
# DEFAULT_THUMBNAIL = 'default_thumbnail'
# USAGES = (ACCESS, CHARACTERIZATION, EXTRACTION, PRESERVATION, THUMBNAIL,
# TRANSCRIPTION, VALIDATION, POLICY, DEFAULT_ACCESS,
# DEFAULT_CHARACTERIZATION, DEFAULT_THUMBNAIL)
# DISPLAY_CHOICES = (
# (ACCESS, _('Access')),
# (CHARACTERIZATION, _('Characterization')),
# (EXTRACTION, _('Extract')),
# (PRESERVATION, _('Preservation')),
# (THUMBNAIL, _('Thumbnail')),
# (TRANSCRIPTION, _('Transcription')),
# (VALIDATION, _('Validation')),
# (POLICY, _('Validation against a policy')),
# )
# HIDDEN_CHOICES = (
# (DEFAULT_ACCESS, _('Default access')),
# (DEFAULT_CHARACTERIZATION, _('Default characterization')),
# (DEFAULT_THUMBNAIL, _('Default thumbnail')),
# )
# USAGE_MAP = {
# 'normalization': (DEFAULT_ACCESS, ACCESS, PRESERVATION, THUMBNAIL),
# 'characterization': (CHARACTERIZATION, DEFAULT_CHARACTERIZATION),
# 'extraction': (EXTRACTION,),
# 'validation': (VALIDATION, POLICY)
# }
# PURPOSE_CHOICES = DISPLAY_CHOICES + HIDDEN_CHOICES
# SCRIPT_TYPE_CHOICES = (
# ('bashScript', _('Bash script')),
# ('pythonScript', _('Python script')),
# ('command', _('Command line')),
# ('as_is', _('No shebang needed'))
# )
# COMMAND_USAGE_CHOICES = (
# ('characterization', _('Characterization')),
# ('event_detail', _('Event Detail')),
# ('extraction', _('Extraction')),
# ('normalization', _('Normalization')),
# ('transcription', _('Transcription')),
# ('validation', _('Validation')),
# ('verification', _('Verification')),
# )
, which may include functions, classes, or code. Output only the next line. | fields = ('description',) |
Next line prediction: <|code_start|>
UUID_REGEX = r'[\w]{8}(-[\w]{4}){3}-[\w]{12}'
urlpatterns = [
url(r'^$', views.home, name='fpr_index'),
url(r'^(?P<category>format|formatgroup|idrule|idcommand|fprule|fpcommand)/(?P<uuid>' + UUID_REGEX + ')/toggle_enabled/$', views.toggle_enabled,
name='toggle_enabled'),
# Formats
url(r'^format/$', views.format_list,
name='format_list'),
url(r'^format/create/$', views.format_edit,
name='format_create'),
url(r'^format/(?P<slug>[-\w]+)/$', views.format_detail,
name='format_detail'),
url(r'^format/(?P<slug>[-\w]+)/edit/$', views.format_edit,
name='format_edit'),
# Format Versions
url(r'^format/(?P<format_slug>[-\w]+)/create/$', views.formatversion_edit,
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from fpr import views)
and context including class names, function names, or small code snippets from other files:
# Path: fpr/views.py
# CLASS_CATEGORY_MAP = {
# 'format': fprmodels.Format,
# 'formatgroup': fprmodels.FormatGroup,
# 'idrule': fprmodels.IDRule,
# 'idcommand': fprmodels.IDCommand,
# 'fprule': fprmodels.FPRule,
# 'fpcommand': fprmodels.FPCommand,
# }
# def context(variables):
# def home(request):
# def toggle_enabled(request, category, uuid):
# def format_list(request):
# def format_detail(request, slug):
# def format_edit(request, slug=None):
# def formatversion_detail(request, format_slug, slug=None):
# def formatversion_edit(request, format_slug, slug=None):
# def formatversion_delete(request, format_slug, slug):
# def formatgroup_list(request):
# def formatgroup_edit(request, slug=None):
# def formatgroup_delete(request, slug):
# def idtool_list(request):
# def idtool_detail(request, slug):
# def idtool_edit(request, slug=None):
# def idrule_list(request):
# def idrule_detail(request, uuid=None):
# def idrule_edit(request, uuid=None):
# def idrule_delete(request, uuid):
# def idcommand_list(request):
# def idcommand_detail(request, uuid):
# def idcommand_edit(request, uuid=None):
# def idcommand_delete(request, uuid):
# def fprule_list(request, usage=None):
# def fprule_detail(request, uuid):
# def fprule_edit(request, uuid=None):
# def fprule_delete(request, uuid):
# def fptool_list(request):
# def fptool_detail(request, slug):
# def fptool_edit(request, slug=None):
# def fpcommand_list(request, usage=None):
# def fpcommand_detail(request, uuid):
# def fpcommand_edit(request, uuid=None):
# def fpcommand_delete(request, uuid):
# def revision_list(request, entity_name, uuid):
# def _augment_revisions_with_detail_url(request, entity_name, model, revisions):
. Output only the next line. | name='formatversion_create'), |
Predict the next line for this snippet: <|code_start|> def error_code(self):
try:
return "resp %d" % int(self.err)
except ValueError:
return self.err
def process_resp(resp, datatype):
if resp is None:
if datatype == 'boolean':
return False
if datatype == 'int':
return 0
if datatype == 'float_structure':
return { 'ok': False }
if datatype == 'string':
return ""
return None
if datatype == 'float_structure':
# resp is first an int representing status
# then the float
resps = resp.split()
resp = { 'ok': int(resps[0]) >= 0 }
try:
resp['value'] = float(resps[1])
except IndexError:
resp['ok'] = False
elif datatype == 'string':
# resp is a simple string, just pass it direcly
<|code_end|>
with the help of current file imports:
from mod.mod_protocol import CMD_ARGS
and context from other files:
# Path: mod/mod_protocol.py
# CMD_ARGS = {
# 'ALL': {
# 'pi': [],
# 'say': [str,],
# 'l': [int,int,int,int,],
# 'displ_bright': [int],
# 'glcd_text': [int,int,int,str],
# 'glcd_dialog': [str],
# 'glcd_draw': [int,int,int,str],
# 'uc': [],
# 'ud': [],
# 'a': [int,str,int,str,float,float,float,int,int,],
# 'd': [int,],
# 'g': [int],
# 's': [int,float],
# 'ncp': [int,int,int],
# 'is': [int,int,int,int,int,str,str,],
# 'b': [int,int],
# 'bn': [str,],
# 'bd': [int],
# 'ba': [int,int,str,],
# 'br': [int,int,int],
# 'p': [int,int,int],
# 'pn': [str,],
# 'pb': [int,str],
# 'pr': [],
# 'ps': [],
# 'psa': [str,],
# 'pcl': [],
# 'pbd': [int,int],
# 'sr': [int,int],
# 'ssg': [int,int],
# 'sn': [int,str,],
# 'ssl': [int],
# 'sss': [],
# 'ssa': [str,],
# 'ssd': [int],
# 'ts': [float,str,int],
# 'tn': [],
# 'tf': [],
# 'ti': [int],
# 'restore': [],
# 'r': [int,],
# 'c': [int,int,],
# 'upr': [int],
# 'ups': [int],
# 'lp': [int],
# 'reset_eeprom': [],
# 'screenshot': [int,str],
# 'enc_clicked': [int],
# 'enc_left': [int],
# 'enc_right': [int],
# 'button_clicked': [int],
# 'pot_call_check': [int],
# 'pot_call_ok': [int],
# 'control_skip_enable': [],
# 'control_bad_skip': [],
# 'save_pot_cal': [int,int],
# 'sys_gio': [int,int,float],
# 'sys_ghp': [float],
# 'sys_ngc': [int],
# 'sys_ngt': [int],
# 'sys_ngd': [int],
# 'sys_cmm': [int],
# 'sys_cmr': [int],
# 'sys_pbg': [int],
# 'sys_ams': [],
# 'sys_bts': [],
# 'sys_btd': [],
# 'sys_ctl': [str],
# 'sys_ver': [str],
# 'sys_ser': [],
# 'sys_usb': [int],
# 'sys_mnr': [int],
# 'sys_rbt': [],
# 'sys_led': [int,int,],
# 'sys_nam': [int,str],
# 'sys_uni': [int,str],
# 'sys_val': [int,str],
# 'sys_ind': [int,float],
# 'sys_pch': [int],
# 'sys_spc': [int],
# },
# 'DUO': {
# 'boot': [int,int,str,],
# 'fn': [int],
# 'bc': [int,int],
# 'n': [int],
# 'si': [int,int,int],
# 'ncp': [int,int], # TODO
# },
# 'DUOX': {
# 'boot': [int,int,str,],
# 'ss': [int],
# 'sl': [int],
# 'sc': [],
# 'pa': [int,int,int,int,int,int],
# 's_contrast': [int,int],
# 'exp_overcurrent': [],
# },
# 'DWARF': {
# 'cs': [int,int],
# 'pa': [int,int,int,int,int,int,int,int],
# },
# }
, which may contain function names, class names, or code. Output only the next line. | pass |
Given the code snippet: <|code_start|> device_capture.append({
'symbol': 'midi_loopback',
'img': midi_input_img,
'connected_img': midi_input_connected,
'type': 'midi',
})
for ix in range(0, pb['hardware']['cv_outs']):
device_playback.append({
'symbol': 'cv_playback_{0}'.format(ix + 1),
'img': cv_input_img,
'connected_img': cv_input_connected,
'type': 'cv',
})
# create plugins
plugins = pb['plugins']
plugins = [p for p in plugins if p['uri'] != 'http://drobilla.net/ns/ingen#GraphPrototype']
plugin_map = {}
for p in plugins:
# read plugin data
data = get_plugin_info(p['uri'])
p['data'] = data
# read plugin image
gui = get_plugin_gui(p['uri'])
screenshot_path = gui.get('screenshot', None)
if screenshot_path is not None and os.path.isfile(screenshot_path):
try:
pimg = Image.open(screenshot_path).convert('RGBA')
except:
<|code_end|>
, generate the next line using the imports in this file:
import argparse
import base64
import json
import os
from enum import Enum
from PIL import Image
from modtools.utils import (
init as lv2_init,
cleanup as lv2_cleanup,
get_pedalboard_info,
get_plugin_info,
get_plugin_gui,
set_cpu_affinity,
)
from aggdraw import Draw, Pen, Symbol
and context (functions, classes, or occasionally code) from other files:
# Path: modtools/utils.py
# def init():
# utils.init()
#
# def cleanup():
# utils.cleanup()
#
# def get_pedalboard_info(bundle):
# info = utils.get_pedalboard_info(bundle.encode("utf-8"))
# if not info:
# raise Exception
# return structToDict(info.contents)
#
# def get_plugin_info(uri):
# info = utils.get_plugin_info(uri.encode("utf-8"))
# if not info:
# raise Exception
# return structToDict(info.contents)
#
# def get_plugin_gui(uri):
# info = utils.get_plugin_gui(uri.encode("utf-8"))
# if not info:
# raise Exception
# return structToDict(info.contents)
#
# def set_cpu_affinity(cpu):
# utils.set_cpu_affinity(cpu)
. Output only the next line. | screenshot_path = None |
Here is a snippet: <|code_start|>
def get_uid():
if DEVICE_UID is None:
raise Exception('Missing device uid')
if os.path.isfile(DEVICE_UID):
with open(DEVICE_UID, 'r') as fh:
return fh.read().strip()
return DEVICE_UID
def get_tag():
if DEVICE_TAG is None:
raise Exception('Missing device tag')
if os.path.isfile(DEVICE_TAG):
with open(DEVICE_TAG, 'r') as fh:
<|code_end|>
. Write the next line using the current file imports:
import os
from mod.settings import API_KEY, DEVICE_KEY, DEVICE_TAG, DEVICE_UID, IMAGE_VERSION
and context from other files:
# Path: mod/settings.py
# API_KEY = os.environ.pop('MOD_API_KEY', None)
#
# DEVICE_KEY = os.environ.pop('MOD_DEVICE_KEY', None)
#
# DEVICE_TAG = os.environ.pop('MOD_DEVICE_TAG', None)
#
# DEVICE_UID = os.environ.pop('MOD_DEVICE_UID', None)
#
# IMAGE_VERSION = fh.read().strip() or None
, which may include functions, classes, or code. Output only the next line. | return fh.read().strip() |
Using the snippet: <|code_start|>
def get_uid():
if DEVICE_UID is None:
raise Exception('Missing device uid')
if os.path.isfile(DEVICE_UID):
with open(DEVICE_UID, 'r') as fh:
return fh.read().strip()
return DEVICE_UID
def get_tag():
if DEVICE_TAG is None:
raise Exception('Missing device tag')
if os.path.isfile(DEVICE_TAG):
with open(DEVICE_TAG, 'r') as fh:
return fh.read().strip()
return DEVICE_TAG
def get_device_key():
if DEVICE_KEY is None:
raise Exception('Missing device key')
if os.path.isfile(DEVICE_KEY):
with open(DEVICE_KEY, 'r') as fh:
return fh.read().strip()
return DEVICE_KEY
def get_server_key():
if API_KEY is None:
<|code_end|>
, determine the next line of code. You have imports:
import os
from mod.settings import API_KEY, DEVICE_KEY, DEVICE_TAG, DEVICE_UID, IMAGE_VERSION
and context (class names, function names, or code) available:
# Path: mod/settings.py
# API_KEY = os.environ.pop('MOD_API_KEY', None)
#
# DEVICE_KEY = os.environ.pop('MOD_DEVICE_KEY', None)
#
# DEVICE_TAG = os.environ.pop('MOD_DEVICE_TAG', None)
#
# DEVICE_UID = os.environ.pop('MOD_DEVICE_UID', None)
#
# IMAGE_VERSION = fh.read().strip() or None
. Output only the next line. | raise Exception('Missing API key') |
Based on the snippet: <|code_start|>
def get_uid():
if DEVICE_UID is None:
raise Exception('Missing device uid')
if os.path.isfile(DEVICE_UID):
with open(DEVICE_UID, 'r') as fh:
return fh.read().strip()
return DEVICE_UID
def get_tag():
if DEVICE_TAG is None:
raise Exception('Missing device tag')
if os.path.isfile(DEVICE_TAG):
with open(DEVICE_TAG, 'r') as fh:
return fh.read().strip()
return DEVICE_TAG
def get_device_key():
if DEVICE_KEY is None:
raise Exception('Missing device key')
if os.path.isfile(DEVICE_KEY):
with open(DEVICE_KEY, 'r') as fh:
return fh.read().strip()
return DEVICE_KEY
def get_server_key():
if API_KEY is None:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from mod.settings import API_KEY, DEVICE_KEY, DEVICE_TAG, DEVICE_UID, IMAGE_VERSION
and context (classes, functions, sometimes code) from other files:
# Path: mod/settings.py
# API_KEY = os.environ.pop('MOD_API_KEY', None)
#
# DEVICE_KEY = os.environ.pop('MOD_DEVICE_KEY', None)
#
# DEVICE_TAG = os.environ.pop('MOD_DEVICE_TAG', None)
#
# DEVICE_UID = os.environ.pop('MOD_DEVICE_UID', None)
#
# IMAGE_VERSION = fh.read().strip() or None
. Output only the next line. | raise Exception('Missing API key') |
Given the following code snippet before the placeholder: <|code_start|> return fh.read().strip()
return DEVICE_UID
def get_tag():
if DEVICE_TAG is None:
raise Exception('Missing device tag')
if os.path.isfile(DEVICE_TAG):
with open(DEVICE_TAG, 'r') as fh:
return fh.read().strip()
return DEVICE_TAG
def get_device_key():
if DEVICE_KEY is None:
raise Exception('Missing device key')
if os.path.isfile(DEVICE_KEY):
with open(DEVICE_KEY, 'r') as fh:
return fh.read().strip()
return DEVICE_KEY
def get_server_key():
if API_KEY is None:
raise Exception('Missing API key')
if os.path.isfile(API_KEY):
with open(API_KEY, 'r') as fh:
return fh.read().strip()
return API_KEY
def get_image_version():
if IMAGE_VERSION is not None:
return IMAGE_VERSION
<|code_end|>
, predict the next line using imports from the current file:
import os
from mod.settings import API_KEY, DEVICE_KEY, DEVICE_TAG, DEVICE_UID, IMAGE_VERSION
and context including class names, function names, and sometimes code from other files:
# Path: mod/settings.py
# API_KEY = os.environ.pop('MOD_API_KEY', None)
#
# DEVICE_KEY = os.environ.pop('MOD_DEVICE_KEY', None)
#
# DEVICE_TAG = os.environ.pop('MOD_DEVICE_TAG', None)
#
# DEVICE_UID = os.environ.pop('MOD_DEVICE_UID', None)
#
# IMAGE_VERSION = fh.read().strip() or None
. Output only the next line. | return 'none' |
Given the following code snippet before the placeholder: <|code_start|>#
# 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 BytesCanUplinkConverterTests(unittest.TestCase):
def setUp(self):
self.converter = BytesCanUplinkConverter()
def _has_no_data(self, data):
return bool(data is None or not data.get("attributes", []) and not data.get("telemetry", []))
def test_wrong_type(self):
can_data = [0, 1, 0, 0, 0]
configs = [{
"key": "var",
"is_ts": True,
"type": "wrong_type"
}]
tb_data = self.converter.convert(configs, can_data)
self.assertTrue(self._has_no_data(tb_data))
def test_bool_true(self):
can_data = [0, 1, 0, 0, 0]
<|code_end|>
, predict the next line using imports from the current file:
import _struct
import unittest
from math import isclose
from random import randint, uniform, choice
from string import ascii_lowercase
from thingsboard_gateway.connectors.can.bytes_can_uplink_converter import BytesCanUplinkConverter
and context including class names, function names, and sometimes code from other files:
# Path: thingsboard_gateway/connectors/can/bytes_can_uplink_converter.py
# class BytesCanUplinkConverter(CanConverter):
# def convert(self, configs, can_data):
# result = {"attributes": {},
# "telemetry": {}}
#
# for config in configs:
# try:
# tb_key = config["key"]
# tb_item = "telemetry" if config["is_ts"] else "attributes"
#
# data_length = config["length"] if config["length"] != -1 else len(can_data) - config["start"]
#
# # The 'value' variable is used in eval
# if config["type"][0] == "b":
# value = bool(can_data[config["start"]])
# elif config["type"][0] == "i" or config["type"][0] == "l":
# value = int.from_bytes(can_data[config["start"]:config["start"] + data_length],
# config["byteorder"],
# signed=config["signed"])
# elif config["type"][0] == "f" or config["type"][0] == "d":
# fmt = ">" + config["type"][0] if config["byteorder"][0] == "b" else "<" + config["type"][0]
# value = struct.unpack_from(fmt,
# bytes(can_data[config["start"]:config["start"] + data_length]))[0]
# elif config["type"][0] == "s":
# value = can_data[config["start"]:config["start"] + data_length].decode(config["encoding"])
# elif config["type"][0] == "r":
# value = ""
# for hex_byte in can_data[config["start"]:config["start"] + data_length]:
# value += "%02x" % hex_byte
# else:
# log.error("Failed to convert CAN data to TB %s '%s': unknown data type '%s'",
# "time series key" if config["is_ts"] else "attribute", tb_key, config["type"])
# continue
#
# if config.get("expression", ""):
# result[tb_item][tb_key] = eval(config["expression"],
# {"__builtins__": {}} if config["strictEval"] else globals(),
# {"value": value, "can_data": can_data})
# else:
# result[tb_item][tb_key] = value
# except Exception as e:
# log.error("Failed to convert CAN data to TB %s '%s': %s",
# "time series key" if config["is_ts"] else "attribute", tb_key, str(e))
# continue
# return result
. Output only the next line. | configs = [{ |
Given the code snippet: <|code_start|> self.__config_dir = config_dir
BackwardCompatibilityAdapter.CONFIG_PATH = self.__config_dir
self.__keys = ['host', 'port', 'type', 'method', 'timeout', 'byteOrder', 'wordOrder', 'retries', 'retryOnEmpty',
'retryOnInvalid', 'baudrate']
@staticmethod
def __save_json_config_file(config):
with open(
f'{BackwardCompatibilityAdapter.CONFIG_PATH}modbus_new_{BackwardCompatibilityAdapter.config_files_count}.json',
'w') as file:
file.writelines(dumps(config, sort_keys=False, indent=' ', separators=(',', ': ')))
BackwardCompatibilityAdapter.config_files_count += 1
def convert(self):
if not self.__config.get('server'):
return self.__config
log.warning(
'You are using old configuration structure for Modbus connector. It will be DEPRECATED in the future '
'version! New config file "modbus_new.json" was generated in %s folder. Please, use it.', self.CONFIG_PATH)
log.warning('You have to manually connect the new generated config file to tb_gateway.yaml!')
slaves = []
for device in self.__config['server'].get('devices', []):
slave = {**device}
for key in self.__keys:
if not device.get(key):
slave[key] = self.__config['server'].get(key)
<|code_end|>
, generate the next line using the imports in this file:
from simplejson import dumps
from thingsboard_gateway.connectors.connector import log
and context (functions, classes, or occasionally code) from other files:
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
. Output only the next line. | slave['pollPeriod'] = slave['timeseriesPollPeriod'] |
Next line prediction: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 BytesSocketUplinkConverter(SocketUplinkConverter):
def __init__(self, config):
self.__config = config
self.dict_result = {
"deviceName": config['deviceName'],
"deviceType": config['deviceType']
}
def convert(self, config, data):
if data is None:
return {}
<|code_end|>
. Use current file imports:
(from thingsboard_gateway.connectors.socket.socket_uplink_converter import SocketUplinkConverter, log)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/socket/socket_uplink_converter.py
# class SocketUplinkConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | try: |
Next line prediction: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 BytesSocketUplinkConverter(SocketUplinkConverter):
def __init__(self, config):
self.__config = config
self.dict_result = {
"deviceName": config['deviceName'],
"deviceType": config['deviceType']
}
def convert(self, config, data):
if data is None:
return {}
try:
<|code_end|>
. Use current file imports:
(from thingsboard_gateway.connectors.socket.socket_uplink_converter import SocketUplinkConverter, log)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/socket/socket_uplink_converter.py
# class SocketUplinkConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | self.dict_result["telemetry"] = [] |
Here is a snippet: <|code_start|> self.__connector.add_device(data_to_connector)
elif iocb.ioError:
log.exception(iocb.ioError)
@staticmethod
def form_iocb(device, config=None, request_type="readProperty"):
config = config if config is not None else device
address = device["address"] if isinstance(device["address"], Address) else Address(device["address"])
object_id = ObjectIdentifier(config["objectId"])
property_id = config.get("propertyId")
value = config.get("propertyValue")
property_index = config.get("propertyIndex")
priority = config.get("priority")
vendor = device.get("vendor", config.get("vendorId", 0))
request = None
iocb = None
if request_type == "readProperty":
try:
request = ReadPropertyRequest(
objectIdentifier=object_id,
propertyIdentifier=property_id
)
request.pduDestination = address
if property_index is not None:
request.propertyArrayIndex = int(property_index)
iocb = IOCB(request)
except Exception as e:
log.exception(e)
elif request_type == "writeProperty":
datatype = get_datatype(object_id.value[0], property_id, vendor)
<|code_end|>
. Write the next line using the current file imports:
from bacpypes.apdu import APDU, IAmRequest, ReadPropertyRequest, SimpleAckPDU, WhoIsRequest, WritePropertyRequest
from bacpypes.app import BIPSimpleApplication
from bacpypes.constructeddata import Any
from bacpypes.core import deferred
from bacpypes.iocb import IOCB
from bacpypes.object import get_datatype
from bacpypes.pdu import Address, GlobalBroadcast
from bacpypes.primitivedata import Null, ObjectIdentifier, Atomic, Integer, Real, Unsigned
from thingsboard_gateway.connectors.bacnet.bacnet_utilities.tb_gateway_bacnet_device import TBBACnetDevice
from thingsboard_gateway.connectors.connector import log
and context from other files:
# Path: thingsboard_gateway/connectors/bacnet/bacnet_utilities/tb_gateway_bacnet_device.py
# class TBBACnetDevice(LocalDeviceObject):
# def __init__(self, configuration):
# assert configuration is not None
# super().__init__(**configuration)
#
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
, which may include functions, classes, or code. Output only the next line. | if (isinstance(value, str) and value.lower() == 'null') or value is None: |
Next line prediction: <|code_start|>
except Exception as e:
log.exception(e)
def indication(self, apdu: APDU):
if isinstance(apdu, IAmRequest):
log.debug("Received IAmRequest from device with ID: %i and address %s:%i",
apdu.iAmDeviceIdentifier[1],
apdu.pduSource.addrTuple[0],
apdu.pduSource.addrTuple[1]
)
log.debug(apdu.pduSource)
request = ReadPropertyRequest(
destination=apdu.pduSource,
objectIdentifier=apdu.iAmDeviceIdentifier,
propertyIdentifier='objectName',
)
iocb = IOCB(request)
deferred(self.request_io, iocb)
iocb.add_callback(self.__iam_cb, vendor_id=apdu.vendorID)
self.requests_in_progress.update({iocb: {"callback": self.__iam_cb}})
def do_read_property(self, device, mapping_type=None, config=None, callback=None):
try:
iocb = device if isinstance(device, IOCB) else self.form_iocb(device, config, "readProperty")
deferred(self.request_io, iocb)
self.requests_in_progress.update({iocb: {"callback": callback,
"device": device,
"mapping_type": mapping_type,
"config": config}})
<|code_end|>
. Use current file imports:
(from bacpypes.apdu import APDU, IAmRequest, ReadPropertyRequest, SimpleAckPDU, WhoIsRequest, WritePropertyRequest
from bacpypes.app import BIPSimpleApplication
from bacpypes.constructeddata import Any
from bacpypes.core import deferred
from bacpypes.iocb import IOCB
from bacpypes.object import get_datatype
from bacpypes.pdu import Address, GlobalBroadcast
from bacpypes.primitivedata import Null, ObjectIdentifier, Atomic, Integer, Real, Unsigned
from thingsboard_gateway.connectors.bacnet.bacnet_utilities.tb_gateway_bacnet_device import TBBACnetDevice
from thingsboard_gateway.connectors.connector import log)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/bacnet/bacnet_utilities/tb_gateway_bacnet_device.py
# class TBBACnetDevice(LocalDeviceObject):
# def __init__(self, configuration):
# assert configuration is not None
# super().__init__(**configuration)
#
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
. Output only the next line. | iocb.add_callback(self.__general_cb) |
Given snippet: <|code_start|># Copyright 2020. ThingsBoard
#
# 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 BytesCanDownlinkConverter(CanConverter):
def convert(self, config, data):
try:
if config.get("dataInHex", ""):
return list(bytearray.fromhex(config["dataInHex"]))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import struct
from thingsboard_gateway.connectors.can.can_converter import CanConverter
from thingsboard_gateway.connectors.converter import log
and context:
# Path: thingsboard_gateway/connectors/can/can_converter.py
# class CanConverter(ABC):
# @abstractmethod
# def convert(self, config, data):
# pass
#
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
which might include code, classes, or functions. Output only the next line. | if not isinstance(data, dict) or not data: |
Predict the next line for this snippet: <|code_start|> def convert(self, config, data):
try:
if config.get("dataInHex", ""):
return list(bytearray.fromhex(config["dataInHex"]))
if not isinstance(data, dict) or not data:
log.error("Failed to convert TB data to CAN payload: data is empty or not a dictionary")
return
if data.get("dataInHex", ""):
return list(bytearray.fromhex(data["dataInHex"]))
if config.get("dataExpression", ""):
value = eval(config["dataExpression"],
{"__builtins__": {}} if config.get("strictEval", True) else globals(),
data)
elif "value" in data:
value = data["value"]
else:
log.error("Failed to convert TB data to CAN payload: no `value` or `dataExpression` property")
return
can_data = []
if config.get("dataBefore", ""):
can_data.extend(bytearray.fromhex(config["dataBefore"]))
if isinstance(value, bool):
can_data.extend([int(value)])
elif isinstance(value, int) or isinstance(value, float):
<|code_end|>
with the help of current file imports:
import struct
from thingsboard_gateway.connectors.can.can_converter import CanConverter
from thingsboard_gateway.connectors.converter import log
and context from other files:
# Path: thingsboard_gateway/connectors/can/can_converter.py
# class CanConverter(ABC):
# @abstractmethod
# def convert(self, config, data):
# pass
#
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
, which may contain function names, class names, or code. Output only the next line. | byteorder = config["dataByteorder"] if config.get("dataByteorder", "") else "big" |
Next line prediction: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 BACnetConverter(Converter):
def __init__(self, config):
pass
def convert(self, config, data):
<|code_end|>
. Use current file imports:
(from thingsboard_gateway.connectors.converter import Converter, log)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | pass |
Given snippet: <|code_start|># 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 GrpcDownlinkConverter(Converter):
def __init__(self):
self.__conversion_methods = {
DownlinkMessageType.Response: self.__convert_response_msg,
DownlinkMessageType.ConnectorConfigurationMsg: self.__convert_connector_configuration_msg,
DownlinkMessageType.GatewayAttributeUpdateNotificationMsg: self.__convert_gateway_attribute_update_notification_msg,
DownlinkMessageType.GatewayAttributeResponseMsg: self.__convert_gateway_attribute_response_msg,
DownlinkMessageType.GatewayDeviceRpcRequestMsg: self.__convert_gateway_device_rpc_request_msg,
DownlinkMessageType.UnregisterConnectorMsg: self.__convert_unregister_connector_msg
}
def convert(self, config, msg):
try:
basic_msg = FromServiceMessage()
message_types = config.get("message_type")
additional_message = config.get("additional_message")
if not isinstance(message_types, list):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from time import time
from typing import Union
from simplejson import dumps
from thingsboard_gateway.connectors.converter import Converter, log
from thingsboard_gateway.gateway.constant_enums import DownlinkMessageType
from thingsboard_gateway.gateway.proto.messages_pb2 import *
and context:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
#
# Path: thingsboard_gateway/gateway/constant_enums.py
# class DownlinkMessageType(Enum):
# Response = 0,
# ConnectorConfigurationMsg = 1,
# GatewayAttributeUpdateNotificationMsg = 2,
# GatewayAttributeResponseMsg = 3,
# GatewayDeviceRpcRequestMsg = 4,
# UnregisterConnectorMsg = 5
which might include code, classes, or functions. Output only the next line. | message_types = [message_types] |
Given the code snippet: <|code_start|>
@staticmethod
def __convert_connector_configuration_msg(basic_msg, msg, additional_data=None):
pass
@staticmethod
def __convert_gateway_attribute_update_notification_msg(basic_msg, msg, additional_data=None):
ts = int(time()*1000)
gw_attr_upd_notify_msg = GatewayAttributeUpdateNotificationMsg()
gw_attr_upd_notify_msg.deviceName = msg['device']
attr_notify_msg = AttributeUpdateNotificationMsg()
for shared_attribute in msg['data']:
ts_kv_proto = TsKvProto()
ts_kv_proto.ts = ts
kv = GrpcDownlinkConverter.__get_key_value_proto_value(shared_attribute, msg['data'][shared_attribute])
ts_kv_proto.kv.MergeFrom(kv)
attr_notify_msg.sharedUpdated.extend([ts_kv_proto])
gw_attr_upd_notify_msg.notificationMsg.MergeFrom(attr_notify_msg)
basic_msg.gatewayAttributeUpdateNotificationMsg.MergeFrom(gw_attr_upd_notify_msg)
return basic_msg
@staticmethod
def __convert_gateway_attribute_response_msg(basic_msg, msg, additional_data=None):
pass
@staticmethod
def __convert_gateway_device_rpc_request_msg(basic_msg, msg, additional_data=None):
msg_data = msg['data']
gw_to_device_rpc = GatewayDeviceRpcRequestMsg()
gw_to_device_rpc.deviceName = msg['device']
<|code_end|>
, generate the next line using the imports in this file:
from time import time
from typing import Union
from simplejson import dumps
from thingsboard_gateway.connectors.converter import Converter, log
from thingsboard_gateway.gateway.constant_enums import DownlinkMessageType
from thingsboard_gateway.gateway.proto.messages_pb2 import *
and context (functions, classes, or occasionally code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
#
# Path: thingsboard_gateway/gateway/constant_enums.py
# class DownlinkMessageType(Enum):
# Response = 0,
# ConnectorConfigurationMsg = 1,
# GatewayAttributeUpdateNotificationMsg = 2,
# GatewayAttributeResponseMsg = 3,
# GatewayDeviceRpcRequestMsg = 4,
# UnregisterConnectorMsg = 5
. Output only the next line. | rpc_request_msg = ToDeviceRpcRequestMsg() |
Given snippet: <|code_start|> DownlinkMessageType.ConnectorConfigurationMsg: self.__convert_connector_configuration_msg,
DownlinkMessageType.GatewayAttributeUpdateNotificationMsg: self.__convert_gateway_attribute_update_notification_msg,
DownlinkMessageType.GatewayAttributeResponseMsg: self.__convert_gateway_attribute_response_msg,
DownlinkMessageType.GatewayDeviceRpcRequestMsg: self.__convert_gateway_device_rpc_request_msg,
DownlinkMessageType.UnregisterConnectorMsg: self.__convert_unregister_connector_msg
}
def convert(self, config, msg):
try:
basic_msg = FromServiceMessage()
message_types = config.get("message_type")
additional_message = config.get("additional_message")
if not isinstance(message_types, list):
message_types = [message_types]
for message_type in message_types:
self.__conversion_methods[message_type](basic_msg, msg, additional_message)
return basic_msg
except Exception as e:
log.exception("[GRPC] ", e)
return None
@staticmethod
def __convert_response_msg(basic_msg, msg, additional_message):
if additional_message is not None:
if additional_message.HasField('gatewayTelemetryMsg'):
additional_message.gatewayTelemetryMsg.MergeFrom(GatewayTelemetryMsg())
elif additional_message.HasField("gatewayAttributesMsg"):
additional_message.gatewayTelemetryMsg.MergeFrom(GatewayTelemetryMsg())
else:
basic_msg.response.connectorMessage.MergeFrom(additional_message)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from time import time
from typing import Union
from simplejson import dumps
from thingsboard_gateway.connectors.converter import Converter, log
from thingsboard_gateway.gateway.constant_enums import DownlinkMessageType
from thingsboard_gateway.gateway.proto.messages_pb2 import *
and context:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
#
# Path: thingsboard_gateway/gateway/constant_enums.py
# class DownlinkMessageType(Enum):
# Response = 0,
# ConnectorConfigurationMsg = 1,
# GatewayAttributeUpdateNotificationMsg = 2,
# GatewayAttributeResponseMsg = 3,
# GatewayDeviceRpcRequestMsg = 4,
# UnregisterConnectorMsg = 5
which might include code, classes, or functions. Output only the next line. | basic_msg.response.status = ResponseStatus.Value(msg.name) |
Given snippet: <|code_start|> module = TBModuleLoader.import_module(self._connector_type, converter_class_name)
if module:
log.debug('Converter %s for device %s - found!', converter_class_name, self.name)
return module
log.error("Cannot find converter for %s device", self.name)
return None
def open(self):
self.__stopped = False
self.start()
def run(self):
self._connected = True
converting_thread = Thread(target=self.__convert_data, daemon=True, name='Converter Thread')
converting_thread.start()
self.__socket.bind((self.__socket_address, self.__socket_port))
if self.__socket_type == 'TCP':
self.__socket.listen(5)
self.__log.info('%s socket is up', self.__socket_type)
while not self.__stopped:
try:
if self.__socket_type == 'TCP':
conn, address = self.__socket.accept()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import socket
from queue import Queue
from random import choice
from string import ascii_lowercase
from threading import Thread
from time import sleep
from thingsboard_gateway.connectors.connector import Connector, log
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
and context:
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
#
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
# PATHS = []
# LOADED_CONNECTORS = {}
#
# @staticmethod
# def find_paths():
# root_path = path.abspath(path.dirname(path.dirname(__file__)))
# log.debug("Root path is: " + root_path)
# if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
# log.debug("Debian installation extensions folder exists.")
# TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
# TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
# TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
#
# @staticmethod
# def import_module(extension_type, module_name):
# if len(TBModuleLoader.PATHS) == 0:
# TBModuleLoader.find_paths()
# buffered_module_name = extension_type + module_name
# if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
# return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
# try:
# for current_path in TBModuleLoader.PATHS:
# current_extension_path = current_path + path.sep + extension_type
# if path.exists(current_extension_path):
# for file in listdir(current_extension_path):
# if not file.startswith('__') and file.endswith('.py'):
# try:
# module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
# log.debug(module_spec)
#
# if module_spec is None:
# continue
#
# module = module_from_spec(module_spec)
# module_spec.loader.exec_module(module)
# for extension_class in getmembers(module, isclass):
# if module_name in extension_class:
# log.info("Import %s from %s.", module_name, current_extension_path)
# TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
# return extension_class[1]
# except ImportError:
# continue
# except Exception as e:
# log.exception(e)
which might include code, classes, or functions. Output only the next line. | self.__connections[address] = conn |
Next line prediction: <|code_start|> conn, address = self.__socket.accept()
self.__connections[address] = conn
self.__log.debug('New connection %s established', address)
thread = Thread(target=self.__process_tcp_connection, daemon=True,
name=f'Processing {address} connection',
args=(conn, address))
thread.start()
else:
data, client_address = self.__socket.recvfrom(self.__socket_buff_size)
self.__converting_requests.put((client_address, data))
except ConnectionAbortedError:
self.__socket.close()
def __process_tcp_connection(self, connection, address):
while not self.__stopped:
data = connection.recv(self.__socket_buff_size)
if data:
self.__converting_requests.put((address, data))
else:
break
connection.close()
self.__connections.pop(address)
self.__log.debug('Connection %s closed', address)
def __convert_data(self):
while not self.__stopped:
if not self.__converting_requests.empty():
<|code_end|>
. Use current file imports:
(import socket
from queue import Queue
from random import choice
from string import ascii_lowercase
from threading import Thread
from time import sleep
from thingsboard_gateway.connectors.connector import Connector, log
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
#
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
# PATHS = []
# LOADED_CONNECTORS = {}
#
# @staticmethod
# def find_paths():
# root_path = path.abspath(path.dirname(path.dirname(__file__)))
# log.debug("Root path is: " + root_path)
# if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
# log.debug("Debian installation extensions folder exists.")
# TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
# TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
# TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
#
# @staticmethod
# def import_module(extension_type, module_name):
# if len(TBModuleLoader.PATHS) == 0:
# TBModuleLoader.find_paths()
# buffered_module_name = extension_type + module_name
# if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
# return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
# try:
# for current_path in TBModuleLoader.PATHS:
# current_extension_path = current_path + path.sep + extension_type
# if path.exists(current_extension_path):
# for file in listdir(current_extension_path):
# if not file.startswith('__') and file.endswith('.py'):
# try:
# module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
# log.debug(module_spec)
#
# if module_spec is None:
# continue
#
# module = module_from_spec(module_spec)
# module_spec.loader.exec_module(module)
# for extension_class in getmembers(module, isclass):
# if module_name in extension_class:
# log.info("Import %s from %s.", module_name, current_extension_path)
# TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
# return extension_class[1]
# except ImportError:
# continue
# except Exception as e:
# log.exception(e)
. Output only the next line. | (address, port), data = self.__converting_requests.get() |
Given the code snippet: <|code_start|> self.__log.exception(e)
return e
@staticmethod
def __write_value_via_udp(address, port, value):
new_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
new_socket.sendto(value, (address, int(port)))
new_socket.close()
def on_attributes_update(self, content):
try:
device = tuple(filter(lambda item: item['deviceName'] == content['device'], self.__config['devices']))[0]
for attribute_update_config in device['attributeUpdates']:
for attribute_update in content['data']:
if attribute_update_config['attributeOnThingsBoard'] == attribute_update:
address, port = device['address'].split(':')
encoding = device.get('encoding', 'utf-8').lower()
converted_data = bytes(str(content['data'][attribute_update]), encoding=encoding)
self.__write_value_via_tcp(address, port, converted_data)
except IndexError:
self.__log.error('Device not found')
def server_side_rpc_handler(self, content):
try:
device = tuple(filter(lambda item: item['deviceName'] == content['device'], self.__config['devices']))[0]
for rpc_config in device['serverSideRpc']:
for (key, value) in content['data'].items():
if value == rpc_config['methodRPC']:
<|code_end|>
, generate the next line using the imports in this file:
import socket
from queue import Queue
from random import choice
from string import ascii_lowercase
from threading import Thread
from time import sleep
from thingsboard_gateway.connectors.connector import Connector, log
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
and context (functions, classes, or occasionally code) from other files:
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
#
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
# PATHS = []
# LOADED_CONNECTORS = {}
#
# @staticmethod
# def find_paths():
# root_path = path.abspath(path.dirname(path.dirname(__file__)))
# log.debug("Root path is: " + root_path)
# if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
# log.debug("Debian installation extensions folder exists.")
# TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
# TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
# TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
#
# @staticmethod
# def import_module(extension_type, module_name):
# if len(TBModuleLoader.PATHS) == 0:
# TBModuleLoader.find_paths()
# buffered_module_name = extension_type + module_name
# if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
# return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
# try:
# for current_path in TBModuleLoader.PATHS:
# current_extension_path = current_path + path.sep + extension_type
# if path.exists(current_extension_path):
# for file in listdir(current_extension_path):
# if not file.startswith('__') and file.endswith('.py'):
# try:
# module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
# log.debug(module_spec)
#
# if module_spec is None:
# continue
#
# module = module_from_spec(module_spec)
# module_spec.loader.exec_module(module)
# for extension_class in getmembers(module, isclass):
# if module_name in extension_class:
# log.info("Import %s from %s.", module_name, current_extension_path)
# TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
# return extension_class[1]
# except ImportError:
# continue
# except Exception as e:
# log.exception(e)
. Output only the next line. | rpc_method = rpc_config['methodProcessing'] |
Based on the snippet: <|code_start|># 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 OdbcUplinkConverter(OdbcConverter):
def convert(self, config, data):
if isinstance(config, str) and config == "*":
return data
converted_data = {}
for config_item in config:
try:
if isinstance(config_item, str):
converted_data[config_item] = data[config_item]
elif isinstance(config_item, dict):
if "nameExpression" in config_item:
name = eval(config_item["nameExpression"], globals(), data)
else:
name = config_item["name"]
if "column" in config_item:
converted_data[name] = data[config_item["column"]]
elif "value" in config_item:
converted_data[name] = eval(config_item["value"], globals(), data)
else:
log.error("Failed to convert SQL data to TB format: no column/value configuration item")
<|code_end|>
, predict the immediate next line with the help of imports:
from thingsboard_gateway.connectors.converter import log
from thingsboard_gateway.connectors.odbc.odbc_converter import OdbcConverter
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
#
# Path: thingsboard_gateway/connectors/odbc/odbc_converter.py
# class OdbcConverter(ABC):
# @abstractmethod
# def convert(self, config, data):
# pass
. Output only the next line. | else: |
Continue the code snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 OdbcUplinkConverter(OdbcConverter):
def convert(self, config, data):
if isinstance(config, str) and config == "*":
return data
<|code_end|>
. Use current file imports:
from thingsboard_gateway.connectors.converter import log
from thingsboard_gateway.connectors.odbc.odbc_converter import OdbcConverter
and context (classes, functions, or code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
#
# Path: thingsboard_gateway/connectors/odbc/odbc_converter.py
# class OdbcConverter(ABC):
# @abstractmethod
# def convert(self, config, data):
# pass
. Output only the next line. | converted_data = {} |
Using the snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
#
# 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 BytesBLEUplinkConverter(BLEUplinkConverter):
def __init__(self, config):
self.__config = config
self.dict_result = {"deviceName": config['deviceName'],
"deviceType": config['deviceType']
}
def convert(self, config, data):
if data is None:
return {}
try:
<|code_end|>
, determine the next line of code. You have imports:
from pprint import pformat
from re import findall
from thingsboard_gateway.connectors.ble.ble_uplink_converter import BLEUplinkConverter, log
and context (class names, function names, or code) available:
# Path: thingsboard_gateway/connectors/ble/ble_uplink_converter.py
# class BLEUplinkConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | self.dict_result["telemetry"] = [] |
Given snippet: <|code_start|> self.dict_result = {"deviceName": config['deviceName'],
"deviceType": config['deviceType']
}
def convert(self, config, data):
if data is None:
return {}
try:
self.dict_result["telemetry"] = []
self.dict_result["attributes"] = []
for section in ('telemetry', 'attributes'):
for item in data[section]:
try:
expression_arr = findall(r'\[[^\s][0-9:]*]', item['valueExpression'])
converted_data = item['valueExpression']
for exp in expression_arr:
indexes = exp[1:-1].split(':')
data_to_replace = ''
if len(indexes) == 2:
from_index, to_index = indexes
concat_arr = item['data'][
int(from_index) if from_index != '' else None:int(
to_index) if to_index != '' else None]
for sub_item in concat_arr:
data_to_replace += str(sub_item)
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pprint import pformat
from re import findall
from thingsboard_gateway.connectors.ble.ble_uplink_converter import BLEUplinkConverter, log
and context:
# Path: thingsboard_gateway/connectors/ble/ble_uplink_converter.py
# class BLEUplinkConverter(Converter):
# def convert(self, config, data):
which might include code, classes, or functions. Output only the next line. | data_to_replace += str(item['data'][int(indexes[0])]) |
Given the code snippet: <|code_start|> if self.buffered_reader is not None and not self.buffered_reader.closed:
self.buffered_reader.close()
self.write_info_to_state_file(self.new_pos)
self.current_pos = self.new_pos
self.current_batch = None
except Exception as e:
log.exception(e)
def get_or_init_buffered_reader(self, pointer):
try:
if self.buffered_reader is None or self.buffered_reader.closed:
new_file_to_read_path = self.settings.get_data_folder_path() + pointer.get_file()
self.buffered_reader = BufferedReader(FileIO(new_file_to_read_path, 'r'))
lines_to_skip = pointer.get_line()
if lines_to_skip > 0:
while self.buffered_reader.readline() is not None:
if lines_to_skip > 0:
lines_to_skip -= 1
else:
break
return self.buffered_reader
except IOError as e:
log.error("Failed to initialize buffered reader! Error: %s", e)
raise RuntimeError("Failed to initialize buffered reader!", e)
except Exception as e:
log.exception(e)
def read_state_file(self):
<|code_end|>
, generate the next line using the imports in this file:
from base64 import b64decode
from io import BufferedReader, FileIO
from os import remove
from os.path import exists
from simplejson import JSONDecodeError, dumps, load
from thingsboard_gateway.storage.file.event_storage_files import EventStorageFiles
from thingsboard_gateway.storage.file.event_storage_reader_pointer import EventStorageReaderPointer
from thingsboard_gateway.storage.file.file_event_storage import log
from thingsboard_gateway.storage.file.file_event_storage_settings import FileEventStorageSettings
and context (functions, classes, or occasionally code) from other files:
# Path: thingsboard_gateway/storage/file/event_storage_files.py
# class EventStorageFiles:
# def __init__(self, state_file, data_files):
# self.state_file = state_file
# self.data_files = data_files
#
# def get_state_file(self):
# return self.state_file
#
# def get_data_files(self):
# return sorted(self.data_files)
#
# def set_data_files(self, data_files):
# self.data_files = data_files
#
# Path: thingsboard_gateway/storage/file/event_storage_reader_pointer.py
# class EventStorageReaderPointer:
# def __init__(self, file, line):
# self.file = file
# self.line = line
#
# def __eq__(self, other):
# return self.file == other.file and self.line == other.line
#
# def __hash__(self):
# return hash((self.file, self.line))
#
# def get_file(self):
# return self.file
#
# def get_line(self):
# return self.line
#
# def set_file(self, file):
# self.file = file
#
# def set_line(self, line):
# self.line = line
#
# Path: thingsboard_gateway/storage/file/file_event_storage.py
# class FileEventStorage(EventStorage):
# def __init__(self, config):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def init_data_folder_if_not_exist(self):
# def init_data_files(self):
# def create_new_datafile(self):
# def create_file(self, prefix, filename):
# def stop(self):
#
# Path: thingsboard_gateway/storage/file/file_event_storage_settings.py
# class FileEventStorageSettings:
# def __init__(self, config):
# self.data_folder_path = config.get("data_folder_path", "./")
# self.max_files_count = config.get("max_file_count", 5)
# self.max_records_per_file = config.get("max_records_per_file", 3)
# self.max_records_between_fsync = config.get("max_records_between_fsync", 1)
# self.max_read_records_count = config.get("max_read_records_count", 1000)
#
# def get_data_folder_path(self):
# return self.data_folder_path
#
# def get_max_files_count(self):
# return self.max_files_count
#
# def get_max_records_per_file(self):
# return self.max_records_per_file
#
# def get_max_records_between_fsync(self):
# return self.max_records_between_fsync
#
# def get_max_read_records_count(self):
# return self.max_read_records_count
. Output only the next line. | try: |
Predict the next line after this snippet: <|code_start|> records_to_read = self.settings.get_max_read_records_count()
while records_to_read > 0:
try:
current_line_in_file = self.new_pos.get_line()
self.buffered_reader = self.get_or_init_buffered_reader(self.new_pos)
if self.buffered_reader is not None:
line = self.buffered_reader.readline()
while line != b'':
try:
self.current_batch.append(b64decode(line).decode("utf-8"))
records_to_read -= 1
except IOError as e:
log.warning("Could not parse line [%s] to uplink message! %s", line, e)
except Exception as e:
log.exception(e)
current_line_in_file += 1
self.new_pos.set_line(current_line_in_file)
self.write_info_to_state_file(self.new_pos)
break
finally:
current_line_in_file += 1
if records_to_read > 0:
line = self.buffered_reader.readline()
self.new_pos.set_line(current_line_in_file)
if records_to_read == 0:
break
if (self.settings.get_max_records_per_file() >= current_line_in_file >= 0) or \
(line == b'' and current_line_in_file >= self.settings.get_max_records_per_file() - 1):
previous_file = self.current_pos
<|code_end|>
using the current file's imports:
from base64 import b64decode
from io import BufferedReader, FileIO
from os import remove
from os.path import exists
from simplejson import JSONDecodeError, dumps, load
from thingsboard_gateway.storage.file.event_storage_files import EventStorageFiles
from thingsboard_gateway.storage.file.event_storage_reader_pointer import EventStorageReaderPointer
from thingsboard_gateway.storage.file.file_event_storage import log
from thingsboard_gateway.storage.file.file_event_storage_settings import FileEventStorageSettings
and any relevant context from other files:
# Path: thingsboard_gateway/storage/file/event_storage_files.py
# class EventStorageFiles:
# def __init__(self, state_file, data_files):
# self.state_file = state_file
# self.data_files = data_files
#
# def get_state_file(self):
# return self.state_file
#
# def get_data_files(self):
# return sorted(self.data_files)
#
# def set_data_files(self, data_files):
# self.data_files = data_files
#
# Path: thingsboard_gateway/storage/file/event_storage_reader_pointer.py
# class EventStorageReaderPointer:
# def __init__(self, file, line):
# self.file = file
# self.line = line
#
# def __eq__(self, other):
# return self.file == other.file and self.line == other.line
#
# def __hash__(self):
# return hash((self.file, self.line))
#
# def get_file(self):
# return self.file
#
# def get_line(self):
# return self.line
#
# def set_file(self, file):
# self.file = file
#
# def set_line(self, line):
# self.line = line
#
# Path: thingsboard_gateway/storage/file/file_event_storage.py
# class FileEventStorage(EventStorage):
# def __init__(self, config):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def init_data_folder_if_not_exist(self):
# def init_data_files(self):
# def create_new_datafile(self):
# def create_file(self, prefix, filename):
# def stop(self):
#
# Path: thingsboard_gateway/storage/file/file_event_storage_settings.py
# class FileEventStorageSettings:
# def __init__(self, config):
# self.data_folder_path = config.get("data_folder_path", "./")
# self.max_files_count = config.get("max_file_count", 5)
# self.max_records_per_file = config.get("max_records_per_file", 3)
# self.max_records_between_fsync = config.get("max_records_between_fsync", 1)
# self.max_read_records_count = config.get("max_read_records_count", 1000)
#
# def get_data_folder_path(self):
# return self.data_folder_path
#
# def get_max_files_count(self):
# return self.max_files_count
#
# def get_max_records_per_file(self):
# return self.max_records_per_file
#
# def get_max_records_between_fsync(self):
# return self.max_records_between_fsync
#
# def get_max_read_records_count(self):
# return self.max_read_records_count
. Output only the next line. | next_file = self.get_next_file(self.files, self.new_pos) |
Continue the code snippet: <|code_start|># 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 EventStorageReader:
def __init__(self, files: EventStorageFiles, settings: FileEventStorageSettings):
self.log = log
self.files = files
self.settings = settings
self.current_batch = None
self.buffered_reader = None
self.current_pos = self.read_state_file()
self.new_pos = self.current_pos
def read(self):
if self.current_batch is not None and self.current_batch:
log.debug("The previous batch was not discarded!")
return self.current_batch
self.current_batch = []
records_to_read = self.settings.get_max_read_records_count()
while records_to_read > 0:
try:
current_line_in_file = self.new_pos.get_line()
self.buffered_reader = self.get_or_init_buffered_reader(self.new_pos)
if self.buffered_reader is not None:
<|code_end|>
. Use current file imports:
from base64 import b64decode
from io import BufferedReader, FileIO
from os import remove
from os.path import exists
from simplejson import JSONDecodeError, dumps, load
from thingsboard_gateway.storage.file.event_storage_files import EventStorageFiles
from thingsboard_gateway.storage.file.event_storage_reader_pointer import EventStorageReaderPointer
from thingsboard_gateway.storage.file.file_event_storage import log
from thingsboard_gateway.storage.file.file_event_storage_settings import FileEventStorageSettings
and context (classes, functions, or code) from other files:
# Path: thingsboard_gateway/storage/file/event_storage_files.py
# class EventStorageFiles:
# def __init__(self, state_file, data_files):
# self.state_file = state_file
# self.data_files = data_files
#
# def get_state_file(self):
# return self.state_file
#
# def get_data_files(self):
# return sorted(self.data_files)
#
# def set_data_files(self, data_files):
# self.data_files = data_files
#
# Path: thingsboard_gateway/storage/file/event_storage_reader_pointer.py
# class EventStorageReaderPointer:
# def __init__(self, file, line):
# self.file = file
# self.line = line
#
# def __eq__(self, other):
# return self.file == other.file and self.line == other.line
#
# def __hash__(self):
# return hash((self.file, self.line))
#
# def get_file(self):
# return self.file
#
# def get_line(self):
# return self.line
#
# def set_file(self, file):
# self.file = file
#
# def set_line(self, line):
# self.line = line
#
# Path: thingsboard_gateway/storage/file/file_event_storage.py
# class FileEventStorage(EventStorage):
# def __init__(self, config):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def init_data_folder_if_not_exist(self):
# def init_data_files(self):
# def create_new_datafile(self):
# def create_file(self, prefix, filename):
# def stop(self):
#
# Path: thingsboard_gateway/storage/file/file_event_storage_settings.py
# class FileEventStorageSettings:
# def __init__(self, config):
# self.data_folder_path = config.get("data_folder_path", "./")
# self.max_files_count = config.get("max_file_count", 5)
# self.max_records_per_file = config.get("max_records_per_file", 3)
# self.max_records_between_fsync = config.get("max_records_between_fsync", 1)
# self.max_read_records_count = config.get("max_read_records_count", 1000)
#
# def get_data_folder_path(self):
# return self.data_folder_path
#
# def get_max_files_count(self):
# return self.max_files_count
#
# def get_max_records_per_file(self):
# return self.max_records_per_file
#
# def get_max_records_between_fsync(self):
# return self.max_records_between_fsync
#
# def get_max_read_records_count(self):
# return self.max_read_records_count
. Output only the next line. | line = self.buffered_reader.readline() |
Predict the next line after this snippet: <|code_start|>
return self.buffered_reader
except IOError as e:
log.error("Failed to initialize buffered reader! Error: %s", e)
raise RuntimeError("Failed to initialize buffered reader!", e)
except Exception as e:
log.exception(e)
def read_state_file(self):
try:
state_data_node = {}
try:
with BufferedReader(FileIO(self.settings.get_data_folder_path() + self.files.get_state_file(), 'r')) as buffered_reader:
state_data_node = load(buffered_reader)
except JSONDecodeError:
log.error("Failed to decode JSON from state file")
state_data_node = 0
except IOError as e:
log.warning("Failed to fetch info from state file! Error: %s", e)
reader_file = None
reader_pos = 0
if state_data_node:
reader_pos = state_data_node['position']
for file in sorted(self.files.get_data_files()):
if file == state_data_node['file']:
reader_file = file
break
if reader_file is None:
reader_file = sorted(self.files.get_data_files())[0]
<|code_end|>
using the current file's imports:
from base64 import b64decode
from io import BufferedReader, FileIO
from os import remove
from os.path import exists
from simplejson import JSONDecodeError, dumps, load
from thingsboard_gateway.storage.file.event_storage_files import EventStorageFiles
from thingsboard_gateway.storage.file.event_storage_reader_pointer import EventStorageReaderPointer
from thingsboard_gateway.storage.file.file_event_storage import log
from thingsboard_gateway.storage.file.file_event_storage_settings import FileEventStorageSettings
and any relevant context from other files:
# Path: thingsboard_gateway/storage/file/event_storage_files.py
# class EventStorageFiles:
# def __init__(self, state_file, data_files):
# self.state_file = state_file
# self.data_files = data_files
#
# def get_state_file(self):
# return self.state_file
#
# def get_data_files(self):
# return sorted(self.data_files)
#
# def set_data_files(self, data_files):
# self.data_files = data_files
#
# Path: thingsboard_gateway/storage/file/event_storage_reader_pointer.py
# class EventStorageReaderPointer:
# def __init__(self, file, line):
# self.file = file
# self.line = line
#
# def __eq__(self, other):
# return self.file == other.file and self.line == other.line
#
# def __hash__(self):
# return hash((self.file, self.line))
#
# def get_file(self):
# return self.file
#
# def get_line(self):
# return self.line
#
# def set_file(self, file):
# self.file = file
#
# def set_line(self, line):
# self.line = line
#
# Path: thingsboard_gateway/storage/file/file_event_storage.py
# class FileEventStorage(EventStorage):
# def __init__(self, config):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def init_data_folder_if_not_exist(self):
# def init_data_files(self):
# def create_new_datafile(self):
# def create_file(self, prefix, filename):
# def stop(self):
#
# Path: thingsboard_gateway/storage/file/file_event_storage_settings.py
# class FileEventStorageSettings:
# def __init__(self, config):
# self.data_folder_path = config.get("data_folder_path", "./")
# self.max_files_count = config.get("max_file_count", 5)
# self.max_records_per_file = config.get("max_records_per_file", 3)
# self.max_records_between_fsync = config.get("max_records_between_fsync", 1)
# self.max_read_records_count = config.get("max_read_records_count", 1000)
#
# def get_data_folder_path(self):
# return self.data_folder_path
#
# def get_max_files_count(self):
# return self.max_files_count
#
# def get_max_records_per_file(self):
# return self.max_records_per_file
#
# def get_max_records_between_fsync(self):
# return self.max_records_between_fsync
#
# def get_max_read_records_count(self):
# return self.max_read_records_count
. Output only the next line. | reader_pos = 0 |
Here is a snippet: <|code_start|># 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 DataFileCountError(Exception):
pass
class EventStorageWriter:
def __init__(self, files: EventStorageFiles, settings: FileEventStorageSettings):
self.files = files
self.settings = settings
self.buffered_writer = None
self.current_file = sorted(files.get_data_files())[-1]
self.current_file_records_count = [0]
self.previous_file_records_count = [0]
self.get_number_of_records_in_file(self.current_file)
def write(self, msg):
if len(self.files.data_files) <= self.settings.get_max_files_count():
if self.current_file_records_count[0] >= self.settings.get_max_records_per_file() or not exists(
<|code_end|>
. Write the next line using the current file imports:
from base64 import b64encode
from io import BufferedWriter, FileIO
from os import O_CREAT, O_EXCL, close as os_close, linesep, open as os_open
from os.path import exists
from time import time
from thingsboard_gateway.storage.file.event_storage_files import EventStorageFiles
from thingsboard_gateway.storage.file.file_event_storage import log
from thingsboard_gateway.storage.file.file_event_storage_settings import FileEventStorageSettings
and context from other files:
# Path: thingsboard_gateway/storage/file/event_storage_files.py
# class EventStorageFiles:
# def __init__(self, state_file, data_files):
# self.state_file = state_file
# self.data_files = data_files
#
# def get_state_file(self):
# return self.state_file
#
# def get_data_files(self):
# return sorted(self.data_files)
#
# def set_data_files(self, data_files):
# self.data_files = data_files
#
# Path: thingsboard_gateway/storage/file/file_event_storage.py
# class FileEventStorage(EventStorage):
# def __init__(self, config):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def init_data_folder_if_not_exist(self):
# def init_data_files(self):
# def create_new_datafile(self):
# def create_file(self, prefix, filename):
# def stop(self):
#
# Path: thingsboard_gateway/storage/file/file_event_storage_settings.py
# class FileEventStorageSettings:
# def __init__(self, config):
# self.data_folder_path = config.get("data_folder_path", "./")
# self.max_files_count = config.get("max_file_count", 5)
# self.max_records_per_file = config.get("max_records_per_file", 3)
# self.max_records_between_fsync = config.get("max_records_between_fsync", 1)
# self.max_read_records_count = config.get("max_read_records_count", 1000)
#
# def get_data_folder_path(self):
# return self.data_folder_path
#
# def get_max_files_count(self):
# return self.max_files_count
#
# def get_max_records_per_file(self):
# return self.max_records_per_file
#
# def get_max_records_between_fsync(self):
# return self.max_records_between_fsync
#
# def get_max_read_records_count(self):
# return self.max_read_records_count
, which may include functions, classes, or code. Output only the next line. | self.settings.get_data_folder_path() + self.current_file): |
Predict the next line for this snippet: <|code_start|>
class DataFileCountError(Exception):
pass
class EventStorageWriter:
def __init__(self, files: EventStorageFiles, settings: FileEventStorageSettings):
self.files = files
self.settings = settings
self.buffered_writer = None
self.current_file = sorted(files.get_data_files())[-1]
self.current_file_records_count = [0]
self.previous_file_records_count = [0]
self.get_number_of_records_in_file(self.current_file)
def write(self, msg):
if len(self.files.data_files) <= self.settings.get_max_files_count():
if self.current_file_records_count[0] >= self.settings.get_max_records_per_file() or not exists(
self.settings.get_data_folder_path() + self.current_file):
try:
self.current_file = self.create_datafile()
log.debug("FileStorage_writer -- Created new data file: %s", self.current_file)
except IOError as e:
log.error("Failed to create a new file! %s", e)
self.files.get_data_files().append(self.current_file)
self.current_file_records_count[0] = 0
try:
if self.buffered_writer is not None and self.buffered_writer.closed is False:
self.buffered_writer.close()
<|code_end|>
with the help of current file imports:
from base64 import b64encode
from io import BufferedWriter, FileIO
from os import O_CREAT, O_EXCL, close as os_close, linesep, open as os_open
from os.path import exists
from time import time
from thingsboard_gateway.storage.file.event_storage_files import EventStorageFiles
from thingsboard_gateway.storage.file.file_event_storage import log
from thingsboard_gateway.storage.file.file_event_storage_settings import FileEventStorageSettings
and context from other files:
# Path: thingsboard_gateway/storage/file/event_storage_files.py
# class EventStorageFiles:
# def __init__(self, state_file, data_files):
# self.state_file = state_file
# self.data_files = data_files
#
# def get_state_file(self):
# return self.state_file
#
# def get_data_files(self):
# return sorted(self.data_files)
#
# def set_data_files(self, data_files):
# self.data_files = data_files
#
# Path: thingsboard_gateway/storage/file/file_event_storage.py
# class FileEventStorage(EventStorage):
# def __init__(self, config):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def init_data_folder_if_not_exist(self):
# def init_data_files(self):
# def create_new_datafile(self):
# def create_file(self, prefix, filename):
# def stop(self):
#
# Path: thingsboard_gateway/storage/file/file_event_storage_settings.py
# class FileEventStorageSettings:
# def __init__(self, config):
# self.data_folder_path = config.get("data_folder_path", "./")
# self.max_files_count = config.get("max_file_count", 5)
# self.max_records_per_file = config.get("max_records_per_file", 3)
# self.max_records_between_fsync = config.get("max_records_between_fsync", 1)
# self.max_read_records_count = config.get("max_read_records_count", 1000)
#
# def get_data_folder_path(self):
# return self.data_folder_path
#
# def get_max_files_count(self):
# return self.max_files_count
#
# def get_max_records_per_file(self):
# return self.max_records_per_file
#
# def get_max_records_between_fsync(self):
# return self.max_records_between_fsync
#
# def get_max_read_records_count(self):
# return self.max_read_records_count
, which may contain function names, class names, or code. Output only the next line. | except IOError as e: |
Predict the next line for this snippet: <|code_start|># 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 DataFileCountError(Exception):
pass
class EventStorageWriter:
def __init__(self, files: EventStorageFiles, settings: FileEventStorageSettings):
self.files = files
self.settings = settings
self.buffered_writer = None
self.current_file = sorted(files.get_data_files())[-1]
self.current_file_records_count = [0]
self.previous_file_records_count = [0]
self.get_number_of_records_in_file(self.current_file)
def write(self, msg):
if len(self.files.data_files) <= self.settings.get_max_files_count():
if self.current_file_records_count[0] >= self.settings.get_max_records_per_file() or not exists(
self.settings.get_data_folder_path() + self.current_file):
try:
self.current_file = self.create_datafile()
log.debug("FileStorage_writer -- Created new data file: %s", self.current_file)
<|code_end|>
with the help of current file imports:
from base64 import b64encode
from io import BufferedWriter, FileIO
from os import O_CREAT, O_EXCL, close as os_close, linesep, open as os_open
from os.path import exists
from time import time
from thingsboard_gateway.storage.file.event_storage_files import EventStorageFiles
from thingsboard_gateway.storage.file.file_event_storage import log
from thingsboard_gateway.storage.file.file_event_storage_settings import FileEventStorageSettings
and context from other files:
# Path: thingsboard_gateway/storage/file/event_storage_files.py
# class EventStorageFiles:
# def __init__(self, state_file, data_files):
# self.state_file = state_file
# self.data_files = data_files
#
# def get_state_file(self):
# return self.state_file
#
# def get_data_files(self):
# return sorted(self.data_files)
#
# def set_data_files(self, data_files):
# self.data_files = data_files
#
# Path: thingsboard_gateway/storage/file/file_event_storage.py
# class FileEventStorage(EventStorage):
# def __init__(self, config):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def init_data_folder_if_not_exist(self):
# def init_data_files(self):
# def create_new_datafile(self):
# def create_file(self, prefix, filename):
# def stop(self):
#
# Path: thingsboard_gateway/storage/file/file_event_storage_settings.py
# class FileEventStorageSettings:
# def __init__(self, config):
# self.data_folder_path = config.get("data_folder_path", "./")
# self.max_files_count = config.get("max_file_count", 5)
# self.max_records_per_file = config.get("max_records_per_file", 3)
# self.max_records_between_fsync = config.get("max_records_between_fsync", 1)
# self.max_read_records_count = config.get("max_read_records_count", 1000)
#
# def get_data_folder_path(self):
# return self.data_folder_path
#
# def get_max_files_count(self):
# return self.max_files_count
#
# def get_max_records_per_file(self):
# return self.max_records_per_file
#
# def get_max_records_between_fsync(self):
# return self.max_records_between_fsync
#
# def get_max_read_records_count(self):
# return self.max_read_records_count
, which may contain function names, class names, or code. Output only the next line. | except IOError as e: |
Based on the snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 MemoryEventStorage(EventStorage):
def __init__(self, config):
self.__queue_len = config.get("max_records_count", 10000)
self.__events_per_time = config.get("read_records_count", 1000)
self.__events_queue = Queue(self.__queue_len)
self.__event_pack = []
self.__stopped = False
log.debug("Memory storage created with following configuration: \nMax size: %i\n Read records per time: %i",
self.__queue_len, self.__events_per_time)
<|code_end|>
, predict the immediate next line with the help of imports:
from queue import Empty, Full, Queue
from thingsboard_gateway.storage.event_storage import EventStorage, log
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/storage/event_storage.py
# class EventStorage(ABC):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def stop(self):
. Output only the next line. | def put(self, event): |
Predict the next line for this snippet: <|code_start|># 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 MemoryEventStorage(EventStorage):
def __init__(self, config):
self.__queue_len = config.get("max_records_count", 10000)
self.__events_per_time = config.get("read_records_count", 1000)
self.__events_queue = Queue(self.__queue_len)
self.__event_pack = []
self.__stopped = False
log.debug("Memory storage created with following configuration: \nMax size: %i\n Read records per time: %i",
self.__queue_len, self.__events_per_time)
def put(self, event):
success = False
if not self.__stopped:
try:
self.__events_queue.put(event)
<|code_end|>
with the help of current file imports:
from queue import Empty, Full, Queue
from thingsboard_gateway.storage.event_storage import EventStorage, log
and context from other files:
# Path: thingsboard_gateway/storage/event_storage.py
# class EventStorage(ABC):
# def put(self, event):
# def get_event_pack(self):
# def event_pack_processing_done(self):
# def stop(self):
, which may contain function names, class names, or code. Output only the next line. | success = True |
Given snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 RequestUplinkConverter(Converter):
@abstractmethod
def convert(self, config, data):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from thingsboard_gateway.connectors.converter import Converter, abstractmethod
and context:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
which might include code, classes, or functions. Output only the next line. | pass |
Given snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 CustomSerialUplinkConverter(Converter):
def __init__(self, config):
self.__config = config
self.result_dict = {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from thingsboard_gateway.connectors.converter import Converter, log
and context:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
which might include code, classes, or functions. Output only the next line. | 'deviceName': config.get('name', 'CustomSerialDevice'), |
Given snippet: <|code_start|># 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 CustomSerialUplinkConverter(Converter):
def __init__(self, config):
self.__config = config
self.result_dict = {
'deviceName': config.get('name', 'CustomSerialDevice'),
'deviceType': config.get('deviceType', 'default'),
'attributes': [],
'telemetry': []
}
def convert(self, config, data: bytes):
keys = ['attributes', 'telemetry']
for key in keys:
self.result_dict[key] = []
if self.__config.get(key) is not None:
for config_object in self.__config.get(key):
data_to_convert = data
if config_object.get('untilDelimiter') is not None:
data_to_convert = data.split(config_object.get('untilDelimiter').encode('UTF-8'))[0]
if config_object.get('fromDelimiter') is not None:
data_to_convert = data.split(config_object.get('fromDelimiter').encode('UTF-8'))[1]
if config_object.get('toByte') is not None:
to_byte = config_object.get('toByte')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from thingsboard_gateway.connectors.converter import Converter, log
and context:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
which might include code, classes, or functions. Output only the next line. | if to_byte == -1: |
Continue the code snippet: <|code_start|>#
# 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 BytesCanUplinkConverter(CanConverter):
def convert(self, configs, can_data):
result = {"attributes": {},
"telemetry": {}}
for config in configs:
try:
tb_key = config["key"]
tb_item = "telemetry" if config["is_ts"] else "attributes"
data_length = config["length"] if config["length"] != -1 else len(can_data) - config["start"]
# The 'value' variable is used in eval
if config["type"][0] == "b":
<|code_end|>
. Use current file imports:
import struct
from thingsboard_gateway.connectors.can.can_converter import CanConverter
from thingsboard_gateway.connectors.converter import log
and context (classes, functions, or code) from other files:
# Path: thingsboard_gateway/connectors/can/can_converter.py
# class CanConverter(ABC):
# @abstractmethod
# def convert(self, config, data):
# pass
#
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | value = bool(can_data[config["start"]]) |
Given the code snippet: <|code_start|># Copyright 2020. ThingsBoard
#
# 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 BytesCanUplinkConverter(CanConverter):
def convert(self, configs, can_data):
result = {"attributes": {},
"telemetry": {}}
for config in configs:
<|code_end|>
, generate the next line using the imports in this file:
import struct
from thingsboard_gateway.connectors.can.can_converter import CanConverter
from thingsboard_gateway.connectors.converter import log
and context (functions, classes, or occasionally code) from other files:
# Path: thingsboard_gateway/connectors/can/can_converter.py
# class CanConverter(ABC):
# @abstractmethod
# def convert(self, config, data):
# pass
#
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | try: |
Next line prediction: <|code_start|> decoded = decoder_functions[lower_type]()
elif lower_type in ['int', 'long', 'integer']:
type_ = str(objects_count * 16) + "int"
assert decoder_functions.get(type_) is not None
decoded = decoder_functions[type_]()
elif lower_type in ["double", "float"]:
type_ = str(objects_count * 16) + "float"
assert decoder_functions.get(type_) is not None
decoded = decoder_functions[type_]()
elif lower_type == 'uint':
type_ = str(objects_count * 16) + "uint"
assert decoder_functions.get(type_) is not None
decoded = decoder_functions[type_]()
else:
log.error("Unknown type: %s", type_)
if isinstance(decoded, int):
result_data = decoded
elif isinstance(decoded, bytes) and lower_type == "string":
result_data = decoded.decode('UTF-8')
elif isinstance(decoded, bytes) and lower_type == "bytes":
result_data = decoded.hex()
elif isinstance(decoded, list):
if configuration.get('bit') is not None:
result_data = int(decoded[configuration['bit']])
else:
<|code_end|>
. Use current file imports:
(from pymodbus.constants import Endian
from pymodbus.exceptions import ModbusIOException
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.pdu import ExceptionResponse
from thingsboard_gateway.connectors.modbus.modbus_converter import ModbusConverter, log)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/modbus/modbus_converter.py
# class ModbusConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | result_data = [int(bit) for bit in decoded] |
Here is a snippet: <|code_start|> log.debug(self.__result)
return self.__result
@staticmethod
def __decode_from_registers(decoder, configuration):
type_ = configuration["type"]
objects_count = configuration.get("objectsCount", configuration.get("registersCount", configuration.get("registerCount", 1)))
lower_type = type_.lower()
decoder_functions = {
'string': decoder.decode_string,
'bytes': decoder.decode_string,
'bit': decoder.decode_bits,
'bits': decoder.decode_bits,
'8int': decoder.decode_8bit_int,
'8uint': decoder.decode_8bit_uint,
'16int': decoder.decode_16bit_int,
'16uint': decoder.decode_16bit_uint,
'16float': decoder.decode_16bit_float,
'32int': decoder.decode_32bit_int,
'32uint': decoder.decode_32bit_uint,
'32float': decoder.decode_32bit_float,
'64int': decoder.decode_64bit_int,
'64uint': decoder.decode_64bit_uint,
'64float': decoder.decode_64bit_float,
}
decoded = None
if lower_type in ['bit','bits']:
<|code_end|>
. Write the next line using the current file imports:
from pymodbus.constants import Endian
from pymodbus.exceptions import ModbusIOException
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.pdu import ExceptionResponse
from thingsboard_gateway.connectors.modbus.modbus_converter import ModbusConverter, log
and context from other files:
# Path: thingsboard_gateway/connectors/modbus/modbus_converter.py
# class ModbusConverter(Converter):
# def convert(self, config, data):
, which may include functions, classes, or code. Output only the next line. | decoded_lastbyte= decoder_functions[type_]() |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 DatabaseRequest:
# Wrap data and write intention to better control
# Writes. They need to be atomic so we don't corrupt DB
def __init__(self, _type: DatabaseActionType, data):
self.type = _type
<|code_end|>
, predict the next line using imports from the current file:
from thingsboard_gateway.storage.sqlite.database_action_type import DatabaseActionType
and context including class names, function names, and sometimes code from other files:
# Path: thingsboard_gateway/storage/sqlite/database_action_type.py
# class DatabaseActionType(Enum):
# WRITE_DATA_STORAGE = auto() # Writes do not require a response on the request
. Output only the next line. | self.data = data |
Predict the next line after this snippet: <|code_start|> for node in node_paths:
if not self.__is_file(ftp, node):
arr.append(ftp.pwd() + node)
final_arr = arr
ftp.cwd(current)
else:
if len(final_arr) > 0:
current = ftp.pwd()
for (j, k) in enumerate(final_arr):
ftp.cwd(k)
if not self.__is_file(ftp, item):
final_arr[j] = str(final_arr[j]) + '/' + item
else:
final_arr = []
ftp.cwd(current)
else:
if not self.__is_file(ftp, item):
final_arr.append(item)
final_arr = self.__get_files(ftp, final_arr, filename, fileex)
ftp.cwd(current_dir)
self._files = final_arr
@property
def config(self):
return {
'delimiter': self.delimiter,
'devicePatternName': self.device_name,
<|code_end|>
using the current file's imports:
import os
from regex import compile
from thingsboard_gateway.connectors.ftp.file import File
and any relevant context from other files:
# Path: thingsboard_gateway/connectors/ftp/file.py
# class File:
# class ReadMode(Enum):
# FULL = 'FULL'
# PARTIAL = 'PARTIAL'
#
# def __init__(self, path_to_file: str, read_mode: ReadMode, max_size: int):
# self._path_to_file = path_to_file
# self._read_mode = read_mode
# self._max_size = max_size
# self._hash = None
# self._cursor = None
#
# def __str__(self):
# return f'{self._path_to_file} {self._read_mode}'
#
# @property
# def path_to_file(self):
# return self._path_to_file
#
# @property
# def hash(self):
# return self._hash
#
# @property
# def read_mode(self):
# return self._read_mode
#
# @property
# def cursor(self):
# return self._cursor
#
# @cursor.setter
# def cursor(self, val):
# self._cursor = val
#
# def has_hash(self):
# return True if self._hash else False
#
# def get_current_hash(self, ftp):
# return crc32((ftp.voidcmd(f'MDTM {self._path_to_file}') + str(ftp.size(self.path_to_file))).encode('utf-8'))
#
# def set_new_hash(self, file_hash):
# self._hash = file_hash
#
# @staticmethod
# def convert_bytes_to_mb(bts):
# r = float(bts)
# for _ in range(2):
# r = r / 1024
# return round(r, 2)
#
# def check_size_limit(self, ftp):
# return self.convert_bytes_to_mb(ftp.size(self.path_to_file)) < self._max_size
. Output only the next line. | 'devicePatternType': self.device_type, |
Based on the snippet: <|code_start|> ts_kv_list_dict = {"ts": ts_kv_list.ts, "values": {}}
for kv in ts_kv_list.kv:
ts_kv_list_dict['values'][kv.key] = GrpcUplinkConverter.get_value(kv)
device_dict['telemetry'].append(ts_kv_list_dict)
result.append(device_dict)
return result
@staticmethod
def __convert_gateway_attributes_msg(msg: GatewayAttributesMsg):
result = []
for attributes_msg in msg.msg:
device_dict = {"deviceName": attributes_msg.deviceName, "attributes": {}}
for kv in attributes_msg.msg.kv:
device_dict['attributes'][kv.key] = GrpcUplinkConverter.get_value(kv)
result.append(device_dict)
return result
@staticmethod
def __convert_gateway_claim_msg(msg: GatewayClaimMsg):
result_dict = {}
for claim_device_msg in msg:
result_dict.update({claim_device_msg.deviceName: {"secretKey": claim_device_msg.msg.secretKey, "durationMs": claim_device_msg.msg.durationMs}})
return result_dict
@staticmethod
def __convert_connect_msg(msg: ConnectMsg) -> dict:
result_dict = {'deviceName': msg.deviceName, 'deviceType': msg.deviceType}
return result_dict
@staticmethod
<|code_end|>
, predict the immediate next line with the help of imports:
from thingsboard_gateway.connectors.converter import Converter, log
from thingsboard_gateway.gateway.proto.messages_pb2 import ConnectMsg, DisconnectMsg, GatewayAttributesMsg, GatewayAttributesRequestMsg, GatewayClaimMsg, \
GatewayRpcResponseMsg, GatewayTelemetryMsg, KeyValueProto, KeyValueType, Response
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | def __convert_disconnect_msg(msg: DisconnectMsg): |
Based on the snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 FTPConverter(Converter):
@abstractmethod
def convert(self, config, data):
<|code_end|>
, predict the immediate next line with the help of imports:
from thingsboard_gateway.connectors.converter import Converter, abstractmethod
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | pass |
Given snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 FTPConverter(Converter):
@abstractmethod
def convert(self, config, data):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from thingsboard_gateway.connectors.converter import Converter, abstractmethod
and context:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
which might include code, classes, or functions. Output only the next line. | pass |
Based on the snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 CustomMqttUplinkConverter(MqttUplinkConverter):
def __init__(self, config):
self.__config = config.get('converter')
self.dict_result = {}
def convert(self, topic, body):
try:
self.dict_result["deviceName"] = topic.split("/")[
<|code_end|>
, predict the immediate next line with the help of imports:
from simplejson import dumps
from thingsboard_gateway.connectors.mqtt.mqtt_uplink_converter import MqttUplinkConverter, log
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/mqtt/mqtt_uplink_converter.py
# class MqttUplinkConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | -1] # getting all data after last '/' symbol in this case: if topic = 'devices/temperature/sensor1' device name will be 'sensor1'. |
Based on the snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class CustomMqttUplinkConverter(MqttUplinkConverter):
def __init__(self, config):
self.__config = config.get('converter')
self.dict_result = {}
def convert(self, topic, body):
try:
self.dict_result["deviceName"] = topic.split("/")[
-1] # getting all data after last '/' symbol in this case: if topic = 'devices/temperature/sensor1' device name will be 'sensor1'.
self.dict_result["deviceType"] = "Thermostat" # just hardcode this
self.dict_result["telemetry"] = [] # template for telemetry array
bytes_to_read = body.replace("0x", "") # Replacing the 0x (if '0x' in body), needs for converting to bytearray
converted_bytes = bytearray.fromhex(bytes_to_read) # Converting incoming data to bytearray
if self.__config.get("extension-config") is not None:
for telemetry_key in self.__config["extension-config"]: # Processing every telemetry key in config for extension
value = 0
for _ in range(self.__config["extension-config"][telemetry_key]): # reading every value with value length from config
value = value * 256 + converted_bytes.pop(0) # process and remove byte from processing
<|code_end|>
, predict the immediate next line with the help of imports:
from simplejson import dumps
from thingsboard_gateway.connectors.mqtt.mqtt_uplink_converter import MqttUplinkConverter, log
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/mqtt/mqtt_uplink_converter.py
# class MqttUplinkConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | telemetry_to_send = {telemetry_key.replace("Bytes", ""): value} # creating telemetry data for sending into Thingsboard |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 BLEUplinkConverter(Converter):
@abstractmethod
def convert(self, config, data):
<|code_end|>
, predict the next line using imports from the current file:
from thingsboard_gateway.connectors.converter import Converter, abstractmethod, log
and context including class names, function names, and sometimes code from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | pass |
Based on the snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 ModbusConverter(Converter):
@abstractmethod
def convert(self, config, data):
<|code_end|>
, predict the immediate next line with the help of imports:
from thingsboard_gateway.connectors.converter import Converter, abstractmethod, log
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | pass |
Based on the snippet: <|code_start|> self.assertListEqual(actual_can_data, list(value.encode(encoding)))
def test_expression_data(self):
default_data_length = 1
default_byteorder = "big"
data = {
"one": 1,
"two": 2,
"three": 3
}
config = {"dataExpression": "one + two + three"}
value = 0
for i in data.values():
value += i
actual_can_data = self.converter.convert(config, data)
self.assertListEqual(actual_can_data,
list(value.to_bytes(default_data_length, default_byteorder)))
def test_strict_eval_violation(self):
data = {"value": randint(0, 256)}
config = {
"dataExpression": "pow(value, 2)",
"strictEval": True
}
self.assertIsNone(self.converter.convert(config, data))
def test_data_before(self):
value = True
expected_can_data = [0, 1, 2, 3, int(value)]
data = {"value": value}
<|code_end|>
, predict the immediate next line with the help of imports:
import struct
import unittest
from random import randint, uniform, choice
from string import ascii_lowercase
from thingsboard_gateway.connectors.can.bytes_can_downlink_converter import BytesCanDownlinkConverter
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/can/bytes_can_downlink_converter.py
# class BytesCanDownlinkConverter(CanConverter):
# def convert(self, config, data):
# try:
# if config.get("dataInHex", ""):
# return list(bytearray.fromhex(config["dataInHex"]))
#
# if not isinstance(data, dict) or not data:
# log.error("Failed to convert TB data to CAN payload: data is empty or not a dictionary")
# return
#
# if data.get("dataInHex", ""):
# return list(bytearray.fromhex(data["dataInHex"]))
#
# if config.get("dataExpression", ""):
# value = eval(config["dataExpression"],
# {"__builtins__": {}} if config.get("strictEval", True) else globals(),
# data)
# elif "value" in data:
# value = data["value"]
# else:
# log.error("Failed to convert TB data to CAN payload: no `value` or `dataExpression` property")
# return
#
# can_data = []
#
# if config.get("dataBefore", ""):
# can_data.extend(bytearray.fromhex(config["dataBefore"]))
#
# if isinstance(value, bool):
# can_data.extend([int(value)])
# elif isinstance(value, int) or isinstance(value, float):
# byteorder = config["dataByteorder"] if config.get("dataByteorder", "") else "big"
# if isinstance(value, int):
# can_data.extend(value.to_bytes(config.get("dataLength", 1),
# byteorder,
# signed=(config.get("dataSigned", False) or value < 0)))
# else:
# can_data.extend(struct.pack(">f" if byteorder[0] == "b" else "<f", value))
# elif isinstance(value, str):
# can_data.extend(value.encode(config["dataEncoding"] if config.get("dataEncoding", "") else "ascii"))
#
# if config.get("dataAfter", ""):
# can_data.extend(bytearray.fromhex(config["dataAfter"]))
#
# return can_data
# except Exception as e:
# log.error("Failed to convert TB data to CAN payload: %s", str(e))
# return
. Output only the next line. | config = {"dataBefore": "00 01 02 03"} |
Using the snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 BACnetUplinkConverter(BACnetConverter):
def __init__(self, config):
self.__config = config
def convert(self, config, data):
value = None
if isinstance(data, ReadPropertyACK):
value = self.__property_value_from_apdu(data)
if config is not None:
datatypes = {"attributes": "attributes",
"timeseries": "telemetry",
<|code_end|>
, determine the next line of code. You have imports:
from bacpypes.apdu import APDU, ReadPropertyACK
from bacpypes.constructeddata import ArrayOf
from bacpypes.primitivedata import Tag
from thingsboard_gateway.connectors.bacnet.bacnet_converter import BACnetConverter, log
and context (class names, function names, or code) available:
# Path: thingsboard_gateway/connectors/bacnet/bacnet_converter.py
# class BACnetConverter(Converter):
# def __init__(self, config):
# def convert(self, config, data):
. Output only the next line. | "telemetry": "telemetry"} |
Next line prediction: <|code_start|> value = self.__property_value_from_apdu(data)
if config is not None:
datatypes = {"attributes": "attributes",
"timeseries": "telemetry",
"telemetry": "telemetry"}
dict_result = {"deviceName": None, "deviceType": None, "attributes": [], "telemetry": []}
dict_result["deviceName"] = self.__config.get("deviceName", config[1].get("name", "BACnet device"))
dict_result["deviceType"] = self.__config.get("deviceType", "default")
dict_result[datatypes[config[0]]].append({config[1]["key"]: value})
else:
dict_result = value
log.debug("%r %r", self, dict_result)
return dict_result
@staticmethod
def __property_value_from_apdu(apdu: APDU):
tag_list = apdu.propertyValue.tagList
non_app_tags = [tag for tag in tag_list if tag.tagClass != Tag.applicationTagClass]
if non_app_tags:
raise RuntimeError("Value has some non-application tags")
first_tag = tag_list[0]
other_type_tags = [tag for tag in tag_list[1:] if tag.tagNumber != first_tag.tagNumber]
if other_type_tags:
raise RuntimeError("All tags must be the same type")
datatype = Tag._app_tag_class[first_tag.tagNumber]
if not datatype:
raise RuntimeError("unknown datatype")
if len(tag_list) > 1:
datatype = ArrayOf(datatype)
value = apdu.propertyValue.cast_out(datatype)
<|code_end|>
. Use current file imports:
(from bacpypes.apdu import APDU, ReadPropertyACK
from bacpypes.constructeddata import ArrayOf
from bacpypes.primitivedata import Tag
from thingsboard_gateway.connectors.bacnet.bacnet_converter import BACnetConverter, log)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/bacnet/bacnet_converter.py
# class BACnetConverter(Converter):
# def __init__(self, config):
# def convert(self, config, data):
. Output only the next line. | return value |
Given the code snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 CanConverter(ABC):
@abstractmethod
def convert(self, config, data):
<|code_end|>
, generate the next line using the imports in this file:
from thingsboard_gateway.connectors.converter import ABC, abstractmethod, log
and context (functions, classes, or occasionally code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | pass |
Next line prediction: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 CanConverter(ABC):
@abstractmethod
def convert(self, config, data):
<|code_end|>
. Use current file imports:
(from thingsboard_gateway.connectors.converter import ABC, abstractmethod, log)
and context including class names, function names, or small code snippets from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | pass |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 SNMPUplinkConverter(Converter):
def __init__(self, config):
self.__config = config
def convert(self, config, data):
<|code_end|>
, predict the next line using imports from the current file:
from thingsboard_gateway.connectors.converter import Converter, log
and context including class names, function names, and sometimes code from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | result = { |
Based on the snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 SNMPUplinkConverter(Converter):
def __init__(self, config):
self.__config = config
def convert(self, config, data):
result = {
"deviceName": self.__config["deviceName"],
"deviceType": self.__config["deviceType"],
"attributes": [],
"telemetry": []
}
try:
if isinstance(data, dict):
<|code_end|>
, predict the immediate next line with the help of imports:
from thingsboard_gateway.connectors.converter import Converter, log
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/converter.py
# class Converter(ABC):
# def convert(self, config, data):
. Output only the next line. | result[config[0]].append({config[1]["key"]: {str(k): str(v) for k, v in data.items()}}) |
Given the code snippet: <|code_start|> super().__init__()
self.loop = None
self.stopped = False
self.name = config['name']
self.device_type = config.get('deviceType', 'default')
self.timeout = config.get('timeout', 10000) / 1000
self.connect_retry = config.get('connectRetry', 5)
self.connect_retry_in_seconds = config.get('connectRetryInSeconds', 0)
self.wait_after_connect_retries = config.get('waitAfterConnectRetries', 0)
self.show_map = config.get('showMap', False)
self.__connector_type = config['connector_type']
self.daemon = True
try:
self.mac_address = self.validate_mac_address(config['MACAddress'])
self.client = BleakClient(self.mac_address)
except ValueError as e:
self.client = None
self.stopped = True
log.error(e)
self.poll_period = config.get('pollPeriod', 5000) / 1000
self.config = {
'extension': config.get('extension', DEFAULT_CONVERTER_CLASS_NAME),
'telemetry': config.get('telemetry', []),
'attributes': config.get('attributes', []),
'attributeUpdates': config.get('attributeUpdates', []),
'serverSideRpc': config.get('serverSideRpc', [])
}
<|code_end|>
, generate the next line using the imports in this file:
from threading import Thread
from platform import system
from time import time, sleep
from bleak import BleakClient
from thingsboard_gateway.connectors.connector import log
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
from thingsboard_gateway.connectors.ble.error_handler import ErrorHandler
import asyncio
and context (functions, classes, or occasionally code) from other files:
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
#
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
# PATHS = []
# LOADED_CONNECTORS = {}
#
# @staticmethod
# def find_paths():
# root_path = path.abspath(path.dirname(path.dirname(__file__)))
# log.debug("Root path is: " + root_path)
# if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
# log.debug("Debian installation extensions folder exists.")
# TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
# TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
# TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
#
# @staticmethod
# def import_module(extension_type, module_name):
# if len(TBModuleLoader.PATHS) == 0:
# TBModuleLoader.find_paths()
# buffered_module_name = extension_type + module_name
# if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
# return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
# try:
# for current_path in TBModuleLoader.PATHS:
# current_extension_path = current_path + path.sep + extension_type
# if path.exists(current_extension_path):
# for file in listdir(current_extension_path):
# if not file.startswith('__') and file.endswith('.py'):
# try:
# module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
# log.debug(module_spec)
#
# if module_spec is None:
# continue
#
# module = module_from_spec(module_spec)
# module_spec.loader.exec_module(module)
# for extension_class in getmembers(module, isclass):
# if module_name in extension_class:
# log.info("Import %s from %s.", module_name, current_extension_path)
# TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
# return extension_class[1]
# except ImportError:
# continue
# except Exception as e:
# log.exception(e)
#
# Path: thingsboard_gateway/connectors/ble/error_handler.py
# class ErrorHandler:
# def __init__(self, e):
# self.e = e
#
# def is_char_not_found(self):
# try:
# if "could not be found!" in self.e.args[0]:
# return True
# except IndexError:
# return False
#
# return False
#
# def is_operation_not_supported(self):
# try:
# if 'not permitted' in self.e.args[1] or 'not supported' in self.e.args[1]:
# return True
# except IndexError:
# return False
#
# return False
. Output only the next line. | self.callback = config['callback'] |
Predict the next line for this snippet: <|code_start|> connect_try += 1
if connect_try == self.connect_retry:
sleep(self.wait_after_connect_retries)
sleep(self.connect_retry_in_seconds)
sleep(.2)
async def notify_callback(self, sender: int, data: bytearray):
not_converted_data = {'telemetry': [], 'attributes': []}
for section in ('telemetry', 'attributes'):
for item in self.config[section]:
if item.get('handle') and item['handle'] == sender:
not_converted_data[section].append({'data': data, **item})
data_for_converter = {
'deviceName': self.name,
'deviceType': self.device_type,
'converter': self.__converter,
'config': {
'attributes': self.config['attributes'],
'telemetry': self.config['telemetry']
},
'data': not_converted_data
}
self.callback(data_for_converter)
async def notify(self, char_id):
await self.client.start_notify(char_id, self.notify_callback)
<|code_end|>
with the help of current file imports:
from threading import Thread
from platform import system
from time import time, sleep
from bleak import BleakClient
from thingsboard_gateway.connectors.connector import log
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
from thingsboard_gateway.connectors.ble.error_handler import ErrorHandler
import asyncio
and context from other files:
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
#
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
# PATHS = []
# LOADED_CONNECTORS = {}
#
# @staticmethod
# def find_paths():
# root_path = path.abspath(path.dirname(path.dirname(__file__)))
# log.debug("Root path is: " + root_path)
# if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
# log.debug("Debian installation extensions folder exists.")
# TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
# TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
# TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
#
# @staticmethod
# def import_module(extension_type, module_name):
# if len(TBModuleLoader.PATHS) == 0:
# TBModuleLoader.find_paths()
# buffered_module_name = extension_type + module_name
# if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
# return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
# try:
# for current_path in TBModuleLoader.PATHS:
# current_extension_path = current_path + path.sep + extension_type
# if path.exists(current_extension_path):
# for file in listdir(current_extension_path):
# if not file.startswith('__') and file.endswith('.py'):
# try:
# module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
# log.debug(module_spec)
#
# if module_spec is None:
# continue
#
# module = module_from_spec(module_spec)
# module_spec.loader.exec_module(module)
# for extension_class in getmembers(module, isclass):
# if module_name in extension_class:
# log.info("Import %s from %s.", module_name, current_extension_path)
# TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
# return extension_class[1]
# except ImportError:
# continue
# except Exception as e:
# log.exception(e)
#
# Path: thingsboard_gateway/connectors/ble/error_handler.py
# class ErrorHandler:
# def __init__(self, e):
# self.e = e
#
# def is_char_not_found(self):
# try:
# if "could not be found!" in self.e.args[0]:
# return True
# except IndexError:
# return False
#
# return False
#
# def is_operation_not_supported(self):
# try:
# if 'not permitted' in self.e.args[1] or 'not supported' in self.e.args[1]:
# return True
# except IndexError:
# return False
#
# return False
, which may contain function names, class names, or code. Output only the next line. | async def __process_self(self): |
Predict the next line after this snippet: <|code_start|> not_converted_data = {'telemetry': [], 'attributes': []}
for section in ('telemetry', 'attributes'):
for item in self.config[section]:
char_id = item['characteristicUUID']
if item['method'] == 'read':
try:
data = await self.client.read_gatt_char(char_id)
not_converted_data[section].append({'data': data, **item})
except Exception as e:
error = ErrorHandler(e)
if error.is_char_not_found() or error.is_operation_not_supported():
log.error(e)
pass
else:
raise e
elif item['method'] == 'notify' and char_id not in self.notifying_chars:
try:
self.__set_char_handle(item, char_id)
self.notifying_chars.append(char_id)
await self.notify(char_id)
except Exception as e:
error = ErrorHandler(e)
if error.is_char_not_found() or error.is_operation_not_supported():
log.error(e)
pass
else:
raise e
if len(not_converted_data['telemetry']) > 0 or len(not_converted_data['attributes']) > 0:
<|code_end|>
using the current file's imports:
from threading import Thread
from platform import system
from time import time, sleep
from bleak import BleakClient
from thingsboard_gateway.connectors.connector import log
from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader
from thingsboard_gateway.connectors.ble.error_handler import ErrorHandler
import asyncio
and any relevant context from other files:
# Path: thingsboard_gateway/connectors/connector.py
# class Connector(ABC):
# def open(self):
# def close(self):
# def get_name(self):
# def is_connected(self):
# def on_attributes_update(self, content):
# def server_side_rpc_handler(self, content):
#
# Path: thingsboard_gateway/tb_utility/tb_loader.py
# class TBModuleLoader:
# PATHS = []
# LOADED_CONNECTORS = {}
#
# @staticmethod
# def find_paths():
# root_path = path.abspath(path.dirname(path.dirname(__file__)))
# log.debug("Root path is: " + root_path)
# if path.exists(DEB_INSTALLATION_EXTENSION_PATH):
# log.debug("Debian installation extensions folder exists.")
# TBModuleLoader.PATHS.append(DEB_INSTALLATION_EXTENSION_PATH)
# TBModuleLoader.PATHS.append(root_path + EXTENSIONS_FOLDER)
# TBModuleLoader.PATHS.append(root_path + CONNECTORS_FOLDER)
#
# @staticmethod
# def import_module(extension_type, module_name):
# if len(TBModuleLoader.PATHS) == 0:
# TBModuleLoader.find_paths()
# buffered_module_name = extension_type + module_name
# if TBModuleLoader.LOADED_CONNECTORS.get(buffered_module_name) is not None:
# return TBModuleLoader.LOADED_CONNECTORS[buffered_module_name]
# try:
# for current_path in TBModuleLoader.PATHS:
# current_extension_path = current_path + path.sep + extension_type
# if path.exists(current_extension_path):
# for file in listdir(current_extension_path):
# if not file.startswith('__') and file.endswith('.py'):
# try:
# module_spec = spec_from_file_location(module_name, current_extension_path + path.sep + file)
# log.debug(module_spec)
#
# if module_spec is None:
# continue
#
# module = module_from_spec(module_spec)
# module_spec.loader.exec_module(module)
# for extension_class in getmembers(module, isclass):
# if module_name in extension_class:
# log.info("Import %s from %s.", module_name, current_extension_path)
# TBModuleLoader.LOADED_CONNECTORS[buffered_module_name] = extension_class[1]
# return extension_class[1]
# except ImportError:
# continue
# except Exception as e:
# log.exception(e)
#
# Path: thingsboard_gateway/connectors/ble/error_handler.py
# class ErrorHandler:
# def __init__(self, e):
# self.e = e
#
# def is_char_not_found(self):
# try:
# if "could not be found!" in self.e.args[0]:
# return True
# except IndexError:
# return False
#
# return False
#
# def is_operation_not_supported(self):
# try:
# if 'not permitted' in self.e.args[1] or 'not supported' in self.e.args[1]:
# return True
# except IndexError:
# return False
#
# return False
. Output only the next line. | data_for_converter = { |
Based on the snippet: <|code_start|># Copyright 2022. ThingsBoard
#
# 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 BytesModbusDownlinkConverter(ModbusConverter):
def __init__(self, config):
self.__config = config
def convert(self, config, data):
byte_order_str = config.get("byteOrder", "LITTLE")
word_order_str = config.get("wordOrder", "LITTLE")
byte_order = Endian.Big if byte_order_str.upper() == "BIG" else Endian.Little
word_order = Endian.Big if word_order_str.upper() == "BIG" else Endian.Little
repack = config.get("repack", False)
<|code_end|>
, predict the immediate next line with the help of imports:
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadBuilder
from thingsboard_gateway.connectors.modbus.modbus_converter import ModbusConverter, log
and context (classes, functions, sometimes code) from other files:
# Path: thingsboard_gateway/connectors/modbus/modbus_converter.py
# class ModbusConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | builder = BinaryPayloadBuilder(byteorder=byte_order, wordorder=word_order, repack=repack) |
Continue the code snippet: <|code_start|> lower_type = config.get("type", config.get("tag", "error")).lower()
if lower_type == "error":
log.error('"type" and "tag" - not found in configuration.')
variable_size = config.get("objectsCount", config.get("registersCount", config.get("registerCount", 1))) * 16
if lower_type in ["integer", "dword", "dword/integer", "word", "int"]:
lower_type = str(variable_size) + "int"
assert builder_functions.get(lower_type) is not None
builder_functions[lower_type](int(value))
elif lower_type in ["uint", "unsigned", "unsigned integer", "unsigned int"]:
lower_type = str(variable_size) + "uint"
assert builder_functions.get(lower_type) is not None
builder_functions[lower_type](int(value))
elif lower_type in ["float", "double"]:
lower_type = str(variable_size) + "float"
assert builder_functions.get(lower_type) is not None
builder_functions[lower_type](float(value))
elif lower_type in ["coil", "bits", "coils", "bit"]:
assert builder_functions.get("bits") is not None
if variable_size / 8 > 1.0:
builder_functions["bits"](bytes(value, encoding='UTF-8')) if isinstance(value, str) else \
builder_functions["bits"]([int(x) for x in bin(value)[2:]])
else:
return bytes(int(value))
elif lower_type in ["string"]:
assert builder_functions.get("string") is not None
builder_functions[lower_type](value)
elif lower_type in builder_functions and 'int' in lower_type:
builder_functions[lower_type](int(value))
<|code_end|>
. Use current file imports:
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadBuilder
from thingsboard_gateway.connectors.modbus.modbus_converter import ModbusConverter, log
and context (classes, functions, or code) from other files:
# Path: thingsboard_gateway/connectors/modbus/modbus_converter.py
# class ModbusConverter(Converter):
# def convert(self, config, data):
. Output only the next line. | elif lower_type in builder_functions and 'float' in lower_type: |
Given 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.
class OdbcUplinkConverterTests(unittest.TestCase):
def setUp(self):
self.converter = OdbcUplinkConverter()
self.db_data = {"boolValue": True,
"intValue": randint(0, 256),
"floatValue": uniform(-3.1415926535, 3.1415926535),
"stringValue": "".join(choice(ascii_lowercase) for _ in range(8))}
def test_glob_matching(self):
converted_data = self.converter.convert("*", self.db_data)
self.assertDictEqual(converted_data, self.db_data)
def test_data_subset(self):
config = ["floatValue", "boolValue"]
converted_data = self.converter.convert(config, self.db_data)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from random import randint, uniform, choice
from string import ascii_lowercase
from thingsboard_gateway.connectors.odbc.odbc_uplink_converter import OdbcUplinkConverter
and context:
# Path: thingsboard_gateway/connectors/odbc/odbc_uplink_converter.py
# class OdbcUplinkConverter(OdbcConverter):
# def convert(self, config, data):
# if isinstance(config, str) and config == "*":
# return data
#
# converted_data = {}
# for config_item in config:
# try:
# if isinstance(config_item, str):
# converted_data[config_item] = data[config_item]
# elif isinstance(config_item, dict):
# if "nameExpression" in config_item:
# name = eval(config_item["nameExpression"], globals(), data)
# else:
# name = config_item["name"]
#
# if "column" in config_item:
# converted_data[name] = data[config_item["column"]]
# elif "value" in config_item:
# converted_data[name] = eval(config_item["value"], globals(), data)
# else:
# log.error("Failed to convert SQL data to TB format: no column/value configuration item")
# else:
# log.error("Failed to convert SQL data to TB format: unexpected configuration type '%s'",
# type(config_item))
# except Exception as e:
# log.error("Failed to convert SQL data to TB format: %s", str(e))
#
# if data.get('ts'):
# converted_data['ts'] = data.get('ts')
#
# return converted_data
which might include code, classes, or functions. Output only the next line. | expected_data = {} |
Based on the snippet: <|code_start|>"""
Goal: expose one method for getting a logger
"""
CONFIG_FILE = 'config/logs.cfg'
def get_figlet(name):
if 'hasher.py' in name:
return """
_ _ _
| | | | __ _ ___| |__ ___ _ __
| |_| |/ _` / __| '_ \ / _ \ '__|
| _ | (_| \__ \ | | | __/ |
|_| |_|\__,_|___/_| |_|\___|_| {}
"""
if 'linker.py' in name:
return """
_ _ _
| | (_)_ __ | | _____ _ __
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import logging
import logging.config
from onefl.version import __version__
and context (classes, functions, sometimes code) from other files:
# Path: onefl/version.py
# DEFAULT_VERISON = '0.0.6'
. Output only the next line. | | | | | '_ \| |/ / _ \ '__| |
Given the code snippet: <|code_start|> opt_ask = '--ask' if ask else ''
ctx.run('PYTHONPATH=. python run/hasher.py -i {} -o {} {}'
.format(inputfolder, outputfolder, opt_ask))
@task
def demo(ctx, ask=True):
""" Generate hashes from PHI """
inputfolder = '.'
outputfolder = '.'
opt_ask = '--ask' if ask else ''
ctx.run('PYTHONPATH=. python run/hasher.py -i {} -o {} {}'
.format(inputfolder, outputfolder, opt_ask))
@task(aliases=['link'],
help={'partner': 'The partner name: {}'.format(VALID_PARTNERS)})
def linker(ctx, partner, ask=True):
""" Generate OneFlorida Ids from hashes """
inputfolder = 'data'
outputfolder = 'data'
opt_ask = '--ask' if ask else ''
if partner:
ctx.run('PYTHONPATH=. python run/linker.py -i {} -o {} -p {} {}'
.format(inputfolder, outputfolder, partner, opt_ask))
else:
print("""
<|code_end|>
, generate the next line using the imports in this file:
from invoke import task
from onefl.partner_name import PartnerName # noqa
from onefl.partner_name import VALID_PARTNERS
and context (functions, classes, or occasionally code) from other files:
# Path: onefl/partner_name.py
# class PartnerName(Enum):
# """
# 3-letter partner names
# """
# HCN = 'HCN' # Health Choice Network
# BND = 'BND' # Bond Community Hospital
# UMI = 'UMI' # University of Miami
#
# FLM = 'FLM' # Florida Medicaid Claims (aka ICHP)
# CHP = 'CHP' # Capital Health Plan Claims
#
# UFH = 'UFH' # University of Florida Health
# TMC = 'TMC' # Tallahassee Memorial Hospital - Cerner
# TMA = 'TMA' # Tallahassee Memorial Hospital - Allscripts
# ORH = 'ORH' # Orlando Health
#
# FLH = 'FLH' # Florida Hospital
# MCH = 'MCH' # Miami Children's Hospital
#
# Path: onefl/partner_name.py
# VALID_PARTNERS = [p.value for p in list(PartnerName)]
. Output only the next line. | Usage: |
Given the code snippet: <|code_start|> opt_ask = '--ask' if ask else ''
ctx.run('PYTHONPATH=. python run/hasher.py -i {} -o {} {}'
.format(inputfolder, outputfolder, opt_ask))
@task
def demo(ctx, ask=True):
""" Generate hashes from PHI """
inputfolder = '.'
outputfolder = '.'
opt_ask = '--ask' if ask else ''
ctx.run('PYTHONPATH=. python run/hasher.py -i {} -o {} {}'
.format(inputfolder, outputfolder, opt_ask))
@task(aliases=['link'],
help={'partner': 'The partner name: {}'.format(VALID_PARTNERS)})
def linker(ctx, partner, ask=True):
""" Generate OneFlorida Ids from hashes """
inputfolder = 'data'
outputfolder = 'data'
opt_ask = '--ask' if ask else ''
if partner:
ctx.run('PYTHONPATH=. python run/linker.py -i {} -o {} -p {} {}'
.format(inputfolder, outputfolder, partner, opt_ask))
else:
print("""
<|code_end|>
, generate the next line using the imports in this file:
from invoke import task
from onefl.partner_name import PartnerName # noqa
from onefl.partner_name import VALID_PARTNERS
and context (functions, classes, or occasionally code) from other files:
# Path: onefl/partner_name.py
# class PartnerName(Enum):
# """
# 3-letter partner names
# """
# HCN = 'HCN' # Health Choice Network
# BND = 'BND' # Bond Community Hospital
# UMI = 'UMI' # University of Miami
#
# FLM = 'FLM' # Florida Medicaid Claims (aka ICHP)
# CHP = 'CHP' # Capital Health Plan Claims
#
# UFH = 'UFH' # University of Florida Health
# TMC = 'TMC' # Tallahassee Memorial Hospital - Cerner
# TMA = 'TMA' # Tallahassee Memorial Hospital - Allscripts
# ORH = 'ORH' # Orlando Health
#
# FLH = 'FLH' # Florida Hospital
# MCH = 'MCH' # Miami Children's Hospital
#
# Path: onefl/partner_name.py
# VALID_PARTNERS = [p.value for p in list(PartnerName)]
. Output only the next line. | Usage: |
Predict the next line after this snippet: <|code_start|> assert os.path.isfile(os.path.join(output_path, uid + '.png'))
assert os.path.isfile(os.path.join(output_path, uid + '.json'))
shutil.rmtree(output_path)
def test_context_manager_disabled(self):
output_path = tempfile.mkdtemp()
uid = str(uuid.uuid4())
with profiling(enable=False, output_path=output_path, uid=uid, info={'test': 42}) as prof:
def foo():
return
foo()
assert not os.path.isfile(os.path.join(output_path, uid + '.pstats'))
assert not os.path.isfile(os.path.join(output_path, uid + '.dot'))
assert not os.path.isfile(os.path.join(output_path, uid + '.png'))
assert not os.path.isfile(os.path.join(output_path, uid + '.json'))
shutil.rmtree(output_path)
def test_callable_param(self):
output_path = tempfile.mkdtemp()
uid = str(uuid.uuid4())
@profiling(enable=lambda *args, **kwargs: True, output_path=lambda *args, **kwargs: output_path, uid=lambda *args, **kwargs: uid, info=lambda *args, **kwargs: {'test': 42})
def foo():
return
<|code_end|>
using the current file's imports:
import os
import shutil
import tempfile
import uuid
import pytest
import mock
import unittest.mock as mock
from marvin_python_toolbox.common.profiling import profiling
and any relevant context from other files:
# Path: marvin_python_toolbox/common/profiling.py
# class profiling(object):
# def __init__(self, enable=True, output_path='profiling', uid=uuid.uuid4, info=None, sortby='tottime'):
# self.enable = enable
# self.output_path = output_path
# self.uid = uid
# self.info = info
# self.sortby = sortby
#
# self.enable_profiling = enable
#
# def __call__(self, func):
#
# @wraps(func)
# def func_wrapper(*args, **kwargs):
# enable_ = self.enable
# if callable(enable_):
# enable_ = enable_(*args, **kwargs)
# self.enable_profiling = bool(enable_)
#
# if self.enable_profiling:
# self.__enter__()
# response = None
# try:
# response = func(*args, **kwargs)
# except Exception:
# raise
# finally:
# if self.enable_profiling:
# output_path_ = self.output_path
# if callable(output_path_):
# self.output_path = output_path_(*args, **kwargs)
# uid_ = self.uid
# if callable(uid_):
# self.uid = uid_()
# info_ = self.info
# if callable(info_):
# self.info = info_(response, *args, **kwargs)
#
# self.__exit__(None, None, None)
#
# return response
#
# return func_wrapper
#
# def __enter__(self):
# pr = None
# if self.enable_profiling:
# pr = Profile(sortby=self.sortby)
# pr.enable()
# self.pr = pr
# return pr
#
# def __exit__(self, type, value, traceback):
# if self.enable_profiling:
# pr = self.pr
# pr.disable()
# # args accept functions
# output_path = self.output_path
# uid = self.uid
# info = self.info
# if callable(uid):
# uid = uid()
#
# # make sure the output path exists
# if not os.path.exists(output_path): # pragma: no cover
# os.makedirs(output_path, mode=0o774)
#
# # collect profiling info
# stats = pstats.Stats(pr)
# stats.sort_stats(self.sortby)
# info_path = os.path.join(output_path, '{}.json'.format(uid))
# stats_path = os.path.join(output_path, '{}.pstats'.format(uid))
# dot_path = os.path.join(output_path, '{}.dot'.format(uid))
# png_path = os.path.join(output_path, '{}.png'.format(uid))
# if info:
# try:
# with open(info_path, 'w') as fp:
# json.dump(info, fp, indent=2, encoding='utf-8')
# except Exception as e:
# logger.error('An error occurred while saving %s: %s.', info_path, e)
# stats.dump_stats(stats_path)
# # create profiling graph
# try:
# subprocess.call(['gprof2dot', '-f', 'pstats', '-o', dot_path, stats_path])
# subprocess.call(['dot', '-Tpng', '-o', png_path, dot_path])
# pr.image_path = png_path
# except Exception:
# logger.error('An error occurred while creating profiling image! '
# 'Please make sure you have installed GraphViz.')
# logger.info('Saving profiling data (%s)', stats_path[:-7])
. Output only the next line. | foo() |
Predict the next line for this snippet: <|code_start|> del os.environ[data_path_key]
path_ = None
try:
path_ = MarvinData.data_path
except InvalidConfigException:
assert not path_
@mock.patch('marvin_python_toolbox.common.data.check_path')
def test_unable_to_create_path(check_path, data_path_key, data_path):
os.environ[data_path_key] = data_path
check_path.return_value = False
path_ = None
try:
path_ = MarvinData.data_path
except InvalidConfigException:
assert not path_
def test_load_data_from_filesystem(data_path_key, data_path):
data = 'return value'
# If the data was not found try to load from filesystem
with mock.patch('marvin_python_toolbox.common.data.open', create=True) as mock_open:
mock_open.return_value = mock.MagicMock(spec=IOBase)
mocked_fp = mock_open.return_value.__enter__.return_value
mocked_fp.read.return_value = data
content = MarvinData.load_data(os.path.join('named_features', 'brands.json'))
<|code_end|>
with the help of current file imports:
import os
import pytest
import mock
import unittest.mock as mock
from marvin_python_toolbox.common.data import MarvinData
from marvin_python_toolbox.common.exceptions import InvalidConfigException
from io import IOBase
from requests import Response
from requests import Response
and context from other files:
# Path: marvin_python_toolbox/common/data.py
# class MarvinData(with_metaclass(AbstractMarvinData)):
# _key = 'MARVIN_DATA_PATH'
#
# @classmethod
# def get_data_path(cls):
# """
# Read data path from the following sources in order of priority:
#
# 1. Environment variable
#
# If not found raises an exception
#
# :return: str - datapath
# """
# marvin_path = os.environ.get(cls._key)
# if not marvin_path:
# raise InvalidConfigException('Data path not set!')
#
# is_path_created = check_path(marvin_path, create=True)
# if not is_path_created:
# raise InvalidConfigException('Data path does not exist!')
#
# return marvin_path
#
# @classmethod
# def _convert_path_to_key(cls, path):
# if path.startswith(os.path.sep):
# path = os.path.relpath(path, start=cls.data_path)
# return '/'.join(path.split(os.path.sep))
#
# @classmethod
# def load_data(cls, relpath):
# """
# Load data from the following sources in order of priority:
#
# 1. Filesystem
#
# :param relpath: path relative to "data_path"
# :return: str - data content
# """
# filepath = os.path.join(cls.data_path, relpath)
# with open(filepath) as fp:
# content = fp.read()
#
# return content
#
# @classmethod
# def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
# """
# Download file from a given url
# """
#
# local_file_name = local_file_name if local_file_name else url.split('/')[-1]
# filepath = os.path.join(cls.data_path, local_file_name)
#
# if not os.path.exists(filepath) or force:
# try:
# headers = requests.head(url, allow_redirects=True).headers
# length = headers.get('Content-Length')
#
# logger.info("Starting download of {} file with {} bytes ...".format(url, length))
#
# widgets = [
# 'Downloading file please wait...', progressbar.Percentage(),
# ' ', progressbar.Bar(),
# ' ', progressbar.ETA(),
# ' ', progressbar.FileTransferSpeed(),
# ]
# bar = progressbar.ProgressBar(widgets=widgets, max_value=int(length) + chunk_size).start()
#
# r = requests.get(url, stream=True)
#
# with open(filepath, 'wb') as f:
# total_chunk = 0
#
# for chunk in r.iter_content(chunk_size):
# if chunk:
# f.write(chunk)
# total_chunk += chunk_size
# bar.update(total_chunk)
#
# bar.finish()
#
# except:
# if os.path.exists(filepath):
# os.remove(filepath)
#
# raise
#
# return filepath
#
# Path: marvin_python_toolbox/common/exceptions.py
# class InvalidConfigException(ConfigException):
# """
# Invalid Marvin Config Base Exception
# """
, which may contain function names, class names, or code. Output only the next line. | mocked_fp.read.assert_called_once() |
Next line prediction: <|code_start|>
file_path = MarvinData.download_file(file_url, local_file_name='myfile')
assert file_path == '/tmp/data/myfile'
@mock.patch('marvin_python_toolbox.common.data.progressbar')
@mock.patch('marvin_python_toolbox.common.data.requests')
def test_download_file_delete_file_if_exception(mocked_requests, mocked_progressbar):
mocked_requests.get.side_effect = Exception()
with open('/tmp/data/error.json', 'w') as f:
f.write('test')
file_url = 'google.com/error.json'
with pytest.raises(Exception) as excinfo:
file_path = MarvinData.download_file(file_url, force=True)
assert os.path.exists('/tmp/data/error.json') is False
@mock.patch('marvin_python_toolbox.common.data.progressbar.ProgressBar')
@mock.patch('marvin_python_toolbox.common.data.requests')
def test_download_file_write_file_if_content(mocked_requests, mocked_progressbar):
file_url = 'google.com/file.json'
response = mock.Mock(spec=Response)
response.iter_content.return_value = 'x'
mocked_requests.get.return_value = response
mocked_open = mock.mock_open()
with mock.patch('marvin_python_toolbox.common.data.open', mocked_open, create=True):
MarvinData.download_file(file_url, force=True)
<|code_end|>
. Use current file imports:
(import os
import pytest
import mock
import unittest.mock as mock
from marvin_python_toolbox.common.data import MarvinData
from marvin_python_toolbox.common.exceptions import InvalidConfigException
from io import IOBase
from requests import Response
from requests import Response)
and context including class names, function names, or small code snippets from other files:
# Path: marvin_python_toolbox/common/data.py
# class MarvinData(with_metaclass(AbstractMarvinData)):
# _key = 'MARVIN_DATA_PATH'
#
# @classmethod
# def get_data_path(cls):
# """
# Read data path from the following sources in order of priority:
#
# 1. Environment variable
#
# If not found raises an exception
#
# :return: str - datapath
# """
# marvin_path = os.environ.get(cls._key)
# if not marvin_path:
# raise InvalidConfigException('Data path not set!')
#
# is_path_created = check_path(marvin_path, create=True)
# if not is_path_created:
# raise InvalidConfigException('Data path does not exist!')
#
# return marvin_path
#
# @classmethod
# def _convert_path_to_key(cls, path):
# if path.startswith(os.path.sep):
# path = os.path.relpath(path, start=cls.data_path)
# return '/'.join(path.split(os.path.sep))
#
# @classmethod
# def load_data(cls, relpath):
# """
# Load data from the following sources in order of priority:
#
# 1. Filesystem
#
# :param relpath: path relative to "data_path"
# :return: str - data content
# """
# filepath = os.path.join(cls.data_path, relpath)
# with open(filepath) as fp:
# content = fp.read()
#
# return content
#
# @classmethod
# def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
# """
# Download file from a given url
# """
#
# local_file_name = local_file_name if local_file_name else url.split('/')[-1]
# filepath = os.path.join(cls.data_path, local_file_name)
#
# if not os.path.exists(filepath) or force:
# try:
# headers = requests.head(url, allow_redirects=True).headers
# length = headers.get('Content-Length')
#
# logger.info("Starting download of {} file with {} bytes ...".format(url, length))
#
# widgets = [
# 'Downloading file please wait...', progressbar.Percentage(),
# ' ', progressbar.Bar(),
# ' ', progressbar.ETA(),
# ' ', progressbar.FileTransferSpeed(),
# ]
# bar = progressbar.ProgressBar(widgets=widgets, max_value=int(length) + chunk_size).start()
#
# r = requests.get(url, stream=True)
#
# with open(filepath, 'wb') as f:
# total_chunk = 0
#
# for chunk in r.iter_content(chunk_size):
# if chunk:
# f.write(chunk)
# total_chunk += chunk_size
# bar.update(total_chunk)
#
# bar.finish()
#
# except:
# if os.path.exists(filepath):
# os.remove(filepath)
#
# raise
#
# return filepath
#
# Path: marvin_python_toolbox/common/exceptions.py
# class InvalidConfigException(ConfigException):
# """
# Invalid Marvin Config Base Exception
# """
. Output only the next line. | mocked_open.assert_called_once_with('/tmp/data/file.json', 'wb') |
Based on the snippet: <|code_start|># 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.
# from click.testing import CliRunner
try:
except ImportError:
class mocked_ctx(object):
obj = {'base_path': '/tmp'}
@mock.patch('marvin_python_toolbox.management.notebook.sys')
@mock.patch('marvin_python_toolbox.management.notebook.os.system')
def test_notebook(system_mocked, sys_mocked):
ctx = mocked_ctx()
port = 8888
enable_security = False
allow_root = False
<|code_end|>
, predict the immediate next line with the help of imports:
import mock
import unittest.mock as mock
import os
from marvin_python_toolbox.management.notebook import notebook, lab
and context (classes, functions, sometimes code) from other files:
# Path: marvin_python_toolbox/management/notebook.py
# def notebook(ctx, port, enable_security, spark_conf, allow_root):
# notebookdir = os.path.join(ctx.obj['base_path'], 'notebooks')
# command = [
# "SPARK_CONF_DIR={0} YARN_CONF_DIR={0}".format(spark_conf if spark_conf else os.path.join(os.environ["SPARK_HOME"], "conf")),
# 'jupyter', 'notebook',
# '--notebook-dir', notebookdir,
# '--ip', '0.0.0.0',
# '--port', str(port),
# '--no-browser',
# '--config', os.path.join(os.environ["MARVIN_TOOLBOX_PATH"], 'extras', 'notebook_extensions', 'jupyter_notebook_config.py')
# ]
#
# command.append("--NotebookApp.token=") if not enable_security else None
# command.append("--allow-root") if allow_root else None
#
# ret = os.system(' '.join(command))
# sys.exit(ret)
#
# def lab(ctx, port, enable_security, spark_conf):
# notebookdir = os.path.join(ctx.obj['base_path'], 'notebooks')
# command = [
# "SPARK_CONF_DIR={0} YARN_CONF_DIR={0}".format(spark_conf if spark_conf else os.path.join(os.environ["SPARK_HOME"], "conf")),
# 'jupyter-lab',
# '--notebook-dir', notebookdir,
# '--ip', '0.0.0.0',
# '--port', str(port),
# '--no-browser',
# ]
#
# command.append("--NotebookApp.token=") if not enable_security else None
#
# ret = os.system(' '.join(command))
# sys.exit(ret)
. Output only the next line. | spark_conf = '/opt/spark/conf' |
Here is a snippet: <|code_start|>@mock.patch('marvin_python_toolbox.management.notebook.sys')
@mock.patch('marvin_python_toolbox.management.notebook.os.system')
def test_notebook(system_mocked, sys_mocked):
ctx = mocked_ctx()
port = 8888
enable_security = False
allow_root = False
spark_conf = '/opt/spark/conf'
system_mocked.return_value = 1
notebook(ctx, port, enable_security, spark_conf, allow_root)
system_mocked.assert_called_once_with('SPARK_CONF_DIR=/opt/spark/conf YARN_CONF_DIR=/opt/spark/conf jupyter notebook --notebook-dir /tmp/notebooks --ip 0.0.0.0 --port 8888 --no-browser --config ' + os.environ["MARVIN_ENGINE_PATH"] + '/marvin_python_toolbox/extras/notebook_extensions/jupyter_notebook_config.py --NotebookApp.token=')
@mock.patch('marvin_python_toolbox.management.notebook.sys')
@mock.patch('marvin_python_toolbox.management.notebook.os.system')
def test_notebook_with_security(system_mocked, sys_mocked):
ctx = mocked_ctx()
port = 8888
enable_security = True
allow_root = False
spark_conf = '/opt/spark/conf'
system_mocked.return_value = 1
notebook(ctx, port, enable_security, spark_conf, allow_root)
system_mocked.assert_called_once_with('SPARK_CONF_DIR=/opt/spark/conf YARN_CONF_DIR=/opt/spark/conf jupyter notebook --notebook-dir /tmp/notebooks --ip 0.0.0.0 --port 8888 --no-browser --config ' + os.environ["MARVIN_ENGINE_PATH"] + '/marvin_python_toolbox/extras/notebook_extensions/jupyter_notebook_config.py')
<|code_end|>
. Write the next line using the current file imports:
import mock
import unittest.mock as mock
import os
from marvin_python_toolbox.management.notebook import notebook, lab
and context from other files:
# Path: marvin_python_toolbox/management/notebook.py
# def notebook(ctx, port, enable_security, spark_conf, allow_root):
# notebookdir = os.path.join(ctx.obj['base_path'], 'notebooks')
# command = [
# "SPARK_CONF_DIR={0} YARN_CONF_DIR={0}".format(spark_conf if spark_conf else os.path.join(os.environ["SPARK_HOME"], "conf")),
# 'jupyter', 'notebook',
# '--notebook-dir', notebookdir,
# '--ip', '0.0.0.0',
# '--port', str(port),
# '--no-browser',
# '--config', os.path.join(os.environ["MARVIN_TOOLBOX_PATH"], 'extras', 'notebook_extensions', 'jupyter_notebook_config.py')
# ]
#
# command.append("--NotebookApp.token=") if not enable_security else None
# command.append("--allow-root") if allow_root else None
#
# ret = os.system(' '.join(command))
# sys.exit(ret)
#
# def lab(ctx, port, enable_security, spark_conf):
# notebookdir = os.path.join(ctx.obj['base_path'], 'notebooks')
# command = [
# "SPARK_CONF_DIR={0} YARN_CONF_DIR={0}".format(spark_conf if spark_conf else os.path.join(os.environ["SPARK_HOME"], "conf")),
# 'jupyter-lab',
# '--notebook-dir', notebookdir,
# '--ip', '0.0.0.0',
# '--port', str(port),
# '--no-browser',
# ]
#
# command.append("--NotebookApp.token=") if not enable_security else None
#
# ret = os.system(' '.join(command))
# sys.exit(ret)
, which may include functions, classes, or code. Output only the next line. | @mock.patch('marvin_python_toolbox.management.notebook.sys') |
Predict the next line after this snippet: <|code_start|> return json.load(f)
else:
return serializer.load(object_file_path)
def _save_obj(self, object_reference, obj):
if not self._is_remote_calling:
if getattr(self, object_reference, None) is not None:
logger.error("Object {} must be assign only once in each action".format(object_reference))
raise Exception('MultipleAssignException', object_reference)
setattr(self, object_reference, obj)
if self._persistence_mode == 'local':
object_file_path = self._get_object_file_path(object_reference)
logger.info("Saving object to {}".format(object_file_path))
self._serializer_dump(obj, object_file_path)
logger.info("Object {} saved!".format(object_reference))
self._local_saved_objects[object_reference] = object_file_path
def _load_obj(self, object_reference, force=False):
if (getattr(self, object_reference, None) is None and self._persistence_mode == 'local') or force:
object_file_path = self._get_object_file_path(object_reference)
logger.info("Loading object from {}".format(object_file_path))
setattr(self, object_reference, self._serializer_load(object_file_path))
logger.info("Object {} loaded!".format(object_reference))
return getattr(self, object_reference)
def _release_local_saved_objects(self):
for object_reference in self._local_saved_objects.keys():
<|code_end|>
using the current file's imports:
import os
import joblib as serializer
import grpc
import json
from abc import ABCMeta, abstractmethod
from concurrent import futures
from .stubs.actions_pb2 import BatchActionResponse, OnlineActionResponse, ReloadResponse, HealthCheckResponse
from .stubs import actions_pb2_grpc
from .._compatibility import six
from .._logging import get_logger
and any relevant context from other files:
# Path: marvin_python_toolbox/engine_base/stubs/actions_pb2_grpc.py
# class OnlineActionHandlerStub(object):
# class OnlineActionHandlerServicer(object):
# class BatchActionHandlerStub(object):
# class BatchActionHandlerServicer(object):
# def __init__(self, channel):
# def _remote_execute(self, request, context):
# def _remote_reload(self, request, context):
# def _health_check(self, request, context):
# def add_OnlineActionHandlerServicer_to_server(servicer, server):
# def __init__(self, channel):
# def _remote_execute(self, request, context):
# def _remote_reload(self, request, context):
# def _health_check(self, request, context):
# def add_BatchActionHandlerServicer_to_server(servicer, server):
#
# Path: marvin_python_toolbox/_compatibility.py
#
# Path: marvin_python_toolbox/_logging.py
# def get_logger(name, namespace='marvin_python_toolbox',
# log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
# """Build a logger that outputs to a file and to the console,"""
#
# log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
# os.getenv('LOG_LEVEL', log_level))
# log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
# os.getenv('LOG_DIR', log_dir))
#
# logger = logging.getLogger('{}.{}'.format(namespace, name))
# logger.setLevel(log_level)
#
# formatter = logging.Formatter(
# '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#
# # Create a console stream handler
# console_handler = logging.StreamHandler()
# console_handler.setLevel(log_level)
# console_handler.setFormatter(formatter)
# logger.addHandler(console_handler)
#
# try:
# log_path = os.path.abspath(log_dir)
# log_filename = '{name}.{pid}.log'.format(
# name=namespace, pid=os.getpid())
#
# file_path = str(os.path.join(log_path, log_filename))
#
# if not os.path.exists(log_path): # pragma: no cover
# os.makedirs(log_path, mode=774)
#
# # Create a file handler
# file_handler = logging.FileHandler(file_path)
# file_handler.setLevel(log_level)
# file_handler.setFormatter(formatter)
# logger.addHandler(file_handler)
# except OSError as e:
# logger.error('Could not create log file {file}: {error}'.format(
# file=file_path, error=e.strerror))
#
# return logger
. Output only the next line. | logger.info("Removing object {} from memory..".format(object_reference)) |
Given the code snippet: <|code_start|> logger.info("Object {} saved!".format(object_reference))
self._local_saved_objects[object_reference] = object_file_path
def _load_obj(self, object_reference, force=False):
if (getattr(self, object_reference, None) is None and self._persistence_mode == 'local') or force:
object_file_path = self._get_object_file_path(object_reference)
logger.info("Loading object from {}".format(object_file_path))
setattr(self, object_reference, self._serializer_load(object_file_path))
logger.info("Object {} loaded!".format(object_reference))
return getattr(self, object_reference)
def _release_local_saved_objects(self):
for object_reference in self._local_saved_objects.keys():
logger.info("Removing object {} from memory..".format(object_reference))
setattr(self, object_reference, None)
self._local_saved_objects = {}
@classmethod
def retrieve_obj(self, object_file_path):
logger.info("Retrieve object from {}".format(object_file_path))
return serializer.load(object_file_path)
def _remote_reload(self, request, context):
protocol = request.protocol
artifacts = request.artifacts
logger.info("Received message from client with protocol [{}] to reload the [{}] artifacts...".format(protocol, artifacts))
<|code_end|>
, generate the next line using the imports in this file:
import os
import joblib as serializer
import grpc
import json
from abc import ABCMeta, abstractmethod
from concurrent import futures
from .stubs.actions_pb2 import BatchActionResponse, OnlineActionResponse, ReloadResponse, HealthCheckResponse
from .stubs import actions_pb2_grpc
from .._compatibility import six
from .._logging import get_logger
and context (functions, classes, or occasionally code) from other files:
# Path: marvin_python_toolbox/engine_base/stubs/actions_pb2_grpc.py
# class OnlineActionHandlerStub(object):
# class OnlineActionHandlerServicer(object):
# class BatchActionHandlerStub(object):
# class BatchActionHandlerServicer(object):
# def __init__(self, channel):
# def _remote_execute(self, request, context):
# def _remote_reload(self, request, context):
# def _health_check(self, request, context):
# def add_OnlineActionHandlerServicer_to_server(servicer, server):
# def __init__(self, channel):
# def _remote_execute(self, request, context):
# def _remote_reload(self, request, context):
# def _health_check(self, request, context):
# def add_BatchActionHandlerServicer_to_server(servicer, server):
#
# Path: marvin_python_toolbox/_compatibility.py
#
# Path: marvin_python_toolbox/_logging.py
# def get_logger(name, namespace='marvin_python_toolbox',
# log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
# """Build a logger that outputs to a file and to the console,"""
#
# log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
# os.getenv('LOG_LEVEL', log_level))
# log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
# os.getenv('LOG_DIR', log_dir))
#
# logger = logging.getLogger('{}.{}'.format(namespace, name))
# logger.setLevel(log_level)
#
# formatter = logging.Formatter(
# '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#
# # Create a console stream handler
# console_handler = logging.StreamHandler()
# console_handler.setLevel(log_level)
# console_handler.setFormatter(formatter)
# logger.addHandler(console_handler)
#
# try:
# log_path = os.path.abspath(log_dir)
# log_filename = '{name}.{pid}.log'.format(
# name=namespace, pid=os.getpid())
#
# file_path = str(os.path.join(log_path, log_filename))
#
# if not os.path.exists(log_path): # pragma: no cover
# os.makedirs(log_path, mode=774)
#
# # Create a file handler
# file_handler = logging.FileHandler(file_path)
# file_handler.setLevel(log_level)
# file_handler.setFormatter(formatter)
# logger.addHandler(file_handler)
# except OSError as e:
# logger.error('Could not create log file {file}: {error}'.format(
# file=file_path, error=e.strerror))
#
# return logger
. Output only the next line. | message = "Reloaded" |
Given snippet: <|code_start|># coding=utf-8
# Copyright [2017] [B2W Digital]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
except ImportError:
@mock.patch("marvin_python_toolbox.loader.isinstance")
@mock.patch("marvin_python_toolbox.loader.getmembers")
@mock.patch("marvin_python_toolbox.loader.imp.load_source")
def test_load_commands_from_file(load_source_mocked, getmembers_mocked, isinstance_mocked):
path = '/tmp'
load_source_mocked.return_value = 'source'
commands = load_commands_from_file(path)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import mock
import unittest.mock as mock
from marvin_python_toolbox.loader import load_commands_from_file
and context:
# Path: marvin_python_toolbox/loader.py
# def load_commands_from_file(path):
# module = imp.load_source('custom_commands', path)
# commands = [obj for name, obj in getmembers(module) if isinstance(obj, click.core.Command)]
# return commands
which might include code, classes, or functions. Output only the next line. | load_source_mocked.assert_called_once_with('custom_commands', '/tmp') |
Using the snippet: <|code_start|> pr = self.pr
pr.disable()
# args accept functions
output_path = self.output_path
uid = self.uid
info = self.info
if callable(uid):
uid = uid()
# make sure the output path exists
if not os.path.exists(output_path): # pragma: no cover
os.makedirs(output_path, mode=0o774)
# collect profiling info
stats = pstats.Stats(pr)
stats.sort_stats(self.sortby)
info_path = os.path.join(output_path, '{}.json'.format(uid))
stats_path = os.path.join(output_path, '{}.pstats'.format(uid))
dot_path = os.path.join(output_path, '{}.dot'.format(uid))
png_path = os.path.join(output_path, '{}.png'.format(uid))
if info:
try:
with open(info_path, 'w') as fp:
json.dump(info, fp, indent=2, encoding='utf-8')
except Exception as e:
logger.error('An error occurred while saving %s: %s.', info_path, e)
stats.dump_stats(stats_path)
# create profiling graph
try:
subprocess.call(['gprof2dot', '-f', 'pstats', '-o', dot_path, stats_path])
<|code_end|>
, determine the next line of code. You have imports:
import os
import json
import subprocess
import cProfile
import pstats
import uuid
from functools import wraps
from .._compatibility import StringIO
from .._logging import get_logger
and context (class names, function names, or code) available:
# Path: marvin_python_toolbox/_compatibility.py
#
# Path: marvin_python_toolbox/_logging.py
# def get_logger(name, namespace='marvin_python_toolbox',
# log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
# """Build a logger that outputs to a file and to the console,"""
#
# log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
# os.getenv('LOG_LEVEL', log_level))
# log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
# os.getenv('LOG_DIR', log_dir))
#
# logger = logging.getLogger('{}.{}'.format(namespace, name))
# logger.setLevel(log_level)
#
# formatter = logging.Formatter(
# '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#
# # Create a console stream handler
# console_handler = logging.StreamHandler()
# console_handler.setLevel(log_level)
# console_handler.setFormatter(formatter)
# logger.addHandler(console_handler)
#
# try:
# log_path = os.path.abspath(log_dir)
# log_filename = '{name}.{pid}.log'.format(
# name=namespace, pid=os.getpid())
#
# file_path = str(os.path.join(log_path, log_filename))
#
# if not os.path.exists(log_path): # pragma: no cover
# os.makedirs(log_path, mode=774)
#
# # Create a file handler
# file_handler = logging.FileHandler(file_path)
# file_handler.setLevel(log_level)
# file_handler.setFormatter(formatter)
# logger.addHandler(file_handler)
# except OSError as e:
# logger.error('Could not create log file {file}: {error}'.format(
# file=file_path, error=e.strerror))
#
# return logger
. Output only the next line. | subprocess.call(['dot', '-Tpng', '-o', png_path, dot_path]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.