ngram
listlengths 0
67.8k
|
|---|
[
"print(model.summary()) image = cv.imread(filename) image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2]",
"# Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the image to",
"safe_crop(image, x, y) print('Start processing image: {}'.format(filename)) x_test = np.empty((1, img_rows, img_cols, 3),",
"img_cols, 3), dtype=np.float32) x_test[0, :, :, 0:3] = image / 255. out =",
"num_classes from data_generator import random_choice, safe_crop, to_bgr from model import build_model if __name__",
"argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the image to be processed\") args = vars(ap.parse_args())",
"img_cols = 320, 320 channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model()",
"* 0.6 + out * 0.4 ret = ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images')",
"img_rows, img_cols = 320, 320 channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5' model =",
"import keras.backend as K import numpy as np from config import num_classes from",
"model import build_model if __name__ == '__main__': # Parse arguments ap = argparse.ArgumentParser()",
"image: {}'.format(filename)) x_test = np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0, :, :, 0:3]",
"cv2 as cv import keras.backend as K import numpy as np from config",
"255. out = model.predict(x_test) out = np.reshape(out, (img_rows, img_cols, num_classes)) out = np.argmax(out,",
"necessary packages import argparse import os import cv2 as cv import keras.backend as",
"as np from config import num_classes from data_generator import random_choice, safe_crop, to_bgr from",
"random_choice, safe_crop, to_bgr from model import build_model if __name__ == '__main__': # Parse",
"out = model.predict(x_test) out = np.reshape(out, (img_rows, img_cols, num_classes)) out = np.argmax(out, axis=2)",
"dtype=np.float32) x_test[0, :, :, 0:3] = image / 255. out = model.predict(x_test) out",
"image.shape[:2] x, y = random_choice(image_size) image = safe_crop(image, x, y) print('Start processing image:",
"cv import keras.backend as K import numpy as np from config import num_classes",
"= model.predict(x_test) out = np.reshape(out, (img_rows, img_cols, num_classes)) out = np.argmax(out, axis=2) out",
"= np.argmax(out, axis=2) out = to_bgr(out) ret = image * 0.6 + out",
"= image * 0.6 + out * 0.4 ret = ret.astype(np.uint8) if not",
"y) print('Start processing image: {}'.format(filename)) x_test = np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0,",
"packages import argparse import os import cv2 as cv import keras.backend as K",
"(img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x, y = random_choice(image_size) image = safe_crop(image,",
"y = random_choice(image_size) image = safe_crop(image, x, y) print('Start processing image: {}'.format(filename)) x_test",
"build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size",
"ret = ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images') cv.imwrite('images/test_image.png', image) cv.imwrite('images/test_merged.png', ret) cv.imwrite('images/test_out.png', out)",
"as cv import keras.backend as K import numpy as np from config import",
"keras.backend as K import numpy as np from config import num_classes from data_generator",
"{}'.format(filename)) x_test = np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0, :, :, 0:3] =",
"ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the image to be processed\") args",
"/ 255. out = model.predict(x_test) out = np.reshape(out, (img_rows, img_cols, num_classes)) out =",
"from data_generator import random_choice, safe_crop, to_bgr from model import build_model if __name__ ==",
"image = cv.imread(filename) image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x,",
"image_size = image.shape[:2] x, y = random_choice(image_size) image = safe_crop(image, x, y) print('Start",
"filename = args[\"image\"] img_rows, img_cols = 320, 320 channel = 3 model_weights_path =",
"num_classes)) out = np.argmax(out, axis=2) out = to_bgr(out) ret = image * 0.6",
"= argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the image to be processed\") args =",
"as K import numpy as np from config import num_classes from data_generator import",
"= random_choice(image_size) image = safe_crop(image, x, y) print('Start processing image: {}'.format(filename)) x_test =",
"to the image to be processed\") args = vars(ap.parse_args()) filename = args[\"image\"] img_rows,",
"cv.imread(filename) image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x, y =",
":, 0:3] = image / 255. out = model.predict(x_test) out = np.reshape(out, (img_rows,",
"img_cols, num_classes)) out = np.argmax(out, axis=2) out = to_bgr(out) ret = image *",
"= build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC)",
"to_bgr(out) ret = image * 0.6 + out * 0.4 ret = ret.astype(np.uint8)",
"320 channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary()) image",
"import argparse import os import cv2 as cv import keras.backend as K import",
"args[\"image\"] img_rows, img_cols = 320, 320 channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5' model",
"= image / 255. out = model.predict(x_test) out = np.reshape(out, (img_rows, img_cols, num_classes))",
"argparse import os import cv2 as cv import keras.backend as K import numpy",
"build_model if __name__ == '__main__': # Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\",",
"= vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols = 320, 320 channel = 3",
"img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x, y = random_choice(image_size) image = safe_crop(image, x,",
"ret = image * 0.6 + out * 0.4 ret = ret.astype(np.uint8) if",
"3), dtype=np.float32) x_test[0, :, :, 0:3] = image / 255. out = model.predict(x_test)",
"import the necessary packages import argparse import os import cv2 as cv import",
"__name__ == '__main__': # Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to",
"import random_choice, safe_crop, to_bgr from model import build_model if __name__ == '__main__': #",
"from config import num_classes from data_generator import random_choice, safe_crop, to_bgr from model import",
"image = safe_crop(image, x, y) print('Start processing image: {}'.format(filename)) x_test = np.empty((1, img_rows,",
"import cv2 as cv import keras.backend as K import numpy as np from",
"model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image =",
"the image to be processed\") args = vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols",
"np.reshape(out, (img_rows, img_cols, num_classes)) out = np.argmax(out, axis=2) out = to_bgr(out) ret =",
"to be processed\") args = vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols = 320,",
"os import cv2 as cv import keras.backend as K import numpy as np",
"'__main__': # Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the image",
"out * 0.4 ret = ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images') cv.imwrite('images/test_image.png', image) cv.imwrite('images/test_merged.png',",
"= np.reshape(out, (img_rows, img_cols, num_classes)) out = np.argmax(out, axis=2) out = to_bgr(out) ret",
"out = to_bgr(out) ret = image * 0.6 + out * 0.4 ret",
"axis=2) out = to_bgr(out) ret = image * 0.6 + out * 0.4",
"if __name__ == '__main__': # Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path",
"cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x, y = random_choice(image_size) image =",
"random_choice(image_size) image = safe_crop(image, x, y) print('Start processing image: {}'.format(filename)) x_test = np.empty((1,",
"img_rows, img_cols, 3), dtype=np.float32) x_test[0, :, :, 0:3] = image / 255. out",
"= safe_crop(image, x, y) print('Start processing image: {}'.format(filename)) x_test = np.empty((1, img_rows, img_cols,",
"print('Start processing image: {}'.format(filename)) x_test = np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0, :,",
"data_generator import random_choice, safe_crop, to_bgr from model import build_model if __name__ == '__main__':",
"'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image = cv.resize(image, (img_rows,",
"\"--image\", help=\"path to the image to be processed\") args = vars(ap.parse_args()) filename =",
"0:3] = image / 255. out = model.predict(x_test) out = np.reshape(out, (img_rows, img_cols,",
"arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the image to be processed\")",
"to_bgr from model import build_model if __name__ == '__main__': # Parse arguments ap",
"Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the image to be",
"help=\"path to the image to be processed\") args = vars(ap.parse_args()) filename = args[\"image\"]",
"model = build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image = cv.resize(image, (img_rows, img_cols),",
"model.predict(x_test) out = np.reshape(out, (img_rows, img_cols, num_classes)) out = np.argmax(out, axis=2) out =",
"0.4 ret = ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images') cv.imwrite('images/test_image.png', image) cv.imwrite('images/test_merged.png', ret) cv.imwrite('images/test_out.png',",
"K import numpy as np from config import num_classes from data_generator import random_choice,",
"processing image: {}'.format(filename)) x_test = np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0, :, :,",
"image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x, y = random_choice(image_size)",
"import os import cv2 as cv import keras.backend as K import numpy as",
"= cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x, y = random_choice(image_size) image",
":, :, 0:3] = image / 255. out = model.predict(x_test) out = np.reshape(out,",
"np.argmax(out, axis=2) out = to_bgr(out) ret = image * 0.6 + out *",
"cv.INTER_CUBIC) image_size = image.shape[:2] x, y = random_choice(image_size) image = safe_crop(image, x, y)",
"import numpy as np from config import num_classes from data_generator import random_choice, safe_crop,",
"x, y = random_choice(image_size) image = safe_crop(image, x, y) print('Start processing image: {}'.format(filename))",
"model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size =",
"image * 0.6 + out * 0.4 ret = ret.astype(np.uint8) if not os.path.exists('images'):",
"= ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images') cv.imwrite('images/test_image.png', image) cv.imwrite('images/test_merged.png', ret) cv.imwrite('images/test_out.png', out) K.clear_session()",
"= cv.imread(filename) image = cv.resize(image, (img_rows, img_cols), cv.INTER_CUBIC) image_size = image.shape[:2] x, y",
"from model import build_model if __name__ == '__main__': # Parse arguments ap =",
"= image.shape[:2] x, y = random_choice(image_size) image = safe_crop(image, x, y) print('Start processing",
"= np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0, :, :, 0:3] = image /",
"np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0, :, :, 0:3] = image / 255.",
"vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols = 320, 320 channel = 3 model_weights_path",
"x, y) print('Start processing image: {}'.format(filename)) x_test = np.empty((1, img_rows, img_cols, 3), dtype=np.float32)",
"= to_bgr(out) ret = image * 0.6 + out * 0.4 ret =",
"+ out * 0.4 ret = ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images') cv.imwrite('images/test_image.png', image)",
"the necessary packages import argparse import os import cv2 as cv import keras.backend",
"out = np.reshape(out, (img_rows, img_cols, num_classes)) out = np.argmax(out, axis=2) out = to_bgr(out)",
"import build_model if __name__ == '__main__': # Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\",",
"320, 320 channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary())",
"<gh_stars>10-100 # import the necessary packages import argparse import os import cv2 as",
"image to be processed\") args = vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols =",
"x_test[0, :, :, 0:3] = image / 255. out = model.predict(x_test) out =",
"image / 255. out = model.predict(x_test) out = np.reshape(out, (img_rows, img_cols, num_classes)) out",
"(img_rows, img_cols, num_classes)) out = np.argmax(out, axis=2) out = to_bgr(out) ret = image",
"= args[\"image\"] img_rows, img_cols = 320, 320 channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5'",
"safe_crop, to_bgr from model import build_model if __name__ == '__main__': # Parse arguments",
"= 3 model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename)",
"# import the necessary packages import argparse import os import cv2 as cv",
"np from config import num_classes from data_generator import random_choice, safe_crop, to_bgr from model",
"channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary()) image =",
"0.6 + out * 0.4 ret = ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images') cv.imwrite('images/test_image.png',",
"= 320, 320 channel = 3 model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path)",
"out = np.argmax(out, axis=2) out = to_bgr(out) ret = image * 0.6 +",
"x_test = np.empty((1, img_rows, img_cols, 3), dtype=np.float32) x_test[0, :, :, 0:3] = image",
"3 model_weights_path = 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image",
"ap.add_argument(\"-i\", \"--image\", help=\"path to the image to be processed\") args = vars(ap.parse_args()) filename",
"args = vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols = 320, 320 channel =",
"== '__main__': # Parse arguments ap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", help=\"path to the",
"= 'models/model.54-2.2507.hdf5' model = build_model() model.load_weights(model_weights_path) print(model.summary()) image = cv.imread(filename) image = cv.resize(image,",
"be processed\") args = vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols = 320, 320",
"numpy as np from config import num_classes from data_generator import random_choice, safe_crop, to_bgr",
"import num_classes from data_generator import random_choice, safe_crop, to_bgr from model import build_model if",
"config import num_classes from data_generator import random_choice, safe_crop, to_bgr from model import build_model",
"processed\") args = vars(ap.parse_args()) filename = args[\"image\"] img_rows, img_cols = 320, 320 channel",
"* 0.4 ret = ret.astype(np.uint8) if not os.path.exists('images'): os.makedirs('images') cv.imwrite('images/test_image.png', image) cv.imwrite('images/test_merged.png', ret)"
] |
[
"def testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ =",
"cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert exitcode ==",
"see LICENSE for more details. \"\"\" from zipfile import is_zipfile as iszip import",
"cmdLine = ['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert",
"pylint: disable = missing-docstring, invalid-name # pylint: disable = unused-argument, no-member, attribute-defined-outside-init #",
"for more details. \"\"\" from zipfile import is_zipfile as iszip import pytest from",
"= ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode",
"* class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse = True) def allZmExe(self, request): self.zmExe",
"too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c) 2020, <NAME>. All rights reserved. license: BSD",
"3-Clause License, see LICENSE for more details. \"\"\" from zipfile import is_zipfile as",
"= getZmExecutables(), autouse = True) def allZmExe(self, request): self.zmExe = zmExes[request.param] def teardown():",
"unused-wildcard-import # pylint: disable = missing-docstring, invalid-name # pylint: disable = unused-argument, no-member,",
"zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine =",
"tmpdir): cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert exitcode",
"invalid-name # pylint: disable = unused-argument, no-member, attribute-defined-outside-init # pylint: disable = too-many-lines,",
"more details. \"\"\" from zipfile import is_zipfile as iszip import pytest from zm",
"no-member, attribute-defined-outside-init # pylint: disable = too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c) 2020,",
"exitcode = runZm(self, cmdLine)[0] assert exitcode == 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert",
"str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode == 0 assert 'version'",
"license: BSD 3-Clause License, see LICENSE for more details. \"\"\" from zipfile import",
"# pylint: disable = wildcard-import, unused-wildcard-import # pylint: disable = missing-docstring, invalid-name #",
"unused-argument, no-member, attribute-defined-outside-init # pylint: disable = too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c)",
"disable = too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c) 2020, <NAME>. All rights reserved.",
"== 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir):",
"stdout def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _",
"# pylint: disable = missing-docstring, invalid-name # pylint: disable = unused-argument, no-member, attribute-defined-outside-init",
"= unused-argument, no-member, attribute-defined-outside-init # pylint: disable = too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright",
"tmpdir): cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine)",
"= joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine = ['version']",
"cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert",
"zipfile import is_zipfile as iszip import pytest from zm import zipapp from tests.func_utils",
"testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self,",
"= runZm(self, cmdLine)[0] assert exitcode == 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath)",
"disable = unused-argument, no-member, attribute-defined-outside-init # pylint: disable = too-many-lines, too-many-branches, too-many-statements \"\"\"",
"too-many-statements \"\"\" Copyright (c) 2020, <NAME>. All rights reserved. license: BSD 3-Clause License,",
"coding=utf-8 # # pylint: disable = wildcard-import, unused-wildcard-import # pylint: disable = missing-docstring,",
"== 0 assert 'version' in stdout def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd",
"testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert",
"\"\"\" from zipfile import is_zipfile as iszip import pytest from zm import zipapp",
"cmdLine) assert exitcode == 0 assert 'version' in stdout def testSysInfoCmd(self, tmpdir): cmdLine",
"disable = missing-docstring, invalid-name # pylint: disable = unused-argument, no-member, attribute-defined-outside-init # pylint:",
"LICENSE for more details. \"\"\" from zipfile import is_zipfile as iszip import pytest",
"['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode ==",
"str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode == 0 assert 'information'",
"= runZm(self, cmdLine) assert exitcode == 0 assert 'version' in stdout def testSysInfoCmd(self,",
"exitcode == 0 assert 'version' in stdout def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo']",
"0 assert 'version' in stdout def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd =",
"(c) 2020, <NAME>. All rights reserved. license: BSD 3-Clause License, see LICENSE for",
"stdout, _ = runZm(self, cmdLine) assert exitcode == 0 assert 'information' in stdout",
"pylint: disable = wildcard-import, unused-wildcard-import # pylint: disable = missing-docstring, invalid-name # pylint:",
"'version' in stdout def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode,",
"All rights reserved. license: BSD 3-Clause License, see LICENSE for more details. \"\"\"",
"request): self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine",
"disable = wildcard-import, unused-wildcard-import # pylint: disable = missing-docstring, invalid-name # pylint: disable",
"cmdLine)[0] assert exitcode == 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath)",
"0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine",
"pylint: disable = too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c) 2020, <NAME>. All rights",
"2020, <NAME>. All rights reserved. license: BSD 3-Clause License, see LICENSE for more",
"import zipapp from tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse =",
"self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode == 0",
"from zipfile import is_zipfile as iszip import pytest from zm import zipapp from",
"autouse = True) def allZmExe(self, request): self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self, request)",
"exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode == 0 assert 'version' in",
"stdout, _ = runZm(self, cmdLine) assert exitcode == 0 assert 'version' in stdout",
"['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert exitcode == 0 zipAppPath",
"zipapp from tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse = True)",
"exitcode == 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self,",
"request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode = runZm(self,",
"iszip import pytest from zm import zipapp from tests.func_utils import * class TestIndyCmd(object):",
"Copyright (c) 2020, <NAME>. All rights reserved. license: BSD 3-Clause License, see LICENSE",
"= wildcard-import, unused-wildcard-import # pylint: disable = missing-docstring, invalid-name # pylint: disable =",
"assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout,",
"missing-docstring, invalid-name # pylint: disable = unused-argument, no-member, attribute-defined-outside-init # pylint: disable =",
"class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse = True) def allZmExe(self, request): self.zmExe =",
"runZm(self, cmdLine)[0] assert exitcode == 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert",
"zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd =",
"import * class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse = True) def allZmExe(self, request):",
"import pytest from zm import zipapp from tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params",
"request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode =",
"printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode",
"self.cwd = str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert exitcode == 0 zipAppPath =",
"True) def allZmExe(self, request): self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def",
"= zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp']",
"<NAME>. All rights reserved. license: BSD 3-Clause License, see LICENSE for more details.",
"details. \"\"\" from zipfile import is_zipfile as iszip import pytest from zm import",
"= ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert exitcode == 0",
"BSD 3-Clause License, see LICENSE for more details. \"\"\" from zipfile import is_zipfile",
"iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _",
"as iszip import pytest from zm import zipapp from tests.func_utils import * class",
"= True) def allZmExe(self, request): self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown)",
"exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode == 0 assert 'information' in",
"testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self,",
"too-many-branches, too-many-statements \"\"\" Copyright (c) 2020, <NAME>. All rights reserved. license: BSD 3-Clause",
"in stdout def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout,",
"def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0]",
"License, see LICENSE for more details. \"\"\" from zipfile import is_zipfile as iszip",
"@pytest.fixture(params = getZmExecutables(), autouse = True) def allZmExe(self, request): self.zmExe = zmExes[request.param] def",
"runZm(self, cmdLine) assert exitcode == 0 assert 'version' in stdout def testSysInfoCmd(self, tmpdir):",
"\"\"\" Copyright (c) 2020, <NAME>. All rights reserved. license: BSD 3-Clause License, see",
"def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd =",
"is_zipfile as iszip import pytest from zm import zipapp from tests.func_utils import *",
"pytest from zm import zipapp from tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params =",
"assert exitcode == 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def",
"tmpdir): cmdLine = ['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine)",
"['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode ==",
"self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine =",
"getZmExecutables(), autouse = True) def allZmExe(self, request): self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self,",
"pylint: disable = unused-argument, no-member, attribute-defined-outside-init # pylint: disable = too-many-lines, too-many-branches, too-many-statements",
"TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse = True) def allZmExe(self, request): self.zmExe = zmExes[request.param]",
"assert 'version' in stdout def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath())",
"zm import zipapp from tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse",
"= missing-docstring, invalid-name # pylint: disable = unused-argument, no-member, attribute-defined-outside-init # pylint: disable",
"tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse = True) def allZmExe(self,",
"attribute-defined-outside-init # pylint: disable = too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c) 2020, <NAME>.",
"isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd = str(tmpdir.realpath()) exitcode,",
"# # pylint: disable = wildcard-import, unused-wildcard-import # pylint: disable = missing-docstring, invalid-name",
"zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd",
"= str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode == 0 assert",
"def testSysInfoCmd(self, tmpdir): cmdLine = ['sysinfo'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ =",
"str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert exitcode == 0 zipAppPath = joinpath(self.cwd, zipapp.ZIPAPP_NAME)",
"rights reserved. license: BSD 3-Clause License, see LICENSE for more details. \"\"\" from",
"allZmExe(self, request): self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir):",
"= str(tmpdir.realpath()) exitcode = runZm(self, cmdLine)[0] assert exitcode == 0 zipAppPath = joinpath(self.cwd,",
"assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd = str(tmpdir.realpath())",
"assert exitcode == 0 assert 'version' in stdout def testSysInfoCmd(self, tmpdir): cmdLine =",
"# coding=utf-8 # # pylint: disable = wildcard-import, unused-wildcard-import # pylint: disable =",
"reserved. license: BSD 3-Clause License, see LICENSE for more details. \"\"\" from zipfile",
"def allZmExe(self, request): self.zmExe = zmExes[request.param] def teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self,",
"= too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c) 2020, <NAME>. All rights reserved. license:",
"teardown(): printErrorOnFailed(self, request) request.addfinalizer(teardown) def testZipAppCmd(self, tmpdir): cmdLine = ['zipapp'] self.cwd = str(tmpdir.realpath())",
"from zm import zipapp from tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(),",
"import is_zipfile as iszip import pytest from zm import zipapp from tests.func_utils import",
"# pylint: disable = too-many-lines, too-many-branches, too-many-statements \"\"\" Copyright (c) 2020, <NAME>. All",
"# pylint: disable = unused-argument, no-member, attribute-defined-outside-init # pylint: disable = too-many-lines, too-many-branches,",
"from tests.func_utils import * class TestIndyCmd(object): @pytest.fixture(params = getZmExecutables(), autouse = True) def",
"wildcard-import, unused-wildcard-import # pylint: disable = missing-docstring, invalid-name # pylint: disable = unused-argument,",
"_ = runZm(self, cmdLine) assert exitcode == 0 assert 'version' in stdout def",
"joinpath(self.cwd, zipapp.ZIPAPP_NAME) assert isfile(zipAppPath) assert iszip(zipAppPath) def testVersionCmd(self, tmpdir): cmdLine = ['version'] self.cwd",
"= ['version'] self.cwd = str(tmpdir.realpath()) exitcode, stdout, _ = runZm(self, cmdLine) assert exitcode"
] |
[
"= subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user) post_list",
"@csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum:",
"thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not",
"thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum =",
"csrf_protect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout as lgout, authenticate, login",
"if vote.type == \"Up\": vote.delete() response_data['action'] = 'removed' else: vote.type = \"Up\" vote.save()",
"= int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and 0 <= page) or subforum_num_pages ==",
"= thread.parent post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if",
"= subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id,",
"post: thread = post.thread post_list = thread.post_set.order_by('local_id') num = 0 found = False",
"c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread', 'title': 'New Thread', 'submit_btn_text':",
"'form': new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create', } return render(request,",
"Http404 @login_required @csrf_protect def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum =",
"for pt in post_list: if pt == post: found = True break num",
"pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll",
"found = True break num += 1 if found: page = (num/forum.posts_per_page)+1 return",
"else: raise Http404 if not form: form = FormUserLogin() c = { 'forum_id':forum_id,",
"pt == post: found = True break num += 1 if found: page",
"0 found = False for pt in post_list: if pt == post: found",
"thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if",
"redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required @csrf_protect def editPost(request, forum_id,",
"and request.user.is_authenticated() and (not thread.closed or is_mod), 'poll': poll, } return render(request, template,",
"'title': 'Reply Thread', 'submit_btn_text': 'Send', } return render(request, template, c) else: c =",
"post_id=post.local_id) else: report_post_form = FormReportPost() c = { 'forum_id':forum_id, 'form': report_post_form, 'post': post,",
"not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod =",
"= subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list = [] for sf in subforum.child_set.order_by('local_id'): if",
"False) if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id,",
"\"Up\": vote.delete() response_data['action'] = 'removed' else: vote.type = \"Up\" vote.save() response_data['action'] = 'added'",
"= subforum.forum, view_permission = subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission =",
"'POST': form = FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request,",
"request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\", \"\") != \"\": rang = range(0, int(request.POST.get(\"poll_option_count\",",
"def post(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id)",
"raise Http404 @login_required @csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum =",
"'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and",
"= get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): post_old_title",
"subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id)",
"render(request, CANT_VIEW_CONTENT, c) raise Http404 def thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum",
"subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list =",
"FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user = request.user report_post.post = post report_post.save()",
"return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost() c = { 'forum_id':forum_id, 'form':",
"== \"True\" and request.POST.get(\"question\", \"\") != \"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question",
"thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and",
"request.method == 'POST': form = FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if",
"post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for",
"and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content = post.content if request.method == 'POST': if",
"HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id) if",
"None if request.method == 'POST': form = FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'],",
"last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\", \"\") !=",
"thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post =",
"= request.POST.get(\"question\") option_list = [] for i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\")",
"for th in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page = int(page) -1 subforum_num_pages",
"else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added' # Send signal signals.upvote.send(sender=forum, user=request.user, post=post)",
"option_list = [] for i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt",
"return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id)",
"CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum =",
"get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum =",
"Http404 def thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum:",
"subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST,",
"not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list = [] for th in sf_th_set: th.is_visited",
"= post.thread post_list = thread.post_set.order_by('local_id') num = 0 found = False for pt",
"= get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): if",
"if thread_num_pages > page and 0 <= page: set_visit(thread, request.user) thread.visit_counter += 1",
"form, } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c)",
"is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request, template, c) else: c = {",
"or is_mod), 'poll': poll, } return render(request, template, c) else: c = {",
"if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user):",
"if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list",
"raise Http404 @login_required def quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post",
"subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if",
"redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user)",
"from Forum.getInstanceLib import * from Forum.modelsLib import * import Forum.signals as signals from",
"FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id",
"subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user) post_list =",
"} if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c) @login_required",
"template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum:",
"subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list = []",
"= get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id,",
"get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post: thread = post.thread post_list",
"post(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if",
"Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id)",
"post_old_title = post.title post_old_content = post.content if request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form",
"'form': new_post_form, 'page_title': 'New Thread', 'title': 'New Thread', 'submit_btn_text': 'Create', } return render(request,",
"new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send signal new",
"FormUserLogin() c = { 'forum_id':forum_id, 'form': form, } if request.is_ajax(): return render(request, template_ajax,",
"firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id)",
"forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum,",
"c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def thread(request,",
"signal signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent =",
"from Forum.forms import * from Forum.lib import * from Forum.getInstanceLib import * from",
"= subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c",
"'forum_id':forum_id, 'form': report_post_form, 'post': post, } if request.is_ajax(): return render(request, template_ajax, c) else:",
"lgout, authenticate, login as lgin from django.shortcuts import render, redirect from datetime import",
"c) else: return render(request, template, c) raise Http404 @login_required @csrf_protect def reportPost(request, forum_id,",
"if (subforum_num_pages > page and 0 <= page) or subforum_num_pages == 0: c",
"# Create your views here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None",
"is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user)",
"Post() quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quotes_text",
"template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum:",
"template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread: if",
"vote: if vote.type == \"Down\": vote.delete() response_data['action'] = 'removed' elif vote.type == \"Up\":",
"and request.user.is_authenticated(): if request.method == 'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form =",
"\"True\" and request.POST.get(\"question\", \"\") != \"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question =",
"thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden",
"view_permission = subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, )",
"= FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form = FormPost(instance=post) else: c = {",
"* from Forum.settings import * from Forum.forms import * from Forum.lib import *",
"forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form",
"is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): if thread.poll: if",
"django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout as lgout,",
"= PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator =",
"FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user) forum =",
"not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted =",
"if forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): if",
"password=form.data['password']) if user: lgin(request, user) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id)",
"def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug()",
"form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user) forum = get_forum_instance(forum_id) if",
"thread_slug): if page == 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread',",
"forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_down_votes: post = get_post_instance(forum, post_id)",
"(num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required @csrf_protect def",
"thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def saveThreadSettings(request, forum_id,",
"if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user = request.user report_post.post = post report_post.save() return",
"else: return render(request, template, c) raise Http404 @login_required @csrf_protect def reportPost(request, forum_id, post_id,",
"new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum = forum new_subforum.creator = request.user",
"@login_required def votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_up_votes: post",
"response_data = {} if quote: quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save()",
"= 'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added' # Send signal signals.downvote.send(sender=forum,",
"edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='',",
"Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum:",
"if not form: form = FormUserLogin() c = { 'forum_id':forum_id, 'form': form, }",
"forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post() quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread)",
"if page == 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id,",
"subforum = thread.parent post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') for pt in unfiltered_post_list:",
"thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum: thread =",
"post = edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if post.title == \"\": post.title =",
"sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user):",
"new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send signal new post published signals.post_published.send(sender=forum,",
"from django.contrib.auth.decorators import login_required from django.contrib.auth import logout as lgout, authenticate, login as",
"user=request.user, post=post) if not post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent = True post.save()",
"{ 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send', }",
"thread.hidden or is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and request.method == 'POST': answer =",
"Create your views here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if",
"render(request, template_ajax, c) else: return render(request, template, c) raise Http404 @login_required @csrf_protect def",
"= FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent =",
"new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum = forum new_subforum.creator = request.user new_subforum.save()",
"post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data = {} if quote: quote.delete() response_data['action'] =",
"== post: if post.title == \"\": post.title = post_old_title post.thread.name = post.title post.thread.save()",
"get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug, page, template=template)",
"Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post",
"post_id) if post: thread = post.thread post_list = thread.post_set.order_by('local_id') num = 0 found",
"login as lgin from django.shortcuts import render, redirect from datetime import datetime from",
"'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form =",
"if forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form)",
"get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data = {}",
"{ 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def replyThread(request,",
"def subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum",
"{ 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def thread(request, forum_id, thread_id,",
"= new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user,",
"'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request,",
"for i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\": option_list.append(opt)",
"-*- coding: utf-8 -*- import json from django.http import Http404, HttpResponse from django.views.decorators.csrf",
"post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher",
"if thread: if not check_slug(thread, thread_slug): if page == 1: return redirect('Forum.views.thread', forum_id=forum_id,",
"thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form': form, 'thread':",
"redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and",
"report_post_form, 'post': post, } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request,",
"# -*- coding: utf-8 -*- import json from django.http import Http404, HttpResponse from",
"not check_slug(thread, thread_slug): if page == 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else:",
"FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save()",
"= template_ajax c = { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else: c =",
"quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else:",
"forum = get_forum_instance(forum_id) if forum and forum.allow_up_votes: post = get_post_instance(forum, post_id) if post",
"thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form': form, 'thread': thread,",
"def votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_down_votes: post =",
"datetime from Forum.models import * from Forum.settings import * from Forum.forms import *",
"votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_down_votes: post = get_post_instance(forum,",
"= get_forum_instance(forum_id) if forum and forum.allow_down_votes: post = get_post_instance(forum, post_id) if post and",
"type=\"Down\").save() response_data['action'] = 'added' # Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent",
"response_data = {} if vote: if vote.type == \"Up\": vote.delete() response_data['action'] = 'removed'",
"{ 'forum_id':forum_id, 'form': form, 'thread': thread, } return render(request, template, c) raise Http404",
"Thread', 'title': 'New Thread', 'submit_btn_text': 'Create', } return render(request, template, c) else: c",
"request.user.is_authenticated(), } return render(request, template, c) else: c = { 'forum_id':forum_id, } return",
"\"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post)",
"subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if",
"new_post.thread=thread new_post.save() # Send signal new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list",
"from math import ceil # Create your views here. def login(request, forum_id, template=\"Forum/forms/login.html\",",
"new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum = subforum.forum,",
"editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post =",
"page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread:",
"quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form =",
"* from Forum.modelsLib import * import Forum.signals as signals from math import ceil",
"json from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import",
"reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form': new_subforum_form,",
"= int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and 0 <= page: set_visit(thread, request.user) thread.visit_counter",
"response_data['action'] = 'added' # Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and",
"if forum: return redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if not form: form =",
"subforum new_subforum.forum = forum new_subforum.creator = request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug())",
"form, 'thread': thread, } return render(request, template, c) raise Http404 @login_required def firstPostUnreadThread(request,",
"= forum new_subforum.creator = request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum",
"saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum,",
"forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\",",
"= Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id =",
"'New Thread', 'title': 'New Thread', 'submit_btn_text': 'Create', } return render(request, template, c) else:",
"@login_required def votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_down_votes: post",
"page == 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id,",
"= FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user = request.user report_post.post = post",
"Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added' # Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if",
"\"Down\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added' #",
"unfiltered_post_list = thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt)",
"subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(),",
"= { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request, forum_id,",
"= request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def",
"thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): can_post =",
"post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form =",
"Forum.modelsLib import * import Forum.signals as signals from math import ceil # Create",
"else: form = FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form': form, 'thread': thread, }",
"check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod = subforum.canModerate(request.user)",
"def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum,",
"subforum.canCreateThread(request.user) subforum_list = [] for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user)",
"= get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id,",
"answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id): forum = get_forum_instance(forum_id)",
"thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id,",
"post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False)",
"(not thread.hidden or is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and request.method == 'POST': answer",
"page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug() return subforum(request, forum_id,",
"subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and 0 <= page) or subforum_num_pages",
"1 thread.save() c = { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3,",
"1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page)",
"new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent",
"poll = None page = int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages >",
"forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post() new_post_form = FormNewThread(instance=new_post) c = {",
"= sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set =",
"thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list = [] unfiltered_post_list",
"new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum,",
"signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent = True",
"thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id)",
"not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list =",
">= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new thread signal",
"forum = get_forum_instance(forum_id) if forum and forum.allow_down_votes: post = get_post_instance(forum, post_id) if post",
"= post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if post.thread.post_set.first() == post:",
"thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum",
"return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id,",
"request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST,",
"'poll': poll, } return render(request, template, c) else: c = { 'forum_id':forum_id, }",
"post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if (not pt.hidden)",
"if thread.poll.userCanVote(request.user) and request.method == 'POST': answer = request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user,",
"'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(),",
"Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send', } return render(request, template, c) else: c",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form': form,",
"forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if",
"check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method == 'POST'):",
"'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not thread.closed or is_mod), 'poll': poll,",
"'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def newSubforum(request, forum_id,",
"from django.contrib.auth import logout as lgout, authenticate, login as lgin from django.shortcuts import",
"(subforum_num_pages > page and 0 <= page) or subforum_num_pages == 0: c =",
"template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread",
"user: lgin(request, user) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) else: raise",
"def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method == 'POST': form",
"thread_num_pages > page and 0 <= page: set_visit(thread, request.user) thread.visit_counter += 1 thread.save()",
"return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum = subforum.forum, view_permission",
"} return render(request, template, c) else: c = { 'forum_id':forum_id, } return render(request,",
"= Post() quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list:",
"= FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form': form, 'thread': thread, } return render(request,",
"forum_id=forum.local_id) raise Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum:",
"vote.delete() response_data['action'] = 'removed' elif vote.type == \"Up\": vote.type = \"Down\" vote.save() response_data['action']",
"if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid():",
"else: vote.type = \"Up\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action']",
"subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list = [] for sf in",
"and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll = None page =",
"@login_required @csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if",
"= post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost() c =",
"subforum_id) if subforum: if not check_slug(subforum, subforum_slug): if page == 1: return redirect('Forum.views.subforum',",
"user) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if",
"<= page: set_visit(thread, request.user) thread.visit_counter += 1 thread.save() c = { 'forum_id':forum_id, 'thread':",
"'POST': answer = request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id,",
"int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and 0 <= page)",
"get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): if request.method",
"old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if post.thread.post_set.first()",
"thread_slug=thread.slug()) def post(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum,",
"redirect from datetime import datetime from Forum.models import * from Forum.settings import *",
"'-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list = [] for th",
"c) raise Http404 @login_required @csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum",
"thread, } return render(request, template, c) raise Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id,",
"subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form':",
"} else: c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply",
"else: report_post_form = FormReportPost() c = { 'forum_id':forum_id, 'form': report_post_form, 'post': post, }",
"if thread and (not thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread',",
"+= 1 if found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page,",
"= get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if not form:",
"= get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form =",
"raise Http404 def thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if",
"if request.method == 'POST': new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid():",
"return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list = [] unfiltered_post_list =",
"c) else: return render(request, template, c) @login_required def logout(request, forum_id): lgout(request) forum =",
"request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\": option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question, option_list)",
"forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): if page",
"new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create', } return render(request, template,",
"thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method == 'POST'): form",
"post and post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post",
"check_slug(thread, thread_slug): if page == 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return",
"template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method == 'POST': form = FormUserLogin(request.POST) if form.is_valid():",
"if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method",
"if request.method == 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid():",
"request.user: edit_post_form = FormPost(instance=post) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT,",
"request.is_ajax(): template = template_ajax c = { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else:",
"= get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data =",
"vote.delete() response_data['action'] = 'removed' else: vote.type = \"Up\" vote.save() response_data['action'] = 'added' else:",
"if forum and forum.allow_up_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote",
"user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post",
"'page_title': 'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send', } return render(request, template, c)",
"redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if",
"== \"Up\": vote.type = \"Down\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Down\").save()",
"report_post.user = request.user report_post.post = post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form",
"post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited",
"template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if",
"quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id)",
"if post.thread.post_set.first() == post: if post.title == \"\": post.title = post_old_title post.thread.name =",
"= get_forum_instance(forum_id) if forum and forum.allow_up_votes: post = get_post_instance(forum, post_id) if post and",
"post, } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c)",
"forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_up_votes: post = get_post_instance(forum, post_id)",
"page) or subforum_num_pages == 0: c = { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page],",
"c) raise Http404 @login_required @csrf_protect def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user)",
"forum: subforum_slug = forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug, page, template=template) raise Http404",
"# Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else:",
"subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form",
"pt in post_list: if pt == post: found = True break num +=",
"else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod = subforum.canModerate(request.user)",
"def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post",
"= \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\"",
"elif vote.type == \"Up\": vote.type = \"Down\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user,",
"request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll = None page",
"raise Http404 @login_required @csrf_protect def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum",
"= report_post_form.save(commit=False) report_post.user = request.user report_post.post = post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id)",
"redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum =",
"new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send signal new post published",
"new_subforum.parent = subforum new_subforum.forum = forum new_subforum.creator = request.user new_subforum.save() return redirect('subforum', forum_id=forum_id,",
"# Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() >= forum.positive_score_event:",
"= { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send',",
"new_post_form = FormPost(instance=new_post) if request.is_ajax(): template = template_ajax c = { 'forum_id':forum_id, 'form':",
") post = edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if post.title == \"\": post.title",
"{ 'forum_id':forum_id, 'form': report_post_form, 'post': post, } if request.is_ajax(): return render(request, template_ajax, c)",
"Forum.getInstanceLib import * from Forum.modelsLib import * import Forum.signals as signals from math",
"if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id):",
"thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if",
"votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_up_votes: post = get_post_instance(forum,",
"get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE):",
"and (not thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list =",
"subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id,",
"0 <= page: set_visit(thread, request.user) thread.visit_counter += 1 thread.save() c = { 'forum_id':forum_id,",
"forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required @csrf_protect def editPost(request, forum_id, post_id,",
"page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def",
"import Http404, HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from django.contrib.auth",
"Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added' # Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if",
"def quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id)",
"math import ceil # Create your views here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"):",
"forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not",
"= get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): if page == 1:",
"} return render(request, CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission,",
"if subforum.canCreateThread(request.user): if request.method == 'POST': new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post)",
"Forum.forms import * from Forum.lib import * from Forum.getInstanceLib import * from Forum.modelsLib",
"1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not thread.closed or",
"= range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list = [] for i in",
"= thread.poll_set.first() else: poll = None page = int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page)))",
"django.shortcuts import render, redirect from datetime import datetime from Forum.models import * from",
"redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user):",
"return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug):",
"can_create_thread = subforum.canCreateThread(request.user) subforum_list = [] for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited",
"if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list = [] for sf",
"quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data),",
"= True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404",
"in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page = int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page)))",
"Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum:",
"(not thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data",
"page and 0 <= page: set_visit(thread, request.user) thread.visit_counter += 1 thread.save() c =",
"'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404",
"request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c) raise Http404 @login_required",
"thread.poll_set.first() else: poll = None page = int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if",
"django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from",
"from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout as",
"subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True)",
"quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quotes_text +=",
"c) raise Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id)",
"new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote",
"or is_mod): can_post = subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') if not",
"thread.parent post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if (not",
"} if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c) raise",
"forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage',",
"lgin from django.shortcuts import render, redirect from datetime import datetime from Forum.models import",
"signals from math import ceil # Create your views here. def login(request, forum_id,",
"return render(request, template_ajax, c) else: return render(request, template, c) @login_required def logout(request, forum_id):",
"Http404 def subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum:",
"forum = subforum.forum, view_permission = subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission",
"if request.method == 'POST': form = FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password'])",
"redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread,",
"pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt)",
"get_vote_instance(request.user, post) response_data = {} if vote: if vote.type == \"Up\": vote.delete() response_data['action']",
"get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread and (not thread.closed or",
"template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if",
"elif post.publisher == request.user: edit_post_form = FormPost(instance=post) else: c = { 'forum_id':forum_id, }",
"def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post",
"c) raise Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if",
"subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method == 'POST': new_post = Post(publisher=request.user) new_post_form =",
"'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and",
"render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum",
"thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id,",
"'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not thread.closed or is_mod), 'poll': poll, } return",
"redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"):",
"reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post =",
"and forum.allow_down_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user,",
"forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug() return",
"import * from Forum.forms import * from Forum.lib import * from Forum.getInstanceLib import",
"= get_vote_instance(request.user, post) response_data = {} if vote: if vote.type == \"Up\": vote.delete()",
"'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send', } return render(request, template, c) else:",
"= None if request.method == 'POST': form = FormUserLogin(request.POST) if form.is_valid(): user =",
"last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required",
"user = authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user) forum = get_forum_instance(forum_id) if forum:",
"post.thread.name = post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user):",
"CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"):",
"> page and 0 <= page: set_visit(thread, request.user) thread.visit_counter += 1 thread.save() c",
"if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not",
"= { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def",
"subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if",
"user_is_administrator = forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if post.title",
"Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count()",
"template=template) raise Http404 def subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id)",
"= FormUserLogin() c = { 'forum_id':forum_id, 'form': form, } if request.is_ajax(): return render(request,",
"report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user = request.user report_post.post = post report_post.save() return redirect('Forum.views.post',",
"thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method ==",
"= get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first()",
"edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited =",
"render, redirect from datetime import datetime from Forum.models import * from Forum.settings import",
"return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher ==",
"if pt == post: found = True break num += 1 if found:",
"quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content =",
"redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher == request.user:",
"forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: thread =",
"thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll = None page = int(page) -1 thread_num_pages",
"'POST'): form = FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"c = { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else: c = { 'forum_id':forum_id,",
"vote.type == \"Up\": vote.type = \"Down\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post,",
"} return render(request, template, c) raise Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug):",
"page and 0 <= page) or subforum_num_pages == 0: c = { 'forum_id':forum_id,",
"None page = int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and",
"{ 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id, 'form': edit_post_form,",
"= forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send signal new post published signals.post_published.send(sender=forum, post=new_post)",
"signal signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent =",
"'form': new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send', } return render(request,",
"!= \"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list = []",
"get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if not form: form",
"= Subforum( forum = subforum.forum, view_permission = subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission =",
"forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod",
"if forum: thread = get_thread_instance(forum, thread_id) if thread and (not thread.closed or thread.parent.canModerate(request.user)):",
"return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id)",
"if request.method == 'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user",
"{ 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user),",
"template_ajax, c) else: return render(request, template, c) raise Http404 @login_required @csrf_protect def reportPost(request,",
"def threadLastPage(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum,",
"quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if request.is_ajax(): template",
"if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum =",
"= get_quote_instance(request.user, post) response_data = {} if quote: quote.delete() response_data['action'] = 'removed' else:",
"= quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if request.is_ajax():",
"= int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404",
"'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request, forum_id, thread_id, thread_slug):",
"c) raise Http404 def threadLastPage(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum:",
"'Create', } return render(request, template, c) else: c = { 'forum_id':forum_id, } return",
"else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def",
"forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum =",
"check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method == 'POST':",
"= get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id,",
"{ 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return render(request, template_ajax,",
"post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll =",
"new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum,",
"thread_slug=new_thread.slug()) else: new_post = Post() new_post_form = FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form':",
"lgout(request) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request,",
"not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if",
"new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum = forum",
"if not check_slug(subforum, subforum_slug): if page == 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug())",
"replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: thread",
"thread.save() c = { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)),",
"redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form':",
"request.POST.get(\"question\") option_list = [] for i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if",
"CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if",
"can_post = subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list",
"= { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id, 'form':",
"if vote.type == \"Down\": vote.delete() response_data['action'] = 'removed' elif vote.type == \"Up\": vote.type",
"published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list:",
"= int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and 0 <=",
"raise Http404 @login_required def votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and",
"new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send signal",
"post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostDown(request, forum_id, post_id): forum =",
"post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_up_votes: post = get_post_instance(forum, post_id) if",
"template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if",
"check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method == 'POST':",
"instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id =",
"subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list = [] for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user):",
"c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect",
"template, c) raise Http404 @login_required @csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user)",
"c = { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)),",
"min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request, template,",
"not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method ==",
"int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and 0 <= page) or subforum_num_pages == 0:",
"form: form = FormUserLogin() c = { 'forum_id':forum_id, 'form': form, } if request.is_ajax():",
"FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create Subforum',",
"'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create', } return render(request, template, c) else:",
"redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug,",
"'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not",
"\"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content",
"len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new thread",
"thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread: if",
"subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method == 'POST': new_post",
"= {} if quote: quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action']",
"'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send', } return",
"thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if last_visit: last_post",
"subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): if page ==",
"thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id)",
"'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def replyThread(request, forum_id,",
"request.user.is_authenticated(): if request.method == 'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST,",
"= { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod,",
"if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if request.is_ajax(): template =",
"post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id)",
"thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent",
"FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited = PostEdited( post=post,",
"post: if post.title == \"\": post.title = post_old_title post.thread.name = post.title post.thread.save() post_edited.save()",
"thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method == 'POST': new_post = Post(publisher=request.user)",
"def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum: thread =",
"post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content =",
"render(request, CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id)",
"get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form = FormReportPost(request.POST)",
"= get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id,",
"not post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score']",
"return render(request, template, c) raise Http404 @login_required def quotePost(request, forum_id, post_id): forum =",
"return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread =",
"return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method == 'POST'): form =",
"and request.method == 'POST': answer = request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer) return",
") new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\", \"\") != \"\": rang",
"in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post() quotes_text =",
"forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum',",
"= Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post)",
"\"Up\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added' #",
"thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id): forum =",
"datetime import datetime from Forum.models import * from Forum.settings import * from Forum.forms",
"if len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new",
"FormPost(instance=new_post) if request.is_ajax(): template = template_ajax c = { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread,",
"num += 1 if found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(),",
"0 <= page) or subforum_num_pages == 0: c = { 'forum_id':forum_id, 'forum': subforum,",
"thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if",
"@csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum:",
"template_ajax c = { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else: c = {",
"get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug):",
"'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create', } return",
"template, c) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise",
"== request.user: edit_post_form = FormPost(instance=post) else: c = { 'forum_id':forum_id, } return render(request,",
"= subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): if thread.poll: if thread.poll.userCanVote(request.user)",
"forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum,",
"thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit",
"= {} if vote: if vote.type == \"Down\": vote.delete() response_data['action'] = 'removed' elif",
"c) raise Http404 def thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id)",
"if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit =",
"create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c = {",
"'POST': new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False)",
"redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum = subforum.forum, view_permission =",
"render(request, template_ajax, c) else: return render(request, template, c) @login_required def logout(request, forum_id): lgout(request)",
"* from Forum.forms import * from Forum.lib import * from Forum.getInstanceLib import *",
"Http404 if not form: form = FormUserLogin() c = { 'forum_id':forum_id, 'form': form,",
"post.thread.parent.canView(request.user): post_old_title = post.title post_old_content = post.content if request.method == 'POST': if post.thread.parent.canModerate(request.user):",
"thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post",
"if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not",
"if subforum.canView(request.user) and (not thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user) post_list = []",
"return redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if not form: form = FormUserLogin() c",
"= sf_th_set.exclude(hidden=True) thread_list = [] for th in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th)",
"= get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request, forum_id, page=1,",
"1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page)",
"raise Http404 @login_required @csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum =",
"Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post",
"return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post() new_post_form = FormNewThread(instance=new_post) c",
"form = FormUserLogin() c = { 'forum_id':forum_id, 'form': form, } if request.is_ajax(): return",
"(request.method == 'POST'): form = FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id,",
"and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data = {} if quote: quote.delete() response_data['action']",
"vote.type == \"Down\": vote.delete() response_data['action'] = 'removed' elif vote.type == \"Up\": vote.type =",
"{ 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request, forum_id, thread_id,",
"if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): if",
"HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout",
"template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread: if",
"Http404 @login_required def votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_up_votes:",
"subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create",
"post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data = {} if vote: if",
"def votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_up_votes: post =",
"= \"Down\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added'",
"signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent = True",
"newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum =",
"= [] for i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt !=",
"'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post",
"subforum.canView(request.user) and (not thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list",
"form = FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user)",
"'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request, template, c) else:",
"if opt != \"\": option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum",
"forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form",
"forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id)",
"post_list = thread.post_set.order_by('local_id') num = 0 found = False for pt in post_list:",
"} return render(request, CANT_VIEW_CONTENT, c) raise Http404 def thread(request, forum_id, thread_id, thread_slug, page=1,",
"int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list = [] for i in rang: opt",
"page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum:",
"subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request, template, c)",
"subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list = [] for",
"c = { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator':",
"new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if",
"report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost() c = { 'forum_id':forum_id,",
"new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST,",
"in unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page =",
"subforum_slug, page, template=template) raise Http404 def subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum",
"check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if last_visit:",
"and post.score() <= forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score'] = post.score()",
"'post': post, } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template,",
"if not post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post)",
"response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostDown(request, forum_id, post_id):",
"your views here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method",
"raise Http404 @login_required def votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and",
"import login_required from django.contrib.auth import logout as lgout, authenticate, login as lgin from",
"else: new_post = Post() quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote",
"post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and",
"import * from Forum.lib import * from Forum.getInstanceLib import * from Forum.modelsLib import",
"Http404 @login_required @csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id)",
"template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post",
"th in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page = int(page) -1 subforum_num_pages =",
"post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def",
"else: return render(request, template, c) raise Http404 @login_required def quotePost(request, forum_id, post_id): forum",
"for quote in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post()",
"and 0 <= page: set_visit(thread, request.user) thread.visit_counter += 1 thread.save() c = {",
"post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostDown(request, forum_id,",
"\"\") if opt != \"\": option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False",
"thread_id) if thread: if not check_slug(thread, thread_slug): if page == 1: return redirect('Forum.views.thread',",
"thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method == 'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form",
"'page_title': 'New Thread', 'title': 'New Thread', 'submit_btn_text': 'Create', } return render(request, template, c)",
"last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post',",
"= [] unfiltered_post_list = thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if (not pt.hidden) or",
"= get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread,",
"is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list = [] for sf in subforum.child_set.order_by('local_id'):",
"1 if found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id)",
"redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form = Subforum(forum=forum)",
"from datetime import datetime from Forum.models import * from Forum.settings import * from",
"old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if",
"post) response_data = {} if vote: if vote.type == \"Up\": vote.delete() response_data['action'] =",
"subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list",
"post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page)",
"= FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user) forum",
"forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method == 'POST': new_post = Post(publisher=request.user) new_post_form",
"subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if",
"question = request.POST.get(\"question\") option_list = [] for i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\",",
"thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod",
"new_post = Post() new_post_form = FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title':",
"> page and 0 <= page) or subforum_num_pages == 0: c = {",
"new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread",
"post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum",
"thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostUp(request, forum_id,",
"FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form = FormPost(instance=post) else: c = { 'forum_id':forum_id,",
"= subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list =",
"rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list = [] for i",
"lgin(request, user) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) else: raise Http404",
"post and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content = post.content if request.method == 'POST':",
"= Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id =",
"render(request, template_ajax, c) else: return render(request, template, c) raise Http404 @login_required def quotePost(request,",
"thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if",
"forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug, page, template=template) raise Http404 def subforum(request, forum_id,",
"post) response_data = {} if vote: if vote.type == \"Down\": vote.delete() response_data['action'] =",
"subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id,",
"thread=thread) for quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user):",
"datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post =",
"c) else: return render(request, template, c) raise Http404 @login_required def quotePost(request, forum_id, post_id):",
"and (not thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id,",
"forum: post = get_post_instance(forum, post_id) if post: thread = post.thread post_list = thread.post_set.order_by('local_id')",
"return render(request, CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user),",
"new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread',",
"'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added' # Send signal signals.upvote.send(sender=forum, user=request.user,",
"post.thread.post_set.first() == post: if post.title == \"\": post.title = post_old_title post.thread.name = post.title",
"c) raise Http404 @login_required def quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum:",
"forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method == 'POST': form = FormUserLogin(request.POST)",
"raise Http404 @login_required @csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum =",
"thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id)",
"Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread",
"thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post()",
"= forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if post.title ==",
"Http404 @login_required @csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id)",
"if thread.parent.canModerate(request.user): if (request.method == 'POST'): form = FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save()",
"vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added' # Send",
"@csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum:",
"unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list:",
"check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list = []",
"= thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): can_post",
"page: set_visit(thread, request.user) thread.visit_counter += 1 thread.save() c = { 'forum_id':forum_id, 'thread': thread,",
"@login_required @csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if",
"redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user)",
"th.isVisited(request.user) thread_list.append(th) page = int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page",
"forum_id, 0, subforum_slug, page, template=template) raise Http404 def subforum(request, forum_id, subforum_id, subforum_slug, page=1,",
"as lgin from django.shortcuts import render, redirect from datetime import datetime from Forum.models",
"page, template=template) raise Http404 def subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum =",
"template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug() return subforum(request, forum_id, 0,",
"subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form =",
"True break num += 1 if found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id,",
"import * from Forum.getInstanceLib import * from Forum.modelsLib import * import Forum.signals as",
"logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404",
"quote in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post() quotes_text",
"= [] for th in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page = int(page)",
"'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request, template, c) else: c =",
"forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): if request.method == 'POST':",
"redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost() c = { 'forum_id':forum_id, 'form': report_post_form,",
"subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum = subforum.forum, view_permission = subforum.view_permission, mod_permission =",
"thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum",
"subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum =",
"th.is_visited = th.isVisited(request.user) thread_list.append(th) page = int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages",
"post.publisher == request.user: edit_post_form = FormPost(instance=post) else: c = { 'forum_id':forum_id, } return",
"page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required",
"vote = get_vote_instance(request.user, post) response_data = {} if vote: if vote.type == \"Down\":",
"thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method == 'POST'): form = FormThreadSettings(request.POST, instance=thread) if",
"forum_id): lgout(request) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404 def",
"forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum,",
"thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod = subforum.canModerate(request.user) if",
"return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user)",
"else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form = FormPost(instance=post)",
"Subforum', 'submit_btn_text': 'Create', } return render(request, template, c) else: c = { 'forum_id':forum_id,",
"if edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator =",
"is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and request.method == 'POST': answer = request.POST.get(\"poll_answer\", False)",
"if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list = [] for th in sf_th_set:",
"= get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id,",
"= get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data =",
"thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise",
"post.score() >= forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return",
"subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c =",
"request.method == 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum",
"import datetime from Forum.models import * from Forum.settings import * from Forum.forms import",
"c) raise Http404 @login_required @csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum",
"unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages",
"report_post_form.save(commit=False) report_post.user = request.user report_post.post = post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else:",
"(not thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id')",
"'forum_id':forum_id, 'form': form, 'thread': thread, } return render(request, template, c) raise Http404 @login_required",
"'form': form, } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template,",
"sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set",
"= FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited = PostEdited(",
"= { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create',",
"vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added' # Send",
"thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quote.delete() return redirect('Forum.views.post',",
"'submit_btn_text': 'Send', } return render(request, template, c) else: c = { 'forum_id':forum_id, }",
"form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c =",
"return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c = { 'forum_id':forum_id,",
"'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template,",
"'removed' else: vote.type = \"Up\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Up\").save()",
"'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not thread.closed",
"opt != \"\": option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread",
"new_subforum.creator = request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum(",
"new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id",
"if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted",
"post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise",
"authenticate, login as lgin from django.shortcuts import render, redirect from datetime import datetime",
"get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"post_id=new_post.local_id) else: new_post = Post() quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for",
"'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return render(request, template_ajax, c)",
"for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned',",
"= FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread",
"== 'POST': answer = request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id,",
"c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id,",
"found = False for pt in post_list: if pt == post: found =",
"thread.parent.canModerate(request.user): if (request.method == 'POST'): form = FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return",
"{} if quote: quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] =",
"Send signal new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread)",
"subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user)",
"= forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum = forum new_subforum.creator = request.user new_subforum.save() return",
"forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread',",
"response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added' # Send signal",
"is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not thread.closed or is_mod), 'poll': poll, }",
"'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return",
"False for pt in post_list: if pt == post: found = True break",
"if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated():",
"from Forum.modelsLib import * import Forum.signals as signals from math import ceil #",
"new_post_form = FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread', 'title':",
"if not post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post)",
"from django.shortcuts import render, redirect from datetime import datetime from Forum.models import *",
"else: c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply Thread',",
"voteThreadPoll(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id)",
"= request.user report_post.post = post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form =",
"= FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread', 'title': 'New",
"page=page) raise Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id)",
"= forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug, page, template=template) raise Http404 def subforum(request,",
"unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote =",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') for",
"thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if",
"get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): post_old_title =",
"thread.closed or is_mod), 'poll': poll, } return render(request, template, c) else: c =",
"if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): if request.method ==",
"} return render(request, CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request, forum_id, thread_id, thread_slug): forum",
"return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form =",
"if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form = FormPost(instance=post) else:",
"= True break num += 1 if found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread',",
"FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content,",
"return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug,",
"import * from Forum.modelsLib import * import Forum.signals as signals from math import",
"\"2\"))) question = request.POST.get(\"question\") option_list = [] for i in rang: opt =",
"if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method",
"request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request,",
"get_last_visit_instance(request.user, thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id,",
"answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id): forum",
"import json from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators",
"= unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote",
"= FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form",
"0, subforum_slug, page, template=template) raise Http404 def subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE):",
"subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread",
"user=request.user, post=post) if not post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent = True post.save()",
"[] for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set =",
"post=post, thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostUp(request,",
"template_ajax, c) else: return render(request, template, c) raise Http404 @login_required def quotePost(request, forum_id,",
"= post_old_title post.thread.name = post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else:",
"forum.allow_up_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post)",
"if page == 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id,",
"get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data = {}",
"return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if last_visit: last_post =",
"return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def replyThread(request, forum_id, thread_id, thread_slug,",
"forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\")",
"thread_slug=thread.slug()) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or",
"new_post_form, 'thread':thread, } else: c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread',",
"return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if",
"new_post = Post() quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in",
"= subforum new_subforum.forum = forum new_subforum.creator = request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id,",
"thread_list = [] for th in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page =",
"{} if vote: if vote.type == \"Down\": vote.delete() response_data['action'] = 'removed' elif vote.type",
"request.POST.get(\"question\", \"\") != \"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list",
"CANT_VIEW_CONTENT, c) raise Http404 def thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum =",
"return redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id)",
"return render(request, template, c) raise Http404 @login_required @csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\",",
"post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data",
"pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id,",
"reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False)",
"= { 'forum_id':forum_id, 'form': form, 'thread': thread, } return render(request, template, c) raise",
"signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post() new_post_form =",
"forum: return redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if not form: form = FormUserLogin()",
"'thread':thread, } else: c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread', 'title':",
"== 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(),",
"and post.score() >= forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score()",
"forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum,",
"return subforum(request, forum_id, 0, subforum_slug, page, template=template) raise Http404 def subforum(request, forum_id, subforum_id,",
"PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user),",
"'form': form, 'thread': thread, } return render(request, template, c) raise Http404 @login_required def",
"if request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\", \"\") != \"\": rang = range(0,",
"if post and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content = post.content if request.method ==",
"= post.title post_old_content = post.content if request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form =",
"def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum:",
"template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post",
"form = FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form': form, 'thread': thread, } return",
"if vote: if vote.type == \"Down\": vote.delete() response_data['action'] = 'removed' elif vote.type ==",
"forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post:",
"'added' # Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() >=",
">= forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data),",
"'New Thread', 'submit_btn_text': 'Create', } return render(request, template, c) else: c = {",
"c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request,",
"vote.type == \"Up\": vote.delete() response_data['action'] = 'removed' else: vote.type = \"Up\" vote.save() response_data['action']",
"signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post() new_post_form",
"instance=post) else: edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user,",
"else: poll = None page = int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages",
"== 'POST': form = FormUserLogin(request.POST) if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if user:",
"thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): if thread.poll:",
"c = { 'forum_id':forum_id, 'form': report_post_form, 'post': post, } if request.is_ajax(): return render(request,",
"thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post() new_post_form = FormNewThread(instance=new_post)",
"get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): if page == 1: return",
"post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form =",
"forum: thread = get_thread_instance(forum, thread_id) if thread and (not thread.closed or thread.parent.canModerate(request.user)): if",
"\"False\") == \"True\" and request.POST.get(\"question\", \"\") != \"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\")))",
"post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score'] =",
"get_quote_instance(request.user, post) response_data = {} if quote: quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user,",
"post_id) if post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data = {} if",
"thread_id) if thread and (not thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return",
"post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_down_votes: post = get_post_instance(forum, post_id) if",
"@login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread",
"get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id,",
"Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post) if",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method == 'POST': new_post =",
"poll, } return render(request, template, c) else: c = { 'forum_id':forum_id, } return",
"if post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data = {} if quote:",
"@login_required def logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id)",
"'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added' # Send signal signals.downvote.send(sender=forum, user=request.user,",
"else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] = 'added' # Send signal signals.downvote.send(sender=forum, user=request.user, post=post)",
"new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id",
"logout as lgout, authenticate, login as lgin from django.shortcuts import render, redirect from",
"'Create Subforum', 'submit_btn_text': 'Create', } return render(request, template, c) else: c = {",
"render(request, template, c) raise Http404 @login_required def quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id)",
"post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data = {} if",
"get_forum_instance(forum_id) if forum and forum.allow_up_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user):",
"} return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def replyThread(request, forum_id, thread_id,",
"= get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and",
"sf_th_set.exclude(hidden=True) thread_list = [] for th in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page",
"in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt)",
"raise Http404 def subforum(request, forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if",
"pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll =",
"c = { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text':",
"else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required",
"request.method == 'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else:",
"post.score() <= forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return",
"if forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum",
"thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden",
"new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum",
"= \"Up\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added'",
"as lgout, authenticate, login as lgin from django.shortcuts import render, redirect from datetime",
"edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return render(request, template_ajax, c) else: return",
"in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name')",
"new_subforum_form = FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum', 'title':",
"= { 'forum_id':forum_id, 'form': form, } if request.is_ajax(): return render(request, template_ajax, c) else:",
"= 'added' # Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score()",
"thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method == 'POST': new_post = Post(publisher=request.user) if",
"instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(),",
"{ 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def newSubforum(request,",
"forum new_subforum.creator = request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum =",
"'form': report_post_form, 'post': post, } if request.is_ajax(): return render(request, template_ajax, c) else: return",
"* from Forum.getInstanceLib import * from Forum.modelsLib import * import Forum.signals as signals",
"forum and forum.allow_down_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote =",
"FormPost(instance=post) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) c =",
"django.contrib.auth import logout as lgout, authenticate, login as lgin from django.shortcuts import render,",
"int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and 0 <= page: set_visit(thread, request.user) thread.visit_counter +=",
"name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\"",
"range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list = [] for i in rang:",
"Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\")",
"request.method == 'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user =",
"else: new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count()",
"report_post = report_post_form.save(commit=False) report_post.user = request.user report_post.post = post report_post.save() return redirect('Forum.views.post', forum_id=forum_id,",
"import csrf_protect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout as lgout, authenticate,",
"new_subforum = Subforum( forum = subforum.forum, view_permission = subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission",
"raise Http404 def threadLastPage(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread",
"render(request, template, c) raise Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum =",
"option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return",
"(not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread',",
"instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() #",
"subforum: if not check_slug(subforum, subforum_slug): if page == 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id,",
"redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def",
"@csrf_protect def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if",
"== 'POST'): form = FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id,",
"'submit_btn_text': 'Create', } return render(request, template, c) else: c = { 'forum_id':forum_id, }",
"subforum.canCreateThread(request.user): if request.method == 'POST': new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if",
"Http404 def threadLastPage(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread =",
"else: new_subforum = Subforum( forum = subforum.forum, view_permission = subforum.view_permission, mod_permission = subforum.mod_permission,",
"thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread:",
"if post: thread = post.thread post_list = thread.post_set.order_by('local_id') num = 0 found =",
"if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data = {} if vote:",
"quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post() quotes_text = \"\"",
"= True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404",
"request.user), } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c)",
"raise Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if",
"in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post)",
"@login_required def quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum,",
"= 'added' # Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score()",
"return render(request, template_ajax, c) else: return render(request, template, c) raise Http404 @login_required @csrf_protect",
"response_data['action'] = 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\")",
"new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post =",
"= request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\": option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question,",
"== 'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post) else: new_post_form",
"if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): post_old_title = post.title",
"request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and",
"int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect",
"@csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"): forum = get_forum_instance(forum_id) if forum: thread",
"subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and",
"thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') for pt",
"'page_title': 'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create', } return render(request, template, c)",
"new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum = forum new_subforum.creator",
"for quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form",
"and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data = {} if vote: if vote.type",
"= subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title':",
"if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user):",
"report_post.post = post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost() c",
"post_id=post_id) raise Http404 @login_required @csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user) forum",
"def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum",
"post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in",
"= get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum,",
"Post() new_post_form = FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread',",
"if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum =",
"thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread:",
"sf_th_set = sf_th_set.exclude(hidden=True) thread_list = [] for th in sf_th_set: th.is_visited = th.isVisited(request.user)",
"'forum_id':forum_id, 'form': form, } if request.is_ajax(): return render(request, template_ajax, c) else: return render(request,",
"if thread.poll: if thread.poll.userCanVote(request.user) and request.method == 'POST': answer = request.POST.get(\"poll_answer\", False) if",
"return render(request, template, c) @login_required def logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id) if",
"subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if",
"else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread",
"{} if vote: if vote.type == \"Up\": vote.delete() response_data['action'] = 'removed' else: vote.type",
"= authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user) forum = get_forum_instance(forum_id) if forum: return",
"post_id) if post and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content = post.content if request.method",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and",
"Forum.signals as signals from math import ceil # Create your views here. def",
"if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title,",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method == 'POST'): form = FormThreadSettings(request.POST, instance=thread)",
"thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user,",
"not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method ==",
"post=post, type=\"Down\").save() response_data['action'] = 'added' # Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if not",
"else: new_post_form = FormPost(instance=new_post) if request.is_ajax(): template = template_ajax c = { 'forum_id':forum_id,",
"post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator",
"opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\": option_list.append(opt) if len(option_list) >= 2:",
"render(request, template, c) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c)",
"0: c = { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3,",
"vote.type = \"Down\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action'] =",
"Http404 @login_required def votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum and forum.allow_down_votes:",
"Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count()",
"is_mod), 'poll': poll, } return render(request, template, c) else: c = { 'forum_id':forum_id,",
"template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if",
"subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod):",
"if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user,",
"'form': new_post_form, 'thread':thread, } else: c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply",
"post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post)",
"edit_post_form = FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form = FormPost(instance=post) else: c =",
"Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent",
"content_type=\"application/json\") raise Http404 @login_required def votePostUp(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum",
"parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\" and",
"return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id): forum = get_forum_instance(forum_id) if",
"thread = get_thread_instance(forum, thread_id) if thread and (not thread.closed or thread.parent.canModerate(request.user)): if not",
"redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if not form: form = FormUserLogin() c =",
"= FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title,",
"thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages =",
"if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method == 'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user):",
"and request.POST.get(\"question\", \"\") != \"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\")",
"= {} if vote: if vote.type == \"Up\": vote.delete() response_data['action'] = 'removed' else:",
"threadLastPage(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id)",
"response_data['action'] = 'removed' elif vote.type == \"Up\": vote.type = \"Down\" vote.save() response_data['action'] =",
"sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page = int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if",
"or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id,",
"page = int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and 0",
"\"\": post.title = post_old_title post.thread.name = post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id,",
"c = { 'forum_id':forum_id, 'form': form, } if request.is_ajax(): return render(request, template_ajax, c)",
"thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): if page ==",
"= 0 found = False for pt in post_list: if pt == post:",
"forum_id=forum.local_id) else: raise Http404 if not form: form = FormUserLogin() c = {",
"render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE):",
"pt.is_quoted = get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count()",
"Http404 @login_required def quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post =",
"get_vote_instance(request.user, post) response_data = {} if vote: if vote.type == \"Down\": vote.delete() response_data['action']",
"new_post.local_id = forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden,",
"def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum,",
"for pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user,",
"thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if request.is_ajax(): template = template_ajax",
"Http404 @login_required @csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id)",
"if request.method == 'POST': new_post = Post(publisher=request.user) if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(request.POST, instance=new_post)",
"= get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post: thread = post.thread",
"\"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list = [] for",
"Forum.settings import * from Forum.forms import * from Forum.lib import * from Forum.getInstanceLib",
"forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings',",
"Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def",
"= get_last_visit_instance(request.user, thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post',",
"post.title = post_old_title post.thread.name = post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id)",
"return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required @csrf_protect def editPost(request,",
"redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method == 'POST': new_post",
"thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if",
"= Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else:",
"[] for i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\":",
"subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id)",
"quote: quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added' return",
"subforum_num_pages == 0: c = { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page,",
"== post: found = True break num += 1 if found: page =",
"unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt)",
"thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method == 'POST'): form = FormThreadSettings(request.POST, instance=thread) if form.is_valid():",
"-1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and 0 <= page: set_visit(thread,",
"[] unfiltered_post_list = thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user):",
"@csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum:",
"get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug())",
"if request.is_ajax(): template = template_ajax c = { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, }",
"if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c",
"not form: form = FormUserLogin() c = { 'forum_id':forum_id, 'form': form, } if",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first()",
"post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] =",
"'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return render(request, template_ajax, c) else:",
"not post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score']",
"post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post: thread",
"'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def thread(request, forum_id, thread_id, thread_slug,",
"post) response_data = {} if quote: quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user, post=post,",
"+= 1 thread.save() c = { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1),",
"= subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form",
"thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod =",
"!= \"\": option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save()",
"subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if",
"else: new_post = Post() new_post_form = FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form': new_post_form,",
"thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent",
"redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id')",
"not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method ==",
"here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method == 'POST':",
"FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread', 'title': 'New Thread',",
"thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and 0 <= page: set_visit(thread, request.user)",
"= new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum = forum new_subforum.creator =",
"check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread and",
"and (not thread.closed or is_mod), 'poll': poll, } return render(request, template, c) else:",
"= Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text",
"'title': 'New Thread', 'submit_btn_text': 'Create', } return render(request, template, c) else: c =",
"@login_required @csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if",
"= get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): quote",
"template, c) @login_required def logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id) if forum: return",
"= forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, )",
"get_thread_instance(forum, thread_id) if thread and (not thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug):",
"== 0: c = { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1),",
"raise Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum:",
"page=page, post_id=post_id) raise Http404 @login_required @csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"): check_user_is_spamming(request.user)",
"@login_required @csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if",
"get_forum_instance(forum_id) if forum and forum.allow_down_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user):",
"Http404, HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from django.contrib.auth import",
"Http404 @login_required @csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id)",
"'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), }",
"int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and 0 <= page:",
"thread.poll: if thread.poll.userCanVote(request.user) and request.method == 'POST': answer = request.POST.get(\"poll_answer\", False) if answer:",
"else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) c = {",
"type=\"Up\").save() response_data['action'] = 'added' # Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent",
"post = get_post_instance(forum, post_id) if post: thread = post.thread post_list = thread.post_set.order_by('local_id') num",
"<= page) or subforum_num_pages == 0: c = { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list,",
"thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post() new_post_form = FormNewThread(instance=new_post) c = { 'forum_id':forum_id,",
"forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def newThread(request,",
"new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text': 'Send', } return render(request, template,",
"subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if",
"= FormPost(instance=post) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) c",
"post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if",
"from Forum.settings import * from Forum.forms import * from Forum.lib import * from",
"get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content = post.content if",
"quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if",
"thread and (not thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id,",
"request.user.is_authenticated() and (not thread.closed or is_mod), 'poll': poll, } return render(request, template, c)",
"else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required",
"'Send', } return render(request, template, c) else: c = { 'forum_id':forum_id, } return",
"num = 0 found = False for pt in post_list: if pt ==",
"subforum_slug): if page == 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum',",
"CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if",
"hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\", \"\") != \"\":",
"as signals from math import ceil # Create your views here. def login(request,",
"pt in unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page",
"and request.user.is_authenticated(), } return render(request, template, c) else: c = { 'forum_id':forum_id, }",
"= new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send signal new post",
"thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required @csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\", template_ajax=\"Forum/forms/ajax/edit_post.html\"):",
"for pt in unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page)))",
"post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif",
"if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated()",
"'can_post':can_post and request.user.is_authenticated() and (not thread.closed or is_mod), 'poll': poll, } return render(request,",
"if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c) raise Http404",
"new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(),",
"'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request, template, c) else: c = { 'forum_id':forum_id,",
"= { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 def thread(request, forum_id,",
"thread: if not check_slug(thread, thread_slug): if page == 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id,",
"post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post) response_data = {} if vote: if vote.type ==",
"forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread and (not",
"= False for pt in post_list: if pt == post: found = True",
"authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum',",
"} return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def newSubforum(request, forum_id, subforum_id,",
"subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if",
"else: return render(request, template, c) @login_required def logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id)",
"return render(request, template, c) raise Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum",
"@login_required @csrf_protect def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id)",
"import Forum.signals as signals from math import ceil # Create your views here.",
"forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\")",
"forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user):",
"= FormReportPost() c = { 'forum_id':forum_id, 'form': report_post_form, 'post': post, } if request.is_ajax():",
"== 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(),",
"print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def newThread(request, forum_id, subforum_id,",
"post=post) if not post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum,",
"return render(request, CANT_VIEW_CONTENT, c) raise Http404 def thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE):",
"template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method == 'POST': form = FormUserLogin(request.POST) if",
"c) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404",
"Forum.models import * from Forum.settings import * from Forum.forms import * from Forum.lib",
"# Send signal new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user,",
"check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method",
"2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new thread signal signals.thread_published.send(sender=forum,",
"'Reply Thread', 'submit_btn_text': 'Send', } return render(request, template, c) else: c = {",
"thread.hidden or is_mod): can_post = subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') if",
"(not thread.closed or is_mod), 'poll': poll, } return render(request, template, c) else: c",
"= get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug, page,",
"raise Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum_slug",
"forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread',",
"post_id) if post and post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form = FormReportPost(request.POST) if",
"login_required from django.contrib.auth import logout as lgout, authenticate, login as lgin from django.shortcuts",
"'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and",
"subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method == 'POST': new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST,",
"return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug,",
"thread_slug=thread.slug()) subforum = thread.parent post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') for pt in",
"django.contrib.auth.decorators import login_required from django.contrib.auth import logout as lgout, authenticate, login as lgin",
"FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread = Thread(",
"forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): if page",
"post.thread post_list = thread.post_set.order_by('local_id') num = 0 found = False for pt in",
"render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def replyThread(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/post.html\",",
"c) @login_required def logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum',",
"def logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) raise",
"thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id,",
"if not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread)",
"'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod,",
"return render(request, CANT_VIEW_CONTENT, c) raise Http404 def threadLastPage(request, forum_id, thread_id, thread_slug): forum =",
"'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id, 'form': edit_post_form, 'post':post,",
"= get_vote_instance(request.user, post) response_data = {} if vote: if vote.type == \"Down\": vote.delete()",
"get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post: thread =",
"thread = post.thread post_list = thread.post_set.order_by('local_id') num = 0 found = False for",
"= post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if post.thread.parent.canModerate(request.user): edit_post_form",
"FormThreadSettings(instance=thread) c = { 'forum_id':forum_id, 'form': form, 'thread': thread, } return render(request, template,",
"edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user),",
"raise Http404 @login_required @csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user) forum =",
"if vote: if vote.type == \"Up\": vote.delete() response_data['action'] = 'removed' else: vote.type =",
"report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user = request.user report_post.post =",
"request.method == 'POST': answer = request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread',",
"\"\") != \"\": rang = range(0, int(request.POST.get(\"poll_option_count\", \"2\"))) question = request.POST.get(\"question\") option_list =",
"* from Forum.lib import * from Forum.getInstanceLib import * from Forum.modelsLib import *",
"option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send",
"response_data['action'] = 'removed' else: vote.type = \"Up\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user,",
"if quote: quote.delete() response_data['action'] = 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added'",
"= FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if request.is_ajax(): template = template_ajax c =",
"'name') if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list = [] for th in",
"get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else:",
"request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request, template, c) else: c",
"signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quote.delete()",
"{ 'forum_id':forum_id, 'form': form, } if request.is_ajax(): return render(request, template_ajax, c) else: return",
"if request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form =",
"not check_slug(thread, thread_slug): return redirect('Forum.views.firstPostUnreadThread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if",
"thread=thread) for quote in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post =",
"page=page) subforum = thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or",
"= None page = int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page",
"if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\")",
"= 'removed' elif vote.type == \"Up\": vote.type = \"Down\" vote.save() response_data['action'] = 'added'",
"= thread_num_pages return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def saveThreadSettings(request,",
"subforum.forum, view_permission = subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission,",
"response_data = {} if vote: if vote.type == \"Down\": vote.delete() response_data['action'] = 'removed'",
"check_slug(subforum, subforum_slug): if page == 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return",
"forum and forum.allow_up_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote =",
"new_post.save() # Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug())",
"vote = get_vote_instance(request.user, post) response_data = {} if vote: if vote.type == \"Up\":",
"sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True)",
"response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added' # Send signal",
"forum = get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug,",
"1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator': is_mod, 'can_create_thread':can_create_thread and request.user.is_authenticated(), } return render(request,",
"return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post() quotes_text = \"\" quote_list =",
"subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user,",
"edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if post.title == \"\": post.title = post_old_title post.thread.name",
"vote.type = \"Up\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] =",
"subforum_list = [] for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf)",
"subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method == 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form =",
"thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated()",
"= Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\",",
"def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum",
"* import Forum.signals as signals from math import ceil # Create your views",
"= Post() new_post_form = FormNewThread(instance=new_post) c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New",
"forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum,",
"raise Http404 if not form: form = FormUserLogin() c = { 'forum_id':forum_id, 'form':",
"forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send signal new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime",
"if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum = thread.parent is_mod",
"poll = thread.poll_set.first() else: poll = None page = int(page) -1 thread_num_pages =",
"forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post)",
"{ 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def voteThreadPoll(request,",
"if subforum: if not check_slug(subforum, subforum_slug): if page == 1: return redirect('Forum.views.subforum', forum_id=forum_id,",
"return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect",
"= get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread and (not thread.closed",
"quote = get_quote_instance(request.user, post) response_data = {} if quote: quote.delete() response_data['action'] = 'removed'",
"= thread.parent is_mod = subforum.canModerate(request.user) if subforum.canView(request.user) and (not thread.hidden or is_mod): if",
"import ceil # Create your views here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form",
"new_post.forum=forum new_post.thread=thread new_post.save() # Send signal new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save()",
"c = { 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return",
"-*- import json from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_protect from",
"unfiltered_post_list: if request.user.is_authenticated(): pt.is_quoted = get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if",
"\"Up\": vote.type = \"Down\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post, type=\"Down\").save() response_data['action']",
"post: found = True break num += 1 if found: page = (num/forum.posts_per_page)+1",
"= request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum",
"utf-8 -*- import json from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_protect",
"and post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post =",
"sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list =",
"Thread', 'submit_btn_text': 'Create', } return render(request, template, c) else: c = { 'forum_id':forum_id,",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post",
"if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll = None",
"thread_list.append(th) page = int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and",
"thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll = None page = int(page)",
"response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostUp(request, forum_id, post_id):",
"= subforum.canCreateThread(request.user) subforum_list = [] for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited =",
"post_list: if pt == post: found = True break num += 1 if",
"new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread)",
"== \"\": post.title = post_old_title post.thread.name = post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post',",
"= { 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax(): return render(request,",
"vote: if vote.type == \"Up\": vote.delete() response_data['action'] = 'removed' else: vote.type = \"Up\"",
"= get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): if page == 1:",
"return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent is_mod = subforum.canModerate(request.user) if",
"break num += 1 if found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id,",
"return render(request, template, c) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT,",
"CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def newSubforum(request, forum_id, subforum_id, subforum_slug, template=FORM_TEMPLATE): check_user_is_spamming(request.user)",
"request.user) thread.visit_counter += 1 thread.save() c = { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1,",
"template, c) raise Http404 @login_required def quotePost(request, forum_id, post_id): forum = get_forum_instance(forum_id) if",
"forum.post_set.count() new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save()",
"if post.title == \"\": post.title = post_old_title post.thread.name = post.title post.thread.save() post_edited.save() post.save()",
"return redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method == 'POST': new_post =",
"{ 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else: c = { 'forum_id':forum_id, 'form': new_post_form,",
"c) c = { 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), } if request.is_ajax():",
"redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post() quotes_text = \"\" quote_list = Quote.objects.filter(user=request.user,",
"forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) else: raise Http404 if not",
"new_thread = Thread( local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if",
"post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(instance=post) elif post.publisher == request.user: edit_post_form = FormPost(instance=post) else: c",
"quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form",
"forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content",
"and (not thread.hidden or is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and request.method == 'POST':",
"form = None if request.method == 'POST': form = FormUserLogin(request.POST) if form.is_valid(): user",
"ceil # Create your views here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form =",
"forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost() c = { 'forum_id':forum_id, 'form': report_post_form, 'post':",
"publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise",
"rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\": option_list.append(opt) if len(option_list) >=",
"== \"Up\": vote.delete() response_data['action'] = 'removed' else: vote.type = \"Up\" vote.save() response_data['action'] =",
"post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def newThread(request, forum_id,",
"page = int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and 0",
"post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id)",
"= { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission,",
"= 'removed' else: Quote(user=request.user, post=post, thread=post.thread).save() response_data['action'] = 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise",
"forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum = forum new_subforum.creator = request.user new_subforum.save() return redirect('subforum',",
"Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create', } return render(request, template, c) else: c",
"views here. def login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method ==",
"= post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostDown(request, forum_id, post_id): forum",
"redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) def post(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum:",
"= FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create",
"render(request, CANT_VIEW_CONTENT, c) c = { 'forum_id':forum_id, 'form': edit_post_form, 'post':post, 'user_is_mod':user_has_permission(post.thread.parent.mod_permission, request.user), }",
"new_post.thread=new_thread new_post.save() # Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id,",
"== \"Down\": vote.delete() response_data['action'] = 'removed' elif vote.type == \"Up\": vote.type = \"Down\"",
"'added' # Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() <=",
"FormReportPost() c = { 'forum_id':forum_id, 'form': report_post_form, 'post': post, } if request.is_ajax(): return",
"thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quote.delete() return redirect('Forum.views.post', forum_id=forum_id,",
"min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not thread.closed or is_mod),",
"newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum =",
"if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if forum.canAdministrate(request.user): if request.method",
"and 0 <= page) or subforum_num_pages == 0: c = { 'forum_id':forum_id, 'forum':",
"if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid():",
"request.user report_post.post = post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost()",
"= { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread', 'title': 'New Thread', 'submit_btn_text': 'Create',",
"thread.poll.userCanVote(request.user) and request.method == 'POST': answer = request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer)",
"post=post) if not post.score_event_sent and post.score() >= forum.positive_score_event: post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum,",
"or is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and request.method == 'POST': answer = request.POST.get(\"poll_answer\",",
"== 'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user = request.user",
"response_data['action'] = 'added' # Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and",
"instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread)",
"template = template_ajax c = { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else: c",
"forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum_slug = forum.main_forum.slug() return subforum(request,",
"import logout as lgout, authenticate, login as lgin from django.shortcuts import render, redirect",
"= { 'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else: c = { 'forum_id':forum_id, 'form':",
"found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404",
"from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required",
"page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list = [] for",
"import * from Forum.settings import * from Forum.forms import * from Forum.lib import",
"pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll",
"raise Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if",
"thread.visit_counter += 1 thread.save() c = { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page,",
"if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum =",
"forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404 @login_required @csrf_protect def newThread(request, forum_id, subforum_id, subforum_slug, template=\"Forum/forms/thread.html\"): check_user_is_spamming(request.user)",
"get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): if page == 1: return",
"\"\": option_list.append(opt) if len(option_list) >= 2: new_thread.setPoll(question, option_list) new_post.hidden=False new_post.forum=forum new_post.thread=new_thread new_post.save() #",
"'removed' elif vote.type == \"Up\": vote.type = \"Down\" vote.save() response_data['action'] = 'added' else:",
"= thread.post_set.order_by('local_id') num = 0 found = False for pt in post_list: if",
"'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id,",
"thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required @csrf_protect def editPost(request, forum_id, post_id, template=\"Forum/forms/edit_post.html\",",
"post_old_content = post.content if request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post)",
"form = FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else:",
"get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug())",
"check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if",
"if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user):",
"subforum(request, forum_id, 0, subforum_slug, page, template=template) raise Http404 def subforum(request, forum_id, subforum_id, subforum_slug,",
"+= \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if thread.parent.canModerate(request.user): new_post_form = FormPost_Mod(instance=new_post) else: new_post_form =",
"Forum.lib import * from Forum.getInstanceLib import * from Forum.modelsLib import * import Forum.signals",
"template, c) raise Http404 @login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id)",
"'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1, 'subforum_pages':range(max(page, 1), min(page+3, subforum_num_pages+1)), 'is_admin':user_has_permission(forum.admin_permission, request.user), 'is_moderator':",
"thread.post_set.order_by('local_id') num = 0 found = False for pt in post_list: if pt",
"<= forum.negative_score_event: post.score_event_sent = True post.save() signals.negative_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data),",
"= 'added' else: Vote(user=request.user, post=post, type=\"Up\").save() response_data['action'] = 'added' # Send signal signals.upvote.send(sender=forum,",
"thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.threadLastPage', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) subforum",
"report_post_form = FormReportPost() c = { 'forum_id':forum_id, 'form': report_post_form, 'post': post, } if",
"'forum_id':forum_id, 'form': new_post_form, 'thread':thread, } else: c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title':",
"c = { 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'Reply Thread', 'title': 'Reply Thread', 'submit_btn_text':",
"if user: lgin(request, user) forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) else:",
"or thread.parent.canModerate(request.user)): if not check_slug(thread, thread_slug): return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user)",
"if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) page = thread_num_pages return",
"'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False)",
"instance=post) if edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator",
"subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id)",
"from Forum.lib import * from Forum.getInstanceLib import * from Forum.modelsLib import * import",
"subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list = [] for th in sf_th_set: th.is_visited =",
"= subforum.thread_set.order_by('-pinned', '-last_publication_datetime', 'name') if not subforum.canModerate(request.user): sf_th_set = sf_th_set.exclude(hidden=True) thread_list = []",
"if forum: subforum_slug = forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug, page, template=template) raise",
"thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if request.user.is_authenticated():",
"or subforum_num_pages == 0: c = { 'forum_id':forum_id, 'forum': subforum, 'subforum_list':subforum_list, 'thread_list':thread_list[(page*forum.threads_per_page):(page*forum.threads_per_page)+forum.threads_per_page], 'subforum_current_page':page+1,",
"= get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug): return redirect('Forum.views.newSubforum', forum_id=forum_id, subforum_id=subforum_id,",
"if forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return",
"forum.allow_down_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user, post)",
"[] for th in sf_th_set: th.is_visited = th.isVisited(request.user) thread_list.append(th) page = int(page) -1",
"thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form = FormThreadSettings(instance=thread) c = {",
"thread_id, thread_slug, template=\"Forum/forms/post.html\", template_ajax=\"Forum/forms/ajax/post.html\"): check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum,",
"return redirect('Forum.views.replythread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canReplyThread(request.user) and request.user.is_authenticated(): if request.method == 'POST':",
"HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id) if",
"import * import Forum.signals as signals from math import ceil # Create your",
"post report_post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: report_post_form = FormReportPost() c = {",
"post.content if request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form",
"check_user_is_spamming(request.user) forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and",
"'thread': thread, } return render(request, template, c) raise Http404 @login_required def firstPostUnreadThread(request, forum_id,",
"signal new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for",
"def thread(request, forum_id, thread_id, thread_slug, page=1, template=THREAD_TEMPLATE): forum = get_forum_instance(forum_id) if forum: thread",
"return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum",
"creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\", \"\")",
"if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id, post_id=thread.getLastPublishedPost().local_id) raise Http404",
"'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST, instance=post) if",
"new_post.save() # Send signal new post published signals.post_published.send(sender=forum, post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list =",
"new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post =",
"new_post_form = FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if request.is_ajax(): template = template_ajax c",
"if form.is_valid(): user = authenticate(username=form.data['username'], password=form.data['password']) if user: lgin(request, user) forum = get_forum_instance(forum_id)",
"forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if",
"edit_post_form = FormPost(instance=post) else: c = { 'forum_id':forum_id, } return render(request, CANT_VIEW_CONTENT, c)",
"= post.content if request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else:",
"in post_list: if pt == post: found = True break num += 1",
"local_id=forum.thread_set.count(), name=new_post.title, parent=subforum, forum=forum, creator=request.user, last_publication_datetime=datetime.now(), hidden=new_post.hidden, ) new_thread.save() if request.POST.get(\"add_poll\", \"False\") ==",
"= get_post_instance(forum, post_id) if post: thread = post.thread post_list = thread.post_set.order_by('local_id') num =",
"from Forum.models import * from Forum.settings import * from Forum.forms import * from",
"forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum = subforum.forum, view_permission = subforum.view_permission,",
"[] unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in",
"signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostDown(request,",
"Subforum( forum = subforum.forum, view_permission = subforum.view_permission, mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission,",
"if forum: post = get_post_instance(forum, post_id) if post: thread = post.thread post_list =",
"= 'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostUp(request, forum_id, post_id): forum",
"get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum, subforum_id) if subforum: if not check_slug(subforum, subforum_slug):",
"get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): quote =",
"= (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise Http404 @login_required @csrf_protect",
"= get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): post_old_title = post.title post_old_content = post.content",
"forum = get_forum_instance(forum_id) if forum: thread = get_thread_instance(forum, thread_id) if thread: if not",
"thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user), 'can_post':can_post and request.user.is_authenticated() and (not thread.closed or is_mod), 'poll':",
"post=new_post) thread.last_publication_datetime=new_post.publication_datetime thread.save() quote_list = Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quote.delete() return",
"import render, redirect from datetime import datetime from Forum.models import * from Forum.settings",
"template_ajax, c) else: return render(request, template, c) @login_required def logout(request, forum_id): lgout(request) forum",
"if (request.method == 'POST'): form = FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread',",
"post.title post_old_content = post.content if request.method == 'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST,",
"'title': 'Create Subforum', 'submit_btn_text': 'Create', } return render(request, template, c) else: c =",
"is_mod): can_post = subforum.canReplyThread(request.user) post_list = [] unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user):",
"# Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() <= forum.negative_score_event:",
"forum_id, subforum_id, subforum_slug, page=1, template=SUBFORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum = get_subforum_instance(forum,",
"return render(request, template_ajax, c) else: return render(request, template, c) raise Http404 @login_required def",
"not check_slug(subforum, subforum_slug): if page == 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else:",
"@csrf_protect def voteThreadPoll(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread =",
"forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug(), page=page) subforum = thread.parent",
"True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required",
"subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod =",
"{ 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum', 'title': 'Create Subforum', 'submit_btn_text': 'Create', }",
"post.title == \"\": post.title = post_old_title post.thread.name = post.title post.thread.save() post_edited.save() post.save() return",
"forum = get_forum_instance(forum_id) if forum: return redirect('base_forum', forum_id=forum.local_id) raise Http404 def forum(request, forum_id,",
"= th.isVisited(request.user) thread_list.append(th) page = int(page) -1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages >",
"if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_post.forum=forum new_post.thread=thread new_post.save() # Send",
"if not check_slug(thread, thread_slug): if page == 1: return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"post.score_event_sent = True post.save() signals.positive_score_event.send(sender=forum, post=post) response_data['score'] = post.score() return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise",
"if forum and forum.allow_down_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote",
"mod_permission = subforum.mod_permission, create_thread_permission = subforum.create_thread_permission, reply_thread_permission = subforum.reply_thread_permission, ) new_subforum_form = FormSubforum(instance=new_subforum)",
"request.method == 'POST': new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post",
"= Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return redirect('Forum.views.post', forum_id=forum.local_id,",
"and thread.poll_set.first().userCanVote(request.user): poll = thread.poll_set.first() else: poll = None page = int(page) -1",
"= FormPost(instance=new_post) if request.is_ajax(): template = template_ajax c = { 'forum_id':forum_id, 'form': new_post_form,",
"{ 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page], 'thread_current_page':page+1, 'thread_pages':range(max(page, 1), min(page+3, thread_num_pages+1)), 'is_moderator': is_mod, 'is_admin':forum.canAdministrate(request.user),",
"forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug(), page=page) if subforum.canView(request.user): is_mod = subforum.canModerate(request.user) can_create_thread = subforum.canCreateThread(request.user) subforum_list",
"if subforum.canView(request.user) and (not thread.hidden or is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and request.method",
"Send signal signals.downvote.send(sender=forum, user=request.user, post=post) if not post.score_event_sent and post.score() <= forum.negative_score_event: post.score_event_sent",
"content_type=\"application/json\") raise Http404 @login_required def votePostDown(request, forum_id, post_id): forum = get_forum_instance(forum_id) if forum",
"redirect('Forum.views.thread', forum_id=forum_id, thread_id=new_thread.local_id, thread_slug=new_thread.slug()) else: new_post = Post() new_post_form = FormNewThread(instance=new_post) c =",
"= [] for sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set",
"== 'POST': new_post = Post(publisher=request.user) new_post_form = FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post =",
"Http404 def forum(request, forum_id, page=1, template=MAIN_FORUM_TEMPLATE): forum = get_forum_instance(forum_id) if forum: subforum_slug =",
"-1 subforum_num_pages = int(ceil(float(len(thread_list))/float(forum.threads_per_page))) if (subforum_num_pages > page and 0 <= page) or",
"subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else: new_subforum = Subforum( forum = subforum.forum, view_permission = subforum.view_permission, mod_permission",
"@login_required def firstPostUnreadThread(request, forum_id, thread_id, thread_slug): forum = get_forum_instance(forum_id) if forum: thread =",
"request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c) @login_required def logout(request,",
"c = { 'forum_id':forum_id, 'form': form, 'thread': thread, } return render(request, template, c)",
"= get_thread_instance(forum, thread_id) if thread and (not thread.closed or thread.parent.canModerate(request.user)): if not check_slug(thread,",
"new_subforum.forum = forum new_subforum.creator = request.user new_subforum.save() return redirect('subforum', forum_id=forum_id, subforum_id=new_subforum.local_id, subforum_slug=new_subforum.slug()) else:",
"last_visit = get_last_visit_instance(request.user, thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return",
"= int(page) -1 thread_num_pages = int(ceil(float(len(post_list))/float(forum.posts_per_page))) if thread_num_pages > page and 0 <=",
"= thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt in unfiltered_post_list: if",
") new_subforum_form = FormSubforum(instance=new_subforum) c = { 'forum_id':forum_id, 'form': new_subforum_form, 'page_title': 'Create Subforum',",
"instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum new_subforum.forum",
"i in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\": option_list.append(opt) if",
"= FormPost_Mod(request.POST, instance=new_post) else: new_post_form = FormPost(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False)",
"and forum.allow_up_votes: post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): vote = get_vote_instance(request.user,",
"answer = request.POST.get(\"poll_answer\", False) if answer: thread.poll.vote(request.user, answer) return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug())",
"new_thread.save() if request.POST.get(\"add_poll\", \"False\") == \"True\" and request.POST.get(\"question\", \"\") != \"\": rang =",
"get_quote_instance(request.user, pt) pt.vote = get_vote_instance(request.user, pt) post_list.append(pt) if request.user.is_authenticated() and thread.poll_set.count() and thread.poll_set.first().userCanVote(request.user):",
"FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum = new_subforum_form.save(commit=False) new_subforum.local_id = forum.subforum_set.count() new_subforum.parent = subforum",
"{ 'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread', 'title': 'New Thread', 'submit_btn_text': 'Create', }",
"= 'removed' else: vote.type = \"Up\" vote.save() response_data['action'] = 'added' else: Vote(user=request.user, post=post,",
"else: edit_post_form = FormPost(request.POST, instance=post) if edit_post_form.is_valid(): post_edited = PostEdited( post=post, user=request.user, datetime=datetime.now(),",
"= [] unfiltered_post_list = thread.post_set.order_by('local_id') if not subforum.canModerate(request.user): unfiltered_post_list = unfiltered_post_list.exclude(hidden=True) for pt",
"'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid(): report_post = report_post_form.save(commit=False) report_post.user = request.user report_post.post",
"if found: page = (num/forum.posts_per_page)+1 return redirect('Forum.views.thread', forum_id=forum_id, thread_id=post.thread.local_id, thread_slug=post.thread.slug(), page=page, post_id=post_id) raise",
"new_post_form, 'page_title': 'New Thread', 'title': 'New Thread', 'submit_btn_text': 'Create', } return render(request, template,",
"redirect('Forum.views.saveThreadSettings', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) if thread.parent.canModerate(request.user): if (request.method == 'POST'): form = FormThreadSettings(request.POST,",
"Thread', 'submit_btn_text': 'Send', } return render(request, template, c) else: c = { 'forum_id':forum_id,",
"'forum_id':forum_id, 'form': new_post_form, 'page_title': 'New Thread', 'title': 'New Thread', 'submit_btn_text': 'Create', } return",
"post=post, user=request.user, datetime=datetime.now(), reason='', old_title=post_old_title, old_content=post_old_content, user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), )",
"redirect('Forum.views.newThread', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) if subforum.canCreateThread(request.user): if request.method == 'POST': new_post = Post(publisher=request.user)",
"= edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if post.title == \"\": post.title = post_old_title",
"= { 'forum_id':forum_id, 'form': report_post_form, 'post': post, } if request.is_ajax(): return render(request, template_ajax,",
"post_old_title post.thread.name = post.title post.thread.save() post_edited.save() post.save() return redirect('Forum.views.post', forum_id=forum_id, post_id=post.local_id) else: if",
"forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if post.thread.post_set.first() == post: if post.title == \"\":",
"thread_slug=thread.slug()) last_visit = get_last_visit_instance(request.user, thread) if last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post:",
"== 'POST': new_subforum_form = Subforum(forum=forum) new_subforum_form = FormSubforum(request.POST, instance=new_subforum_form) if new_subforum_form.is_valid(): new_subforum =",
"== 'POST': if post.thread.parent.canModerate(request.user): edit_post_form = FormPost_Mod(request.POST, instance=post) else: edit_post_form = FormPost(request.POST, instance=post)",
"if post and post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form = FormReportPost(request.POST) if report_post_form.is_valid():",
"subforum_slug = forum.main_forum.slug() return subforum(request, forum_id, 0, subforum_slug, page, template=template) raise Http404 def",
"user_is_moderator = post.thread.parent.canModerate(request.user), user_is_administrator = forum.canAdministrate(request.user), ) post = edit_post_form.save(commit=False) if post.thread.post_set.first() ==",
"forum_id, post_id): forum = get_forum_instance(forum_id) if forum: post = get_post_instance(forum, post_id) if post",
"login(request, forum_id, template=\"Forum/forms/login.html\", template_ajax=\"Forum/forms/ajax/login.html\"): form = None if request.method == 'POST': form =",
"sf in subforum.child_set.order_by('local_id'): if sf.canView(request.user): sf.is_visited = sf.isVisited(request.user) subforum_list.append(sf) sf_th_set = subforum.thread_set.order_by('-pinned', '-last_publication_datetime',",
"} return render(request, CANT_VIEW_CONTENT, c) raise Http404 @login_required @csrf_protect def voteThreadPoll(request, forum_id, thread_id,",
"= thread.post_set.order_by('local_id') for pt in unfiltered_post_list: if (not pt.hidden) or subforum.canModerate(request.user): post_list.append(pt) thread_num_pages",
"if request.is_ajax(): return render(request, template_ajax, c) else: return render(request, template, c) @login_required def",
"'added' return HttpResponse(json.dumps(response_data), content_type=\"application/json\") raise Http404 @login_required def votePostUp(request, forum_id, post_id): forum =",
"forum: thread = get_thread_instance(forum, thread_id) if thread: if not check_slug(thread, thread_slug): return redirect('Forum.views.voteThreadPoll',",
"quote.delete() return redirect('Forum.views.post', forum_id=forum_id, post_id=new_post.local_id) else: new_post = Post() quotes_text = \"\" quote_list",
"in rang: opt = request.POST.get(\"poll-option[\"+str(i)+\"]\", \"\") if opt != \"\": option_list.append(opt) if len(option_list)",
"last_visit: last_post = Post.objects.order_by('publication_datetime').filter(thread=thread, publication_datetime__gt=last_visit.datetime).first() if last_post: return redirect('Forum.views.post', forum_id=forum_id, post_id=last_post.local_id) print(\"shiet\") return",
"new_post.forum=forum new_post.thread=new_thread new_post.save() # Send new thread signal signals.thread_published.send(sender=forum, thread=new_thread) return redirect('Forum.views.thread', forum_id=forum_id,",
"FormPost_Mod(instance=new_post) else: new_post_form = FormPost(instance=new_post) if request.is_ajax(): template = template_ajax c = {",
"render(request, template, c) @login_required def logout(request, forum_id): lgout(request) forum = get_forum_instance(forum_id) if forum:",
"post=post, type=\"Up\").save() response_data['action'] = 'added' # Send signal signals.upvote.send(sender=forum, user=request.user, post=post) if not",
"\"Down\": vote.delete() response_data['action'] = 'removed' elif vote.type == \"Up\": vote.type = \"Down\" vote.save()",
"forum_id=forum_id, thread_id=thread.local_id, thread_slug=thread.slug(), page=page) raise Http404 @csrf_protect def saveThreadSettings(request, forum_id, thread_id, thread_slug, template=\"Forum/forms/thread_settings.html\"):",
"coding: utf-8 -*- import json from django.http import Http404, HttpResponse from django.views.decorators.csrf import",
"post and post.thread.parent.canView(request.user): quote = get_quote_instance(request.user, post) response_data = {} if quote: quote.delete()",
"FormThreadSettings(request.POST, instance=thread) if form.is_valid(): thread.save() return redirect('Forum.views.thread', forum_id=forum_id, thread_id=thread_id, thread_slug=thread.slug()) else: form =",
"get_post_instance(forum, post_id) if post: thread = post.thread post_list = thread.post_set.order_by('local_id') num = 0",
"set_visit(thread, request.user) thread.visit_counter += 1 thread.save() c = { 'forum_id':forum_id, 'thread': thread, 'post_list':post_list[(page*forum.posts_per_page):(page*forum.posts_per_page)+forum.posts_per_page],",
"subforum.canView(request.user) and (not thread.hidden or is_mod): if thread.poll: if thread.poll.userCanVote(request.user) and request.method ==",
"post = get_post_instance(forum, post_id) if post and post.thread.parent.canView(request.user): if request.method == 'POST': report_post_form",
"Quote.objects.filter(user=request.user, thread=thread) for quote in quote_list: quotes_text += \"[quote=\"+quote.post.publisher.username+\"]\"+quote.post.content+\"[/quote]\\n\\n\" new_post.content = quotes_text if",
"render(request, template, c) raise Http404 @login_required @csrf_protect def reportPost(request, forum_id, post_id, template=\"Forum/forms/report_post.html\", template_ajax=\"Forum/forms/ajax/report_post.html\"):",
"= FormNewThread(request.POST, instance=new_post) if new_post_form.is_valid(): new_post = new_post_form.save(commit=False) new_post.local_id = forum.post_set.count() new_thread =",
"page == 1: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id, subforum_slug=subforum.slug()) else: return redirect('Forum.views.subforum', forum_id=forum_id, subforum_id=subforum_id,"
] |
[
"y_dim self.layer_sizes = hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph =",
"###################################################################################################### # Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim,",
"buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error",
"boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): # Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size)",
"post sample predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel",
"var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP: # which copys weights from MLP by",
"train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError',",
"= np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) #",
"to use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph -",
"def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x = input # Generate target for",
"= None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05 self.ensemble_size = post_sample_size",
"= np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False)",
"axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc =",
"layer sizes \"\"\" self.replay_size = int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None #",
"= lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to sample with dropout masks self.lazy_ber_drop_mlp_update =",
"hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) ** 2) #",
"np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc",
"ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y,",
"# tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05 self.ensemble_size = post_sample_size self.post_sample_size =",
"- ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds",
"to ensemble's replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error",
"# define placeholder for parallel sampling # batch x n_post x dim lazy_bernoulli_dropout_mlp",
"= self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError',",
"tf.reduce_mean((self.y_ph - mlp_y) ** 2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss,",
"ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim,",
"bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must",
"keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y =",
"BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y",
"v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP: #",
"0.05 self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size self.batch_size = 100 self.bootstrapp_p = 0.75",
"self.batch_size = 100 self.bootstrapp_p = 0.75 # probability used to add to replay",
"- self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)",
"training=True) # Set training=True to sample with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp)",
"BernoulliDropoutMLP: # which copys weights from MLP by # sess.run(lazy_ber_drop_mlp_update) # , then",
"0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0",
"# TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ######################################################################################################",
"to sample with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in",
"the selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the (input,",
"tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05 self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size",
"if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc =",
"= 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0 boots_ensemble_loss = 0 else: ###########################################################################################",
"output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) ** 2) # mean-square-error",
"lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov))",
"# LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error =",
"= np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0)",
"return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess):",
"= np.matlib.repmat(x, self.post_sample_size, 1) # repmat x for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample",
"sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2)",
"hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True to use dropout",
"dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) **",
"then post sample predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for",
"self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP: # which copys weights",
"= y_dim self.layer_sizes = hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph",
"ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): # Train",
"# Define random target network # Note: initialize RNT weights far away from",
"uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) # repmat x for post sampling #",
"hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim))",
"_train(self, sess): # Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph:",
"sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2)",
"Sample and estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) # repmat x for",
"is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp",
"with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)])",
"logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x =",
"mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss = self.boots_ensemble.train(sess, self.batch_size) return mlp_outs[0], ber_drop_outs[0],",
"# 1. Create MLP to learn RTN: which is only used for LazyBernoulliDropoutMLP.",
"= tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble # Create",
"mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the same batch with MLP",
"output size :param hidden_sizes: hidden layer sizes \"\"\" self.replay_size = int(1e6) self.learning_rate =",
"tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) #",
"boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss)",
"tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP: # which copys",
"axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc =",
"Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size,",
"= mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) ** 2) # mean-square-error mlp_optimizer =",
"ber_drop_mlp_loss = 0 boots_ensemble_loss = 0 else: ########################################################################################### # Post Sample and estimate",
"# store the (input, target) to replay buffer self.mlp_replay_buffer.store(x, y) # add (x,",
"= tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses)",
"else: ########################################################################################### # Post Sample and estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1)",
"with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True)",
"ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble #",
"# add (x, y) to ensemble's replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y,",
"def _train(self, sess): # Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op],",
"Define random target network # Note: initialize RNT weights far away from 0",
"self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss = self.boots_ensemble.train(sess, self.batch_size) return",
"weights from MLP by # sess.run(lazy_ber_drop_mlp_update) # , then post sample predictions with",
"spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs,",
"target y ###################################################################################################### # Define LazyBernoulliDropout MLP # 1. Create MLP to learn",
"2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss,",
"self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define",
"= 0 boots_ensemble_loss = 0 else: ########################################################################################### # Post Sample and estimate uncertainty",
"fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph)",
"kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input,",
"TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### #",
"layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self,",
"loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble",
"get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x = input # Generate target for the",
"selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the (input, target)",
"self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss = self.boots_ensemble.train(sess, self.batch_size) return mlp_outs[0], ber_drop_outs[0], boots_ensemble_loss.mean()",
"(self.y_ph - self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer =",
"count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object):",
"as np import tensorflow as tf import time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP,",
"output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target y ###################################################################################################### # Define LazyBernoulliDropout MLP #",
"mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the same batch with MLP ber_drop_outs =",
"self.x_dim = x_dim self.y_dim = y_dim self.layer_sizes = hidden_sizes + [y_dim] self.x_ph =",
"(x, y) to ensemble's replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if",
"post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size :param y_dim: output size :param",
"data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc)",
"trained with dropout masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer,",
"self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph)",
"log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc',",
"np.matlib.repmat(x, self.post_sample_size, 1) # repmat x for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample =",
"set training=True to use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean(",
"# sess.run(lazy_ber_drop_mlp_update) # , then post sample predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'):",
"to replay buffer self.x_dim = x_dim self.y_dim = y_dim self.layer_sizes = hidden_sizes +",
"= mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP: # which copys weights from",
"lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph:",
"x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) # repmat x for post sampling # LazyBernoulliDropoutMLP",
"lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample,",
"self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05 self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size self.batch_size",
"# Define LazyBernoulliDropout MLP # 1. Create MLP to learn RTN: which is",
"# 2. Create lazy BernoulliDropoutMLP: # which copys weights from MLP by #",
"which is trained with dropout masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp =",
"np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc",
"= 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss =",
"y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size :param y_dim: output",
"y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the (input, target) to replay",
"ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss =",
"self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error)",
"y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger =",
"feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the same batch with",
"x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger",
"y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0",
"import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'):",
"= 0.05 self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size self.batch_size = 100 self.bootstrapp_p =",
"sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss = self.boots_ensemble.train(sess, self.batch_size)",
"dropout masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu,",
"and estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) # repmat x for post",
"ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess,",
"self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error,",
"Train BernoulliDropoutMLP on the same batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph:",
"self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### #",
"sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the same",
"v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP: # which is trained",
"sess.run(lazy_ber_drop_mlp_update) # , then post sample predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): #",
"x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs)",
"__init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size :param",
"kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target y ######################################################################################################",
"tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP:",
"logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size :param y_dim: output size :param hidden_sizes:",
"# BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error =",
"1) # repmat x for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph:",
"target for the selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store",
"boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0 boots_ensemble_loss = 0 else:",
"x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size :param y_dim:",
"lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0 boots_ensemble_loss = 0 else: ########################################################################################### # Post",
"learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess,",
"and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y",
"replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name,",
"= np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss =",
"self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size self.batch_size = 100 self.bootstrapp_p = 0.75 #",
"self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) ** 2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op",
"= BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True",
"parallel sampling # batch x n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate,",
"mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) #",
"- mlp_y) ** 2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP'))",
"tf import time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer",
"lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time()",
"Define BernoulliDropout MLP: # which is trained with dropout masks and regularization term",
"mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP:",
"feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov",
"predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel sampling #",
"ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0 boots_ensemble_loss",
"Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x = input # Generate",
"import time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import",
"term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph,",
"ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble",
"= BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must set",
"###################################################################################################### # Define LazyBernoulliDropout MLP # 1. Create MLP to learn RTN: which",
"learn RTN: which is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size)",
"= RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y",
"post_sample_size self.post_sample_size = post_sample_size self.batch_size = 100 self.bootstrapp_p = 0.75 # probability used",
"Note: initialize RNT weights far away from 0 and keep fixed random_net =",
"= MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target",
"# Train BernoulliDropoutMLP on the same batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op],",
"feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov",
"masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel sampling # batch x n_post",
"# , then post sample predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define",
"with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error =",
"x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov =",
"BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to",
"= 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss =",
"t, start_time): x = input # Generate target for the selected input y",
"ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError',",
"self.random_net_y = random_net(self.x_ph) # target y ###################################################################################################### # Define LazyBernoulliDropout MLP # 1.",
"self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time',",
"self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid)",
"hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target y ###################################################################################################### # Define LazyBernoulliDropout MLP",
"# Set training=True to sample with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for",
"tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) # TODO:",
"x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov =",
"= np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False)",
"Define LazyBernoulliDropout MLP # 1. Create MLP to learn RTN: which is only",
"BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger",
"= random_net(self.x_ph) # target y ###################################################################################################### # Define LazyBernoulliDropout MLP # 1. Create",
"# mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy",
"tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble # Create BootstrappedEnsembleNN",
"# train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t)",
"MLP to learn RTN: which is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim,",
"tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define random target",
"self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate =",
"boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred),",
"from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer",
"0 ber_drop_mlp_loss = 0 boots_ensemble_loss = 0 else: ########################################################################################### # Post Sample and",
"self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define random target network # Note:",
"mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) ** 2) # mean-square-error mlp_optimizer",
"for the selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the",
"start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def",
"= MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y)",
"self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss',",
"bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True to use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum(",
"sizes \"\"\" self.replay_size = int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01)",
"BernoulliDropout MLP: # which is trained with dropout masks and regularization term with",
"BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer,",
"self.replay_size = int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer =",
"MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update)",
"lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample =",
"sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the (input, target) to replay buffer self.mlp_replay_buffer.store(x,",
"# Note: initialize RNT weights far away from 0 and keep fixed random_net",
"from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def",
"np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## #",
"1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05 self.ensemble_size",
"bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error",
"spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from",
"0 and keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid)",
"mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on",
"replay buffer self.x_dim = x_dim self.y_dim = y_dim self.layer_sizes = hidden_sizes + [y_dim]",
"MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target y",
"self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the same batch",
"self.layer_sizes = hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32,",
"= 0 ber_drop_mlp_loss = 0 boots_ensemble_loss = 0 else: ########################################################################################### # Post Sample",
"ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y -",
"time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss,",
"spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self,",
"= input # Generate target for the selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph:",
"lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss)",
"in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP: # which is trained with",
"feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the (input, target) to replay buffer self.mlp_replay_buffer.store(x, y)",
"store the (input, target) to replay buffer self.mlp_replay_buffer.store(x, y) # add (x, y)",
"= np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling})",
"np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble",
"masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### #",
"input # Generate target for the selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1,",
"MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss",
"Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']})",
"self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x = input",
"[y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### #",
"######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step',",
"# which copys weights from MLP by # sess.run(lazy_ber_drop_mlp_update) # , then post",
"LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y",
"Create lazy BernoulliDropoutMLP: # which copys weights from MLP by # sess.run(lazy_ber_drop_mlp_update) #",
"ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain'))",
"= ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'):",
"= tf.reduce_mean((self.y_ph - mlp_y) ** 2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op =",
"is trained with dropout masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes,",
"self.bootstrapp_p = 0.75 # probability used to add to replay buffer self.x_dim =",
"######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc',",
"= sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the",
"MLP: # which is trained with dropout masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'):",
"= np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## # log",
"self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss',",
"self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov",
"for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample,",
"BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger,",
"ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): # Train MLP mlp_batch =",
"v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP: # which is",
"# target y ###################################################################################################### # Define LazyBernoulliDropout MLP # 1. Create MLP to",
"boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov))",
"RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y =",
"from MLP by # sess.run(lazy_ber_drop_mlp_update) # , then post sample predictions with dropout",
":param x_dim: input size :param y_dim: output size :param hidden_sizes: hidden layer sizes",
"'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size,",
"x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define random target network #",
"import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx",
"loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size :param y_dim: output size :param hidden_sizes: hidden",
"= 0 else: ########################################################################################### # Post Sample and estimate uncertainty x_postSampling = np.matlib.repmat(x,",
"only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp =",
"lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set",
"UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input",
"sample with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables,",
"None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05 self.ensemble_size = post_sample_size self.post_sample_size",
"100 self.bootstrapp_p = 0.75 # probability used to add to replay buffer self.x_dim",
"input size :param y_dim: output size :param hidden_sizes: hidden layer sizes \"\"\" self.replay_size",
"\"\"\" :param x_dim: input size :param y_dim: output size :param hidden_sizes: hidden layer",
"lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): # Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs",
"t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc)",
"= hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None,",
"# BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y",
"used to add to replay buffer self.x_dim = x_dim self.y_dim = y_dim self.layer_sizes",
"boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): # Train MLP",
"dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ######################################################################################################",
"self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with",
"import tensorflow as tf import time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars,",
"placeholder for parallel sampling # batch x n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes,",
"training=True) # Must set training=True to use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain'))",
"np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error =",
"x_dim self.y_dim = y_dim self.layer_sizes = hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None,",
"###################################################################################################### # Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t,",
"zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP: # which is trained with dropout",
"import numpy as np import tensorflow as tf import time from spinup.algos.ude_td3_new.core import",
"= 1e-6 self.dropout_rate = 0.05 self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size self.batch_size =",
"which is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'):",
"mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph -",
"BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y -",
"with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate)",
"MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import",
"self.post_sample_size = post_sample_size self.batch_size = 100 self.bootstrapp_p = 0.75 # probability used to",
"get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger class",
"y_dim: output size :param hidden_sizes: hidden layer sizes \"\"\" self.replay_size = int(1e6) self.learning_rate",
"0.75 # probability used to add to replay buffer self.x_dim = x_dim self.y_dim",
"t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0",
"repmat x for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred",
"tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) #",
"masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid)",
"MLP by # sess.run(lazy_ber_drop_mlp_update) # , then post sample predictions with dropout masks.",
"ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds =",
"lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to sample with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp,",
"ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc,",
"rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ########################################################################################",
"MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) **",
"** 2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2.",
"# Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim,",
"# batch x n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid)",
"input, sess, t, start_time): x = input # Generate target for the selected",
"tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define random target network # Note: initialize RNT",
"Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x",
"dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to sample with",
"MLP # 1. Create MLP to learn RTN: which is only used for",
"BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph,",
"np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error",
"use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y)",
"dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel sampling # batch x",
"ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc",
"away from 0 and keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8),",
"copys weights from MLP by # sess.run(lazy_ber_drop_mlp_update) # , then post sample predictions",
"class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim:",
"ensemble's replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error =",
":param y_dim: output size :param hidden_sizes: hidden layer sizes \"\"\" self.replay_size = int(1e6)",
"lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc",
"Generate target for the selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] #",
"boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc,",
"= post_sample_size self.batch_size = 100 self.bootstrapp_p = 0.75 # probability used to add",
"output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to sample with dropout masks",
"= 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc =",
"x.reshape(1, -1)})[0] # store the (input, target) to replay buffer self.mlp_replay_buffer.store(x, y) #",
"np import tensorflow as tf import time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble,",
"feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss = self.boots_ensemble.train(sess, self.batch_size) return mlp_outs[0],",
"mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2",
"tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer",
"boots_ensemble_loss] def _train(self, sess): # Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss,",
"Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param",
"int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate",
"1e-6 self.dropout_rate = 0.05 self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size self.batch_size = 100",
"weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to sample",
"weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True to",
"self.dropout_rate = 0.05 self.ensemble_size = post_sample_size self.post_sample_size = post_sample_size self.batch_size = 100 self.bootstrapp_p",
"start_time): x = input # Generate target for the selected input y =",
"0 boots_ensemble_loss = 0 else: ########################################################################################### # Post Sample and estimate uncertainty x_postSampling",
"0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0 boots_ensemble_loss = 0 else: ########################################################################################### #",
"LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu,",
"self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss,",
"same batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) #",
"1. Create MLP to learn RTN: which is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer",
"sess, t, start_time): x = input # Generate target for the selected input",
"with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss =",
"0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0 boots_ensemble_loss = 0",
"on the same batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph:",
"self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self,",
"# Define BernoulliDropout MLP: # which is trained with dropout masks and regularization",
"self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc",
"# which is trained with dropout masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp",
"mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP: #",
"= sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred),",
"# Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time):",
"target) to replay buffer self.mlp_replay_buffer.store(x, y) # add (x, y) to ensemble's replay",
"to learn RTN: which is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim,",
"= np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False)",
"for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP: # which",
"dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) #",
"boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss",
"BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger",
"self.mlp_replay_buffer.store(x, y) # add (x, y) to ensemble's replay buffer with probability bootstrapp_p",
"= 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc =",
"+ [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ######################################################################################################",
"ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0)",
"the same batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']})",
"size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss",
"x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True)",
"with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel sampling # batch x n_post x",
"output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True to use dropout mask",
"from 0 and keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu,",
"x_dim: input size :param y_dim: output size :param hidden_sizes: hidden layer sizes \"\"\"",
"kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) ** 2)",
"lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): # Train MLP mlp_batch",
"########################################################################################### # Post Sample and estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) #",
"# probability used to add to replay buffer self.x_dim = x_dim self.y_dim =",
"ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time)",
"boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return",
"<reponame>LinghengMeng/spinningup import numpy as np import tensorflow as tf import time from spinup.algos.ude_td3_new.core",
"as tf import time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from",
"x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov =",
"mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP: # which copys weights from MLP",
"self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc',",
"self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss',",
"sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error",
"self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05 self.ensemble_size =",
"Must set training=True to use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss =",
"= sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the (input, target) to replay buffer",
"= BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define",
"= sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble boots_ensemble_loss = self.boots_ensemble.train(sess,",
"network # Note: initialize RNT weights far away from 0 and keep fixed",
"by # sess.run(lazy_ber_drop_mlp_update) # , then post sample predictions with dropout masks. with",
"# Generate target for the selected input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0]",
"post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0)",
"-1)})[0] # store the (input, target) to replay buffer self.mlp_replay_buffer.store(x, y) # add",
"for parallel sampling # batch x n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6,",
"= np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ########################################################################################",
"self.y_dim = y_dim self.layer_sizes = hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim))",
"used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes,",
"= 0.75 # probability used to add to replay buffer self.x_dim = x_dim",
"y) to ensemble's replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size:",
"size :param y_dim: output size :param hidden_sizes: hidden layer sizes \"\"\" self.replay_size =",
"# log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc)",
"random target network # Note: initialize RNT weights far away from 0 and",
"0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0",
"= tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp in zip(mlp.variables, lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout",
"the (input, target) to replay buffer self.mlp_replay_buffer.store(x, y) # add (x, y) to",
"= sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y - lazy_ber_drop_mlp_pred),",
"# Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph:",
"self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to sample with dropout masks self.lazy_ber_drop_mlp_update",
"np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP",
"lazy BernoulliDropoutMLP: # which copys weights from MLP by # sess.run(lazy_ber_drop_mlp_update) # ,",
"var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define BootstrappedEnsemble # Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble =",
"tensorflow as tf import time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars",
"2. Create lazy BernoulliDropoutMLP: # which copys weights from MLP by # sess.run(lazy_ber_drop_mlp_update)",
"dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True to use",
"target network # Note: initialize RNT weights far away from 0 and keep",
"\"\"\" self.replay_size = int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer",
"self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error,",
"RTN: which is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with",
"probability used to add to replay buffer self.x_dim = x_dim self.y_dim = y_dim",
"lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error,",
"sampling # batch x n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu,",
"numpy as np import tensorflow as tf import time from spinup.algos.ude_td3_new.core import MLP,",
"tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ######################################################################################################",
"0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0",
"rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred =",
"random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) #",
"hidden layer sizes \"\"\" self.replay_size = int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None",
"EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\"",
", then post sample predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder",
"= post_sample_size self.post_sample_size = post_sample_size self.batch_size = 100 self.bootstrapp_p = 0.75 # probability",
"buffer self.x_dim = x_dim self.y_dim = y_dim self.layer_sizes = hidden_sizes + [y_dim] self.x_ph",
"# repmat x for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling})",
"boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss",
"###################################################################################################### # Define random target network # Note: initialize RNT weights far away",
"random_net(self.x_ph) # target y ###################################################################################################### # Define LazyBernoulliDropout MLP # 1. Create MLP",
"** 2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op =",
"np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## # log data",
"self.x_ph = tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define",
"ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2 +",
"axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc =",
"input y = sess.run(self.random_net_y, feed_dict={self.x_ph: x.reshape(1, -1)})[0] # store the (input, target) to",
"batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train",
"- boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train",
"hidden_sizes: hidden layer sizes \"\"\" self.replay_size = int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer =",
"sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the same batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss,",
"boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss,",
"self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False)",
"batch x n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y",
"post_sample_size self.batch_size = 100 self.bootstrapp_p = 0.75 # probability used to add to",
"import ReplayBuffer, RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim,",
"initialize RNT weights far away from 0 and keep fixed random_net = MLP(self.layer_sizes,",
"ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BEPredError', boots_ensemble_pred_error) self.uncertainty_on_random_net_logger.log_tabular('LBDUnc', lazy_ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss)",
"regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y =",
"sample predictions with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel sampling",
"2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create",
"with dropout masks and regularization term with tf.variable_scope('BernoulliDropoutUncertaintyTrain'): bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate,",
"maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target y ###################################################################################################### # Define LazyBernoulliDropout",
"Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph, layer_sizes=self.layer_sizes,",
"RNT weights far away from 0 and keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8,",
"y_ph=self.y_ph, layer_sizes=self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, learning_rate=self.learning_rate) ###################################################################################################### # Define logger self.uncertainty_on_random_net_logger = Logger(output_fname=loger_file_name, **logger_kwargs) def",
"ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov))",
"ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x)",
"= tf.placeholder(dtype=tf.float32, shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define random",
"with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) # Train BootstrappedEnsemble",
"- lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample",
"y ###################################################################################################### # Define LazyBernoulliDropout MLP # 1. Create MLP to learn RTN:",
"mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph - mlp_y) ** 2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)",
"= np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error",
"ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): # Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs =",
"= np.linalg.norm((y - lazy_ber_drop_mlp_pred), ord=2) lazy_ber_drop_mlp_postSample_cov = np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) #",
"far away from 0 and keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8,",
"= self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2)",
"self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic",
"**logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x = input # Generate target",
"= 100 self.bootstrapp_p = 0.75 # probability used to add to replay buffer",
"np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc",
"replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0",
"self.uncertainty_on_random_net_logger.log_tabular('BDUnc', ber_drop_mlp_postSample_unc) self.uncertainty_on_random_net_logger.log_tabular('BEUnc', boots_ensemble_preds_unc) self.uncertainty_on_random_net_logger.log_tabular('LBDLoss', lazy_ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BDLoss', ber_drop_mlp_loss) self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() -",
"from spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size,",
"ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample, axis=0) ber_drop_mlp_pred_error = np.linalg.norm((y - ber_drop_mlp_pred), ord=2) ber_drop_mlp_postSample_cov = np.cov(ber_drop_mlp_postSample,",
"estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) # repmat x for post sampling",
"def __init__(self, x_dim, y_dim, hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size",
"= tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define random target network # Note: initialize",
"size :param hidden_sizes: hidden layer sizes \"\"\" self.replay_size = int(1e6) self.learning_rate = 1e-3",
"Set training=True to sample with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp,",
"mlp_y) ** 2) # mean-square-error mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) #",
"= 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss = 0 boots_ensemble_loss =",
"self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op",
"self.post_sample_size, 1) # repmat x for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y,",
"to add to replay buffer self.x_dim = x_dim self.y_dim = y_dim self.layer_sizes =",
"replay buffer self.mlp_replay_buffer.store(x, y) # add (x, y) to ensemble's replay buffer with",
"self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP",
"y_dim)) ###################################################################################################### # Define random target network # Note: initialize RNT weights far",
"and keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y",
"training=True to sample with dropout masks self.lazy_ber_drop_mlp_update = tf.group([tf.assign(v_lazy_ber_drop_mlp, v_mlp) for v_mlp, v_lazy_ber_drop_mlp",
"# Must set training=True to use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss",
"lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred = np.mean(lazy_ber_drop_mlp_postSample, axis=0) lazy_ber_drop_mlp_pred_error = np.linalg.norm((y -",
"x = input # Generate target for the selected input y = sess.run(self.random_net_y,",
"hidden_sizes, post_sample_size, logger_kwargs, loger_file_name='unc_on_random_net.txt'): \"\"\" :param x_dim: input size :param y_dim: output size",
"bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target y ###################################################################################################### # Define",
"boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## #",
"np.cov(lazy_ber_drop_mlp_postSample, rowvar=False) lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred",
"= x_dim self.y_dim = y_dim self.layer_sizes = hidden_sizes + [y_dim] self.x_ph = tf.placeholder(dtype=tf.float32,",
"= Logger(output_fname=loger_file_name, **logger_kwargs) def get_predError_and_uncerEstimate_on_policy_based_input(self, input, sess, t, start_time): x = input #",
"shape=(None, y_dim)) ###################################################################################################### # Define random target network # Note: initialize RNT weights",
"= bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True to use dropout mask ber_drop_mlp_reg_losses =",
"y) # add (x, y) to ensemble's replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x,",
"= np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred",
"0 else: ########################################################################################### # Post Sample and estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size,",
"= self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'], self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train",
"self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error =",
"np.cov(ber_drop_mlp_postSample, rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred =",
"Post Sample and estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) # repmat x",
"(input, target) to replay buffer self.mlp_replay_buffer.store(x, y) # add (x, y) to ensemble's",
"maxval=0.8), bias_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8), hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.random_net_y = random_net(self.x_ph) # target y ###################################################################################################### #",
":param hidden_sizes: hidden layer sizes \"\"\" self.replay_size = int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer",
"boots_ensemble_loss = 0 else: ########################################################################################### # Post Sample and estimate uncertainty x_postSampling =",
"training=True to use dropout mask ber_drop_mlp_reg_losses = tf.reduce_sum( tf.losses.get_regularization_losses(scope='BernoulliDropoutUncertaintyTrain')) self.ber_drop_mlp_loss = tf.reduce_mean( (self.y_ph",
"self.uncertainty_on_random_net_logger.log_tabular('BELoss', boots_ensemble_loss) self.uncertainty_on_random_net_logger.log_tabular('Time', time.time() - start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc,",
"weights far away from 0 and keep fixed random_net = MLP(self.layer_sizes, kernel_initializer=tf.keras.initializers.random_uniform(minval=-0.8, maxval=0.8),",
"boots_ensemble_loss = self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error) self.uncertainty_on_random_net_logger.log_tabular('BDPredError', ber_drop_mlp_pred_error)",
"= tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.mlp_train_op = mlp_optimizer.minimize(self.mlp_loss, var_list=get_vars('MLP')) # 2. Create lazy BernoulliDropoutMLP: # which",
"= int(1e6) self.learning_rate = 1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6",
"+ ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars(",
"tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) mlp_y = mlp(self.x_ph) self.mlp_loss = tf.reduce_mean((self.y_ph",
"which copys weights from MLP by # sess.run(lazy_ber_drop_mlp_update) # , then post sample",
"buffer self.mlp_replay_buffer.store(x, y) # add (x, y) to ensemble's replay buffer with probability",
"probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p) if t<self.batch_size: lazy_ber_drop_mlp_pred_error = 0 ber_drop_mlp_pred_error = 0",
"with dropout masks. with tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel sampling # batch",
"n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph,",
"self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True to use dropout mask ber_drop_mlp_reg_losses",
"to replay buffer self.mlp_replay_buffer.store(x, y) # add (x, y) to ensemble's replay buffer",
"Create MLP to learn RTN: which is only used for LazyBernoulliDropoutMLP. self.mlp_replay_buffer =",
"BernoulliDropoutMLP on the same batch with MLP ber_drop_outs = sess.run([self.ber_drop_mlp_loss, self.ber_drop_mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'],",
"self.y_ph: mlp_batch['y']}) sess.run(self.lazy_ber_drop_mlp_update) # Train BernoulliDropoutMLP on the same batch with MLP ber_drop_outs",
"lazy_bernoulli_dropout_mlp.variables)]) ###################################################################################################### # Define BernoulliDropout MLP: # which is trained with dropout masks",
"boots_ensemble_preds_pred = np.mean(boots_ensemble_preds, axis=0) boots_ensemble_pred_error = np.linalg.norm((y - boots_ensemble_preds_pred), ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds,",
"lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess) ######################################################################################## # log data self.uncertainty_on_random_net_logger.log_tabular('Step', t) self.uncertainty_on_random_net_logger.log_tabular('LBDPredError', lazy_ber_drop_mlp_pred_error)",
"time from spinup.algos.ude_td3_new.core import MLP, BeroulliDropoutMLP, BootstrappedEnsemble, get_vars, count_vars from spinup.algos.ude_td3_new.replay_buffer import ReplayBuffer,",
"- start_time) self.uncertainty_on_random_net_logger.dump_tabular(print_data=False) return [lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss]",
"x for post sampling # LazyBernoulliDropoutMLP lazy_ber_drop_mlp_postSample = sess.run(self.lazy_ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) lazy_ber_drop_mlp_pred =",
"ord=2) boots_ensemble_preds_cov = np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss,",
"RandomNetReplayBuffer from spinup.utils.logx import EpochLogger, Logger class UncertaintyOnRandomNetwork(object): def __init__(self, x_dim, y_dim, hidden_sizes,",
"= tf.reduce_mean( (self.y_ph - self.ber_drop_mlp_y) ** 2 + ber_drop_mlp_reg_losses) # TODO: heteroscedastic loss",
"0 ber_drop_mlp_pred_error = 0 boots_ensemble_pred_error = 0 lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0",
"rowvar=False) ber_drop_mlp_postSample_unc = np.sum(np.diag(ber_drop_mlp_postSample_cov)) # BootstrappedEnsemble boots_ensemble_preds = self.boots_ensemble.prediction(sess, x) boots_ensemble_preds_pred = np.mean(boots_ensemble_preds,",
"define placeholder for parallel sampling # batch x n_post x dim lazy_bernoulli_dropout_mlp =",
"###################################################################################################### # Define BernoulliDropout MLP: # which is trained with dropout masks and",
"# Create BootstrappedEnsembleNN with tf.variable_scope('BootstrappedEnsembleUncertainty'): self.boots_ensemble = BootstrappedEnsemble(ensemble_size=self.ensemble_size, x_dim=self.x_dim, y_dim=self.y_dim, replay_size=self.replay_size, x_ph=self.x_ph, y_ph=self.y_ph,",
"add to replay buffer self.x_dim = x_dim self.y_dim = y_dim self.layer_sizes = hidden_sizes",
"for LazyBernoulliDropoutMLP. self.mlp_replay_buffer = RandomNetReplayBuffer(self.x_dim, self.y_dim, size=self.replay_size) with tf.variable_scope('MLP'): mlp = MLP(self.layer_sizes, kernel_regularizer=self.mlp_kernel_regularizer,",
"BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=self.bernoulli_dropout_weight_regularizer, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.ber_drop_mlp_y = bernoulli_dropout_mlp(self.x_ph, training=True) # Must set training=True",
"sess): # Train MLP mlp_batch = self.mlp_replay_buffer.sample_batch(self.batch_size) mlp_outs = sess.run([self.mlp_loss, self.mlp_train_op], feed_dict={self.x_ph: mlp_batch['x'],",
"= 1e-3 self.mlp_kernel_regularizer = None # tf.keras.regularizers.l2(l=0.01) self.bernoulli_dropout_weight_regularizer = 1e-6 self.dropout_rate = 0.05",
"lazy_ber_drop_mlp_postSample_unc = 0 ber_drop_mlp_postSample_unc = 0 boots_ensemble_preds_unc = 0 lazy_ber_drop_mlp_loss = 0 ber_drop_mlp_loss",
"lazy_ber_drop_mlp_postSample_unc = np.sum(np.diag(lazy_ber_drop_mlp_postSample_cov)) # BernoulliDropoutMLP ber_drop_mlp_postSample = sess.run(self.ber_drop_mlp_y, feed_dict={self.x_ph: x_postSampling}) ber_drop_mlp_pred = np.mean(ber_drop_mlp_postSample,",
"add (x, y) to ensemble's replay buffer with probability bootstrapp_p self.boots_ensemble.add_to_replay_buffer(x, y, self.bootstrapp_p)",
"np.cov(boots_ensemble_preds, rowvar=False) boots_ensemble_preds_unc = np.sum(np.diag(boots_ensemble_preds_cov)) ######################################################################################## # train lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss = self._train(sess)",
"heteroscedastic loss ber_drop_mlp_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.ber_drop_mlp_train_op = ber_drop_mlp_optimizer.minimize(self.ber_drop_mlp_loss, var_list=get_vars( 'BernoulliDropoutUncertaintyTrain')) ###################################################################################################### # Define",
"LazyBernoulliDropout MLP # 1. Create MLP to learn RTN: which is only used",
"[lazy_ber_drop_mlp_pred_error, ber_drop_mlp_pred_error, boots_ensemble_pred_error, lazy_ber_drop_mlp_postSample_unc, ber_drop_mlp_postSample_unc, boots_ensemble_preds_unc, lazy_ber_drop_mlp_loss, ber_drop_mlp_loss, boots_ensemble_loss] def _train(self, sess): #",
"x n_post x dim lazy_bernoulli_dropout_mlp = BeroulliDropoutMLP(self.layer_sizes, weight_regularizer=1e-6, dropout_rate=self.dropout_rate, hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y =",
"tf.variable_scope('LazyBernoulliDropoutUncertaintySample'): # define placeholder for parallel sampling # batch x n_post x dim",
"# Post Sample and estimate uncertainty x_postSampling = np.matlib.repmat(x, self.post_sample_size, 1) # repmat",
"hidden_activation=tf.keras.activations.relu, output_activation=tf.keras.activations.sigmoid) self.lazy_ber_drop_mlp_y = lazy_bernoulli_dropout_mlp(self.x_ph, training=True) # Set training=True to sample with dropout",
"shape=(None, x_dim)) self.y_ph = tf.placeholder(dtype=tf.float32, shape=(None, y_dim)) ###################################################################################################### # Define random target network"
] |
[
"import format_object from landscape.lib.log import log_failure from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\"",
"specified as a string, a C{_persist} attribute will be available after registration. \"\"\"",
"def send_message(self, urgent): message = self.get_message() if message is not None: info(\"Queueing a",
"was called. Subclasses should provide a get_data method, and message_type, message_key, and persist_name",
"= None def _reset(self): if self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property def persist(self):",
"to the Landscape server which does not constantly change. New messages will only",
"a get_data method, and message_type, message_key, and persist_name class attributes. \"\"\" message_type =",
"and persist_name class attributes. \"\"\" message_type = None message_key = None def get_message(self):",
"urgent): message = self.get_message() if message is not None: info(\"Queueing a message with",
"data should override this method. \"\"\" pass def exchange(self, urgent=False): \"\"\" Conditionally add",
"this method. \"\"\" pass def exchange(self, urgent=False): \"\"\" Conditionally add a message to",
"def persist_data(self): \"\"\" Sub-classes that need to defer the saving of persistent data",
"for the C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\" A utility for plugins",
"result of get_data() has changed since the last time it was called. Subclasses",
"message to the message store if new data is available. \"\"\" return self.registry.broker.call_if_accepted(self.message_type,",
"return self.client class DataWatcher(MonitorPlugin): \"\"\" A utility for plugins which send data to",
"BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified as a string, a C{_persist}",
"from logging import info from twisted.internet.defer import succeed from landscape.log import format_object from",
"the result of get_data() has changed since the last time it was called.",
"last time it was called. Subclasses should provide a get_data method, and message_type,",
"!= data: self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key: data} def send_message(self, urgent): message",
"landscape.lib.log import log_failure from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If",
"def monitor(self): \"\"\"An alias for the C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\"",
"and message_type, message_key, and persist_name class attributes. \"\"\" message_type = None message_key =",
"\"\"\" Construct a message with the latest data, or None, if the data",
"the data has not changed since the last call. \"\"\" data = self.get_data()",
"urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None) def persist_data(self): \"\"\"",
"class attributes. \"\"\" message_type = None message_key = None def get_message(self): \"\"\" Construct",
"from landscape.lib.log import log_failure from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name:",
"constantly change. New messages will only be sent when the result of get_data()",
"message is not None: info(\"Queueing a message with updated data watcher info \"",
"is not None: info(\"Queueing a message with updated data watcher info \" \"for",
"message = self.get_message() if message is not None: info(\"Queueing a message with updated",
"has not changed since the last call. \"\"\" data = self.get_data() if self._persist.get(\"data\")",
"landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified as a string,",
"add a message to the message store if new data is available. \"\"\"",
"since the last call. \"\"\" data = self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\",",
"= None scope = None def register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is",
"\"\"\"An alias for the C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\" A utility",
"self.client class DataWatcher(MonitorPlugin): \"\"\" A utility for plugins which send data to the",
"to the message store if new data is available. \"\"\" return self.registry.broker.call_if_accepted(self.message_type, self.send_message,",
"self._persist = None def _reset(self): if self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property def",
"\" \"for %s.\", format_object(self)) result = self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data()",
"None message_key = None def get_message(self): \"\"\" Construct a message with the latest",
"data = self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key:",
"persist_data(self): \"\"\" Sub-classes that need to defer the saving of persistent data should",
"since the last time it was called. Subclasses should provide a get_data method,",
"None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist = None def _reset(self): if self.persist_name is",
"data, or None, if the data has not changed since the last call.",
"\"\"\" Conditionally add a message to the message store if new data is",
"a message to the message store if new data is available. \"\"\" return",
"which send data to the Landscape server which does not constantly change. New",
"send_message(self, urgent): message = self.get_message() if message is not None: info(\"Queueing a message",
"self.persist_name is not None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist = None def _reset(self):",
"self.monitor.persist.root_at(self.persist_name) else: self._persist = None def _reset(self): if self.persist_name is not None: self.registry.persist.remove(self.persist_name)",
"exchange(self, urgent=False): \"\"\" Conditionally add a message to the message store if new",
"None def get_message(self): \"\"\" Construct a message with the latest data, or None,",
"with updated data watcher info \" \"for %s.\", format_object(self)) result = self.registry.broker.send_message( message,",
"<reponame>pengwu/scapy_env from logging import info from twisted.internet.defer import succeed from landscape.log import format_object",
"get_message(self): \"\"\" Construct a message with the latest data, or None, if the",
"the saving of persistent data should override this method. \"\"\" pass def exchange(self,",
"result = self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result",
"import log_failure from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified",
"If specified as a string, a C{_persist} attribute will be available after registration.",
"utility for plugins which send data to the Landscape server which does not",
"will be available after registration. \"\"\" persist_name = None scope = None def",
"= self.get_message() if message is not None: info(\"Queueing a message with updated data",
"the message store if new data is available. \"\"\" return self.registry.broker.call_if_accepted(self.message_type, self.send_message, urgent)",
"message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None) def",
"A utility for plugins which send data to the Landscape server which does",
"succeed from landscape.log import format_object from landscape.lib.log import log_failure from landscape.broker.client import BrokerClientPlugin",
"method. \"\"\" pass def exchange(self, urgent=False): \"\"\" Conditionally add a message to the",
"self.message_type, self.message_key: data} def send_message(self, urgent): message = self.get_message() if message is not",
"message with updated data watcher info \" \"for %s.\", format_object(self)) result = self.registry.broker.send_message(",
"def persist(self): \"\"\"Return our L{Persist}, if any.\"\"\" return self._persist @property def monitor(self): \"\"\"An",
"persist(self): \"\"\"Return our L{Persist}, if any.\"\"\" return self._persist @property def monitor(self): \"\"\"An alias",
"info \" \"for %s.\", format_object(self)) result = self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id):",
"plugins which send data to the Landscape server which does not constantly change.",
"self.message_key: data} def send_message(self, urgent): message = self.get_message() if message is not None:",
"not constantly change. New messages will only be sent when the result of",
"self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key: data} def send_message(self, urgent): message = self.get_message()",
"self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key: data} def send_message(self, urgent):",
"%s.\", format_object(self)) result = self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure)",
"message_type = None message_key = None def get_message(self): \"\"\" Construct a message with",
"if any.\"\"\" return self._persist @property def monitor(self): \"\"\"An alias for the C{client} attribute.\"\"\"",
"from landscape.log import format_object from landscape.lib.log import log_failure from landscape.broker.client import BrokerClientPlugin class",
"watcher info \" \"for %s.\", format_object(self)) result = self.registry.broker.send_message( message, self._session_id, urgent=urgent) def",
"only be sent when the result of get_data() has changed since the last",
"self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None) def persist_data(self):",
"with the latest data, or None, if the data has not changed since",
"monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is not None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist",
"self).register(monitor) if self.persist_name is not None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist = None",
"will only be sent when the result of get_data() has changed since the",
"\"\"\" data = self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return {\"type\": self.message_type,",
"string, a C{_persist} attribute will be available after registration. \"\"\" persist_name = None",
"Subclasses should provide a get_data method, and message_type, message_key, and persist_name class attributes.",
"\"\"\" message_type = None message_key = None def get_message(self): \"\"\" Construct a message",
"None: info(\"Queueing a message with updated data watcher info \" \"for %s.\", format_object(self))",
"\"for %s.\", format_object(self)) result = self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data)",
"message_key = None def get_message(self): \"\"\" Construct a message with the latest data,",
"Sub-classes that need to defer the saving of persistent data should override this",
"self._persist @property def monitor(self): \"\"\"An alias for the C{client} attribute.\"\"\" return self.client class",
"a message with the latest data, or None, if the data has not",
"_reset(self): if self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our L{Persist},",
"Landscape server which does not constantly change. New messages will only be sent",
"for plugins which send data to the Landscape server which does not constantly",
"which does not constantly change. New messages will only be sent when the",
"self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key: data} def",
"DataWatcher(MonitorPlugin): \"\"\" A utility for plugins which send data to the Landscape server",
"log_failure from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified as",
"def register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is not None: self._persist = self.monitor.persist.root_at(self.persist_name)",
"format_object(self)) result = self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return",
"saving of persistent data should override this method. \"\"\" pass def exchange(self, urgent=False):",
"urgent=False): \"\"\" Conditionally add a message to the message store if new data",
"def exchange(self, urgent=False): \"\"\" Conditionally add a message to the message store if",
"\"\"\" @cvar persist_name: If specified as a string, a C{_persist} attribute will be",
"method, and message_type, message_key, and persist_name class attributes. \"\"\" message_type = None message_key",
"\"\"\" persist_name = None scope = None def register(self, monitor): super(MonitorPlugin, self).register(monitor) if",
"import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified as a string, a",
"self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our L{Persist}, if any.\"\"\" return self._persist @property def",
"return self._persist @property def monitor(self): \"\"\"An alias for the C{client} attribute.\"\"\" return self.client",
"register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is not None: self._persist = self.monitor.persist.root_at(self.persist_name) else:",
"or None, if the data has not changed since the last call. \"\"\"",
"of get_data() has changed since the last time it was called. Subclasses should",
"not None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist = None def _reset(self): if self.persist_name",
"has changed since the last time it was called. Subclasses should provide a",
"data) return {\"type\": self.message_type, self.message_key: data} def send_message(self, urgent): message = self.get_message() if",
"that need to defer the saving of persistent data should override this method.",
"a C{_persist} attribute will be available after registration. \"\"\" persist_name = None scope",
"be sent when the result of get_data() has changed since the last time",
"attributes. \"\"\" message_type = None message_key = None def get_message(self): \"\"\" Construct a",
"pass def exchange(self, urgent=False): \"\"\" Conditionally add a message to the message store",
"any.\"\"\" return self._persist @property def monitor(self): \"\"\"An alias for the C{client} attribute.\"\"\" return",
"the C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\" A utility for plugins which",
"should provide a get_data method, and message_type, message_key, and persist_name class attributes. \"\"\"",
"else: self._persist = None def _reset(self): if self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property",
"does not constantly change. New messages will only be sent when the result",
"last call. \"\"\" data = self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return",
"called. Subclasses should provide a get_data method, and message_type, message_key, and persist_name class",
"not None: info(\"Queueing a message with updated data watcher info \" \"for %s.\",",
"def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None) def persist_data(self): \"\"\" Sub-classes",
"import info from twisted.internet.defer import succeed from landscape.log import format_object from landscape.lib.log import",
"class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified as a string, a C{_persist} attribute",
"get_data method, and message_type, message_key, and persist_name class attributes. \"\"\" message_type = None",
"need to defer the saving of persistent data should override this method. \"\"\"",
"when the result of get_data() has changed since the last time it was",
"data to the Landscape server which does not constantly change. New messages will",
"data} def send_message(self, urgent): message = self.get_message() if message is not None: info(\"Queueing",
"changed since the last call. \"\"\" data = self.get_data() if self._persist.get(\"data\") != data:",
"MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified as a string, a C{_persist} attribute will",
"def _reset(self): if self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our",
"Conditionally add a message to the message store if new data is available.",
"self.get_message() if message is not None: info(\"Queueing a message with updated data watcher",
"None scope = None def register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is not",
"C{_persist} attribute will be available after registration. \"\"\" persist_name = None scope =",
"= None message_key = None def get_message(self): \"\"\" Construct a message with the",
"result.addErrback(log_failure) return result return succeed(None) def persist_data(self): \"\"\" Sub-classes that need to defer",
"if message is not None: info(\"Queueing a message with updated data watcher info",
"persistent data should override this method. \"\"\" pass def exchange(self, urgent=False): \"\"\" Conditionally",
"\"\"\"Return our L{Persist}, if any.\"\"\" return self._persist @property def monitor(self): \"\"\"An alias for",
"persist_name: If specified as a string, a C{_persist} attribute will be available after",
"after registration. \"\"\" persist_name = None scope = None def register(self, monitor): super(MonitorPlugin,",
"@property def persist(self): \"\"\"Return our L{Persist}, if any.\"\"\" return self._persist @property def monitor(self):",
"L{Persist}, if any.\"\"\" return self._persist @property def monitor(self): \"\"\"An alias for the C{client}",
"data: self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key: data} def send_message(self, urgent): message =",
"None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our L{Persist}, if any.\"\"\" return self._persist @property",
"persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None) def persist_data(self): \"\"\" Sub-classes that",
"override this method. \"\"\" pass def exchange(self, urgent=False): \"\"\" Conditionally add a message",
"attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\" A utility for plugins which send data",
"super(MonitorPlugin, self).register(monitor) if self.persist_name is not None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist =",
"messages will only be sent when the result of get_data() has changed since",
"format_object from landscape.lib.log import log_failure from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar",
"result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None) def persist_data(self): \"\"\" Sub-classes that need to",
"it was called. Subclasses should provide a get_data method, and message_type, message_key, and",
"class DataWatcher(MonitorPlugin): \"\"\" A utility for plugins which send data to the Landscape",
"return succeed(None) def persist_data(self): \"\"\" Sub-classes that need to defer the saving of",
"succeed(None) def persist_data(self): \"\"\" Sub-classes that need to defer the saving of persistent",
"\"\"\" pass def exchange(self, urgent=False): \"\"\" Conditionally add a message to the message",
"a string, a C{_persist} attribute will be available after registration. \"\"\" persist_name =",
"change. New messages will only be sent when the result of get_data() has",
"= None def register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is not None: self._persist",
"None, if the data has not changed since the last call. \"\"\" data",
"the last call. \"\"\" data = self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\", data)",
"if the data has not changed since the last call. \"\"\" data =",
"as a string, a C{_persist} attribute will be available after registration. \"\"\" persist_name",
"is not None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist = None def _reset(self): if",
"def get_message(self): \"\"\" Construct a message with the latest data, or None, if",
"result return succeed(None) def persist_data(self): \"\"\" Sub-classes that need to defer the saving",
"if self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key: data} def send_message(self,",
"@cvar persist_name: If specified as a string, a C{_persist} attribute will be available",
"\"\"\" Sub-classes that need to defer the saving of persistent data should override",
"message_type, message_key, and persist_name class attributes. \"\"\" message_type = None message_key = None",
"= None def get_message(self): \"\"\" Construct a message with the latest data, or",
"the latest data, or None, if the data has not changed since the",
"defer the saving of persistent data should override this method. \"\"\" pass def",
"data has not changed since the last call. \"\"\" data = self.get_data() if",
"monitor(self): \"\"\"An alias for the C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\" A",
"from twisted.internet.defer import succeed from landscape.log import format_object from landscape.lib.log import log_failure from",
"updated data watcher info \" \"for %s.\", format_object(self)) result = self.registry.broker.send_message( message, self._session_id,",
"data watcher info \" \"for %s.\", format_object(self)) result = self.registry.broker.send_message( message, self._session_id, urgent=urgent)",
"of persistent data should override this method. \"\"\" pass def exchange(self, urgent=False): \"\"\"",
"if self.persist_name is not None: self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist = None def",
"New messages will only be sent when the result of get_data() has changed",
"provide a get_data method, and message_type, message_key, and persist_name class attributes. \"\"\" message_type",
"from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin): \"\"\" @cvar persist_name: If specified as a",
"return {\"type\": self.message_type, self.message_key: data} def send_message(self, urgent): message = self.get_message() if message",
"alias for the C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\" A utility for",
"persist_name class attributes. \"\"\" message_type = None message_key = None def get_message(self): \"\"\"",
"registration. \"\"\" persist_name = None scope = None def register(self, monitor): super(MonitorPlugin, self).register(monitor)",
"to defer the saving of persistent data should override this method. \"\"\" pass",
"a message with updated data watcher info \" \"for %s.\", format_object(self)) result =",
"call. \"\"\" data = self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return {\"type\":",
"is not None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our L{Persist}, if any.\"\"\" return",
"latest data, or None, if the data has not changed since the last",
"self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our L{Persist}, if any.\"\"\"",
"not None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our L{Persist}, if any.\"\"\" return self._persist",
"the last time it was called. Subclasses should provide a get_data method, and",
"= self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return",
"sent when the result of get_data() has changed since the last time it",
"get_data() has changed since the last time it was called. Subclasses should provide",
"info from twisted.internet.defer import succeed from landscape.log import format_object from landscape.lib.log import log_failure",
"= self.get_data() if self._persist.get(\"data\") != data: self._persist.set(\"data\", data) return {\"type\": self.message_type, self.message_key: data}",
"info(\"Queueing a message with updated data watcher info \" \"for %s.\", format_object(self)) result",
"available after registration. \"\"\" persist_name = None scope = None def register(self, monitor):",
"changed since the last time it was called. Subclasses should provide a get_data",
"message_key, and persist_name class attributes. \"\"\" message_type = None message_key = None def",
"time it was called. Subclasses should provide a get_data method, and message_type, message_key,",
"twisted.internet.defer import succeed from landscape.log import format_object from landscape.lib.log import log_failure from landscape.broker.client",
"persist_name = None scope = None def register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name",
"logging import info from twisted.internet.defer import succeed from landscape.log import format_object from landscape.lib.log",
"message with the latest data, or None, if the data has not changed",
"self.registry.broker.send_message( message, self._session_id, urgent=urgent) def persist_data(message_id): self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None)",
"return result return succeed(None) def persist_data(self): \"\"\" Sub-classes that need to defer the",
"None def register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is not None: self._persist =",
"= self.monitor.persist.root_at(self.persist_name) else: self._persist = None def _reset(self): if self.persist_name is not None:",
"@property def monitor(self): \"\"\"An alias for the C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin):",
"the Landscape server which does not constantly change. New messages will only be",
"attribute will be available after registration. \"\"\" persist_name = None scope = None",
"not changed since the last call. \"\"\" data = self.get_data() if self._persist.get(\"data\") !=",
"send data to the Landscape server which does not constantly change. New messages",
"should override this method. \"\"\" pass def exchange(self, urgent=False): \"\"\" Conditionally add a",
"self.persist_data() result.addCallback(persist_data) result.addErrback(log_failure) return result return succeed(None) def persist_data(self): \"\"\" Sub-classes that need",
"{\"type\": self.message_type, self.message_key: data} def send_message(self, urgent): message = self.get_message() if message is",
"self._persist = self.monitor.persist.root_at(self.persist_name) else: self._persist = None def _reset(self): if self.persist_name is not",
"import succeed from landscape.log import format_object from landscape.lib.log import log_failure from landscape.broker.client import",
"be available after registration. \"\"\" persist_name = None scope = None def register(self,",
"None def _reset(self): if self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return",
"if self.persist_name is not None: self.registry.persist.remove(self.persist_name) @property def persist(self): \"\"\"Return our L{Persist}, if",
"our L{Persist}, if any.\"\"\" return self._persist @property def monitor(self): \"\"\"An alias for the",
"C{client} attribute.\"\"\" return self.client class DataWatcher(MonitorPlugin): \"\"\" A utility for plugins which send",
"landscape.log import format_object from landscape.lib.log import log_failure from landscape.broker.client import BrokerClientPlugin class MonitorPlugin(BrokerClientPlugin):",
"\"\"\" A utility for plugins which send data to the Landscape server which",
"Construct a message with the latest data, or None, if the data has",
"scope = None def register(self, monitor): super(MonitorPlugin, self).register(monitor) if self.persist_name is not None:",
"server which does not constantly change. New messages will only be sent when"
] |
[
"df : pandas.DataFrame Source dataframe. col_name : str Name of the column to",
"2 print(f\"Graus de liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf)",
"n1 + n2 - 2 gl = len(usa) + len(can) - 2 print(f\"Graus",
"a dataframe. It drops any numpy.nan entries before sampling. The sampling is performed",
"can.isna().sum() # In[33]: def q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var = False,",
"# In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False,",
"significância de 5%__. # ## Questão 5 # # Obtenha todos atletas brasileiros,",
"Podemos afimar agora que as médias são estatisticamente iguais? Reponda com um boolean",
"p = sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p))",
"drops any numpy.nan entries before sampling. The sampling is performed without replacement. Example",
"Você consegue chegar a esse valor de p-valor a partir da variável de",
"e esporte praticado. Estaremos especialmente interessados nas variáveis numéricas altura (`height`) e peso",
"para comparação das médias das alturas (`height`) para amostras independentes e variâncias diferentes",
"- 2 gl = len(usa) + len(can) - 2 print(f\"Graus de liberdade: {gl}\")",
"Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das Olimpíadas de 2016 no Rio",
"sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute o",
"do teste são condizentes? Por que? # * Plote o qq-plot para essa",
"print('stat= {}, p={}'.format(stat,p)) if p > 0.05: print('Probably the same distribution') else: print('Probably",
"daqui # In[9]: # Sua análise começa aqui. # ## Questão 1 #",
"de uma Análise Exploratória de Dados (EDA). # # > Obs.: Por favor,",
"entre as alturas de `bra` e `can`. Podemos afimar agora que as médias",
"e canadenses em `DataFrame`s chamados `bra`, `usa` e `can`,respectivamente. Realize um teste de",
"sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]: athletes.head() #",
"com base nesse teste (ao nível de significância de 5%)? Responda com um",
"significância de 5%? Responda com um boolean (`True` ou `False`). # In[19]: def",
"# In[4]: athletes.info() # In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() #",
"questão 6, mas agora entre as alturas de `usa` e `can`. Qual o",
"começa aqui. # ## Questão 1 # # Considerando uma amostra de tamanho",
"não é legal). # In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1,",
"------- pandas.Series Sample of size n from dataframe's column. \"\"\" np.random.seed(seed) random_idx =",
"de hipóteses. Utilizaremos o _data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que",
"# coding: utf-8 # # Desafio 4 # # Neste desafio, vamos praticar",
"resultado faz sentido? # * Você consegue interpretar esse p-valor? # * Você",
"valor de p-valor a partir da variável de estatística? # In[72]: stat, p",
"# __Para refletir__: # # * Esse resultado faz sentido? # In[18]: amostra_q2",
"In[47]: can.isna().sum() # In[33]: def q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var =",
"de `usa` e `can`. Qual o valor do p-valor retornado? Responda como um",
"= np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array com index das colunas return df.loc[random_idx,",
"favor, não modifique o nome das funções de resposta. # ## _Setup_ geral",
"as np import scipy.stats as sct import seaborn as sns import statsmodels.api as",
"as sm # In[2]: #%matplotlib inline from IPython.core.pylabtools import figsize figsize(12, 8) sns.set()",
"In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show",
"liberdade para o teste t independente com variancias semelhantes: df = n1 +",
"sobre os atletas das Olimpíadas de 2016 no Rio de Janeiro. # #",
"## _Setup_ geral # In[1]: import pandas as pd import matplotlib.pyplot as plt",
"p={}'.format(stat,p)) return bool(p> 0.05) # In[17]: q2() # __Para refletir__: # # *",
"uma distribuição normal ao nível de significância de 5%? Responda com um boolean",
"those who haven't seen yet. Parameters ---------- df : pandas.DataFrame Source dataframe. col_name",
"as plt import numpy as np import scipy.stats as sct import seaborn as",
"`False`). # In[27]: athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality == 'USA')",
"afimar agora que as médias são estatisticamente iguais? Reponda com um boolean (`True`",
"esporte praticado. Estaremos especialmente interessados nas variáveis numéricas altura (`height`) e peso (`weight`).",
"entre `bra` e `usa`. Podemos afirmar que as médias são estatisticamente iguais? Responda",
"procedimento da questão 5, mas agora entre as alturas de `bra` e `can`.",
"The sampling is performed without replacement. Example of numpydoc for those who haven't",
"e `can`. Podemos afimar agora que as médias são estatisticamente iguais? Reponda com",
"athletes.info() # In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]: def",
"as alturas de `usa` e `can`. Qual o valor do p-valor retornado? Responda",
"são normalmente distribuídas com base nesse teste (ao nível de significância de 5%)?",
"* Plote o qq-plot para essa variável e a analise. # * Existe",
"column of a dataframe. It drops any numpy.nan entries before sampling. The sampling",
"dataframe. col_name : str Name of the column to be sampled. n :",
"to be sampled. n : int Sample size. Default is 100. seed :",
"o histograma dessa variável (com, por exemplo, `bins=25`). A forma do gráfico e",
"n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return",
"legal). # In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\":",
"e 7 a seguir considere todos testes efetuados ao nível de significância de",
"bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') # ## Questão 6",
"as médias são estatisticamente iguais? Reponda com um boolean (`True` ou `False`). #",
"um pouco sobre testes de hipóteses. Utilizaremos o _data set_ [2016 Olympics in",
"esse valor de p-valor a partir da variável de estatística? # In[72]: stat,",
"of a dataframe. It drops any numpy.nan entries before sampling. The sampling is",
"análise a partir daqui # In[9]: # Sua análise começa aqui. # ##",
"= sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[24]: q4() # __Para",
"variáveis numéricas altura (`height`) e peso (`weight`). As análises feitas aqui são parte",
"com a função `get_sample()`. Faça o teste de normalidade de D'Agostino-Pearson utilizando a",
"das médias das alturas (`height`) para amostras independentes e variâncias diferentes com a",
"e variâncias diferentes com a função `scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos afirmar",
"a partir daqui # In[9]: # Sua análise começa aqui. # ## Questão",
"nome, nacionalidade, altura, peso e esporte praticado. Estaremos especialmente interessados nas variáveis numéricas",
"of numpydoc for those who haven't seen yet. Parameters ---------- df : pandas.DataFrame",
"análise começa aqui. # ## Questão 1 # # Considerando uma amostra de",
"boolean (`True` ou `False`). # In[10]: def q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42)",
"de significância de 5%)? Responda com um boolean (`True` ou `False`). # In[16]:",
"bins=25, hist_kws={\"density\": True}) plt.show () # In[22]: sns.boxplot(data = amostra_q3) # ## Questão",
"sobre testes de hipóteses. Utilizaremos o _data set_ [2016 Olympics in Rio de",
"athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name, n=100,",
"com um boolean (`True` ou `False`). # In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight',",
"(`True` ou `False`). # In[16]: def q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat,",
"p={}'.format(stat,p)) return bool(p> 0.05) # In[20]: q3() # __Para refletir__: # # *",
"# In[20]: q3() # __Para refletir__: # # * Plote o histograma dessa",
"Questão 4 # # Realize uma transformação logarítmica em na amostra de `weight`",
"bra['height'].describe() # In[30]: bra.isna().sum() # In[31]: usa['height'].describe() # In[32]: usa.isna().sum() # In[46]: can['height'].describe()",
"`False`). # In[48]: def q6(): stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var = False,",
"# ## _Setup_ geral # In[1]: import pandas as pd import matplotlib.pyplot as",
"performed without replacement. Example of numpydoc for those who haven't seen yet. Parameters",
"sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute o",
"resposta. # ## _Setup_ geral # In[1]: import pandas as pd import matplotlib.pyplot",
"_data set_ conta com informações gerais sobre 11538 atletas como nome, nacionalidade, altura,",
"In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name,",
"return df.loc[random_idx, col_name] #retorna uma series com index e valor da coluna #",
"= sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[20]: q3() # __Para",
"In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy = 'omit') print('stat=",
"do p-valor retornado? Responda como um único escalar arredondado para oito casas decimais.",
"`DataFrame`s chamados `bra`, `usa` e `can`,respectivamente. Realize um teste de hipóteses para comparação",
"de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das Olimpíadas de 2016 no",
"com um boolean (`True` ou `False`). # In[10]: def q1(): amostra_q1 = get_sample(athletes,'height',",
"a função `scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos afirmar que as médias são",
"q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN')",
"Considerando agora uma amostra de tamanho 3000 da coluna `weight` obtida com a",
"stat, p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[11]: q1()",
"# # Obtenha todos atletas brasileiros, norte-americanos e canadenses em `DataFrame`s chamados `bra`,",
"== 'CAN')] # In[28]: bra = athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality ==",
"5 6 e 7 a seguir considere todos testes efetuados ao nível de",
"agora utilizando o teste de normalidade de Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora",
"função `scipy.stats.shapiro()`. Podemos afirmar que as alturas são normalmente distribuídas com base nesse",
"Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das Olimpíadas de 2016",
"de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos afirmar que os pesos vêm de",
"a sample from a column of a dataframe. It drops any numpy.nan entries",
"teste t de Welch, que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p))",
"5%? Responda com um boolean (`True` ou `False`). # In[19]: def q3(): amostra_q3",
"numpydoc for those who haven't seen yet. Parameters ---------- df : pandas.DataFrame Source",
"* O resultado faz sentido? # * Você consegue interpretar esse p-valor? #",
"esse p-valor? # * Você consegue chegar a esse valor de p-valor a",
"import scipy.stats as sct import seaborn as sns import statsmodels.api as sm #",
"\"\"\"Get a sample from a column of a dataframe. It drops any numpy.nan",
"sample from a column of a dataframe. It drops any numpy.nan entries before",
"afirmar que as alturas são normalmente distribuídas com base nesse teste (ao nível",
"return bool(p> 0.05) # In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA')",
"= sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute",
"de p-valor a partir da variável de estatística? # In[72]: stat, p =",
"hist_kws={\"density\": True}) plt.show () # In[26]: sns.boxplot(data = amostra_q4_transformada) # > __Para as",
"# In[11]: q1() # __Para refletir__: # # * Plote o histograma dessa",
"sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') # ## Questão 7 # # Repita o",
"Responda como um único escalar arredondado para oito casas decimais. # In[87]: def",
"numpy as np import scipy.stats as sct import seaborn as sns import statsmodels.api",
"# Repita o mesmo procedimento acima, mas agora utilizando o teste de normalidade",
"através da função `scipy.stats.jarque_bera()`. Agora podemos afirmar que as alturas são normalmente distribuídas",
"normalidade da variável transformada ao nível de significância de 5%? Responda com um",
"# In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False,",
"como um único escalar arredondado para oito casas decimais. # In[87]: def q7():",
"set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas",
"size n from dataframe's column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna",
"da coluna # ## Inicia sua análise a partir daqui # In[9]: #",
"IPython.core.pylabtools import figsize figsize(12, 8) sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]:",
"# Obtenha todos atletas brasileiros, norte-americanos e canadenses em `DataFrame`s chamados `bra`, `usa`",
"seed : int Random seed. Default is 42. Returns ------- pandas.Series Sample of",
"boolean (`True` ou `False`). # In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42)",
"para o teste t independente com variancias semelhantes: df = n1 + n2",
"q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p))",
"'USA'] can = athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe() # In[30]: bra.isna().sum() #",
"# In[9]: # Sua análise começa aqui. # ## Questão 1 # #",
"get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show () # In[22]: sns.boxplot(data =",
"de 5%)? Responda com um boolean (`True` ou `False`). # In[10]: def q1():",
"p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[11]: q1() #",
"Você esperava um resultado diferente agora? # In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42)",
"de Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora podemos afirmar que as alturas são",
"q7() # __Para refletir__: # # * O resultado faz sentido? # *",
"the same distribution') else: print('Probably different distributions') return float(np.round(p, 8)) # In[88]: q7()",
"t independente com variancias semelhantes: df = n1 + n2 - 2 gl",
"a esse valor de p-valor a partir da variável de estatística? # In[72]:",
"import numpy as np import scipy.stats as sct import seaborn as sns import",
"ou `False`). # In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada =",
"In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat, p = sct.normaltest(amostra_q3) print('stat=",
"Esse _data set_ conta com informações gerais sobre 11538 atletas como nome, nacionalidade,",
"In[10]: def q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) print('stat=",
"de `bra` e `can`. Podemos afimar agora que as médias são estatisticamente iguais?",
"# In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]: athletes.head() # In[6]:",
"+ n2 - 2 gl = len(usa) + len(can) - 2 print(f\"Graus de",
"different distributions') return float(np.round(p, 8)) # In[88]: q7() # __Para refletir__: # #",
"as alturas são normalmente distribuídas (ao nível de significância de 5%)? Responda com",
"resultado do teste são condizentes? Por que? # * Você esperava um resultado",
"`can`. Podemos afimar agora que as médias são estatisticamente iguais? Reponda com um",
"o resultado do teste são condizentes? Por que? # * Plote o qq-plot",
"resultado diferente agora? # In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4)",
"(athletes.nationality == 'USA') | (athletes.nationality == 'CAN')] # In[28]: bra = athletes[athletes.nationality ==",
"amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return",
"`usa`. Podemos afirmar que as médias são estatisticamente iguais? Responda com um boolean",
"usa.isna().sum() # In[46]: can['height'].describe() # In[47]: can.isna().sum() # In[33]: def q5(): stat, p",
"In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True})",
"significância de 5%? Responda com um boolean (`True` ou `False`). # In[23]: def",
"função `get_sample()`. Faça o teste de normalidade de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`.",
"variancias semelhantes: df = n1 + n2 - 2 gl = len(usa) +",
"Returns ------- pandas.Series Sample of size n from dataframe's column. \"\"\" np.random.seed(seed) random_idx",
"execute o teste de normalidade de Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos afirmar",
"normalidade de Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos afirmar que as alturas são",
"p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[24]: q4() #",
"0.05) # In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25,",
"diferentes com a função `scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos afirmar que as",
"boolean (`True` ou `False`). # In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42)",
"# * Plote o histograma dessa variável (com, por exemplo, `bins=25`). A forma",
"return bool(p> 0.05) # In[20]: q3() # __Para refletir__: # # * Plote",
"def q7(): stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy = 'omit')",
"float(np.round(p, 8)) # In[88]: q7() # __Para refletir__: # # * O resultado",
"_p-value hacking_, e não é legal). # In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42)",
"statsmodels.api as sm # In[2]: #%matplotlib inline from IPython.core.pylabtools import figsize figsize(12, 8)",
"col_name] #retorna uma series com index e valor da coluna # ## Inicia",
"agora que as médias são estatisticamente iguais? Reponda com um boolean (`True` ou",
"seed=42): \"\"\"Get a sample from a column of a dataframe. It drops any",
"# Realize uma transformação logarítmica em na amostra de `weight` da questão 3",
"isso na prática. Isso é chamado _p-value hacking_, e não é legal). #",
"numpy.nan entries before sampling. The sampling is performed without replacement. Example of numpydoc",
"stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy = 'omit') #False: se",
"distribution') else: print('Probably different distributions') return float(np.round(p, 8)) # In[88]: q7() # __Para",
"# Repita o procedimento da questão 6, mas agora entre as alturas de",
"tamanho 3000 da coluna `height` obtida com a função `get_sample()`, execute o teste",
"norte-americanos e canadenses em `DataFrame`s chamados `bra`, `usa` e `can`,respectivamente. Realize um teste",
"iguais? Reponda com um boolean (`True` ou `False`). # In[48]: def q6(): stat,",
"mas agora utilizando o teste de normalidade de Jarque-Bera através da função `scipy.stats.jarque_bera()`.",
"e repita o mesmo procedimento. Podemos afirmar a normalidade da variável transformada ao",
"com index das colunas return df.loc[random_idx, col_name] #retorna uma series com index e",
"Estaremos especialmente interessados nas variáveis numéricas altura (`height`) e peso (`weight`). As análises",
"obtida com a função `get_sample()`, execute o teste de normalidade de Shapiro-Wilk com",
"In[88]: q7() # __Para refletir__: # # * O resultado faz sentido? #",
"# In[28]: bra = athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality == 'USA'] can",
"df.loc[random_idx, col_name] #retorna uma series com index e valor da coluna # ##",
"vêm de uma distribuição normal ao nível de significância de 5%? Responda com",
"alturas (`height`) para amostras independentes e variâncias diferentes com a função `scipy.stats.ttest_ind()` entre",
"que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) if p > 0.05:",
"variâncias diferentes com a função `scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos afirmar que",
"do gráfico e o resultado do teste são condizentes? Por que? # *",
"função `scipy.stats.jarque_bera()`. Agora podemos afirmar que as alturas são normalmente distribuídas (ao nível",
"Responda com um boolean (`True` ou `False`). # In[23]: def q4(): amostra_q4 =",
"q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada)",
"q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat, p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p))",
"comparação das médias das alturas (`height`) para amostras independentes e variâncias diferentes com",
"# ## Questão 7 # # Repita o procedimento da questão 6, mas",
"os atletas das Olimpíadas de 2016 no Rio de Janeiro. # # Esse",
"são condizentes? Por que? # * Você esperava um resultado diferente agora? #",
"atletas das Olimpíadas de 2016 no Rio de Janeiro. # # Esse _data",
"bins=25, hist_kws={\"density\": True}) plt.show () # In[26]: sns.boxplot(data = amostra_q4_transformada) # > __Para",
"nas variáveis numéricas altura (`height`) e peso (`weight`). As análises feitas aqui são",
"coluna `height` obtida com a função `get_sample()`, execute o teste de normalidade de",
"qq-plot para essa variável e a analise. # * Existe algum nível de",
"Podemos afirmar que as médias são estatisticamente iguais? Responda com um boolean (`True`",
"label='USA') # ## Questão 6 # # Repita o procedimento da questão 5,",
"= len(usa) + len(can) - 2 print(f\"Graus de liberdade: {gl}\") q7_sf = sct.t.sf(stat,",
"python # coding: utf-8 # # Desafio 4 # # Neste desafio, vamos",
"função `get_sample()`, execute o teste de normalidade de Shapiro-Wilk com a função `scipy.stats.shapiro()`.",
"`bra`, `usa` e `can`,respectivamente. Realize um teste de hipóteses para comparação das médias",
"de 2016 no Rio de Janeiro. # # Esse _data set_ conta com",
"print('Probably the same distribution') else: print('Probably different distributions') return float(np.round(p, 8)) # In[88]:",
"também poderia ajudar a entender a resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000,",
"In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe()",
"feitas aqui são parte de uma Análise Exploratória de Dados (EDA). # #",
"que os pesos vêm de uma distribuição normal ao nível de significância de",
"decimais. # In[87]: def q7(): stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = False,",
"bra.isna().sum() # In[31]: usa['height'].describe() # In[32]: usa.isna().sum() # In[46]: can['height'].describe() # In[47]: can.isna().sum()",
"print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25,",
"Considerando uma amostra de tamanho 3000 da coluna `height` obtida com a função",
"execute o teste t de Welch, que não assume igual variação populaciona print('stat=",
"oito casas decimais. # In[87]: def q7(): stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var",
"# In[22]: sns.boxplot(data = amostra_q3) # ## Questão 4 # # Realize uma",
"plot_ também poderia ajudar a entender a resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight',",
"a normalidade da variável transformada ao nível de significância de 5%? Responda com",
"agora? # In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25,",
"6 e 7 a seguir considere todos testes efetuados ao nível de significância",
"'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau de liberdade para o teste t",
"independente com variancias semelhantes: df = n1 + n2 - 2 gl =",
"q3() # __Para refletir__: # # * Plote o histograma dessa variável (com,",
"(`True` ou `False`). # In[27]: athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality",
"base nesse teste (ao nível de significância de 5%)? Responda com um boolean",
"seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show () # In[22]: sns.boxplot(data = amostra_q3) #",
"sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[20]: q3() # __Para refletir__:",
"7 # # Repita o procedimento da questão 6, mas agora entre as",
"Responda com um boolean (`True` ou `False`). # In[27]: athletes.columns # In[45]: athletes[(athletes.nationality",
"o teste de normalidade de Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora podemos afirmar",
"stat, p = sct.shapiro(amostra_q1) p > 0.0000001 # ## Questão 2 # #",
"Reponda com um boolean (`True` ou `False`). # In[48]: def q6(): stat, p",
"distribuídas com base nesse teste (ao nível de significância de 5%)? Responda com",
"In[9]: # Sua análise começa aqui. # ## Questão 1 # # Considerando",
"amostra_q4_transformada = np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05)",
"Sua análise começa aqui. # ## Questão 1 # # Considerando uma amostra",
"altura (`height`) e peso (`weight`). As análises feitas aqui são parte de uma",
"# * Você consegue interpretar esse p-valor? # * Você consegue chegar a",
"label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') # ## Questão 6 # # Repita",
"atletas brasileiros, norte-americanos e canadenses em `DataFrame`s chamados `bra`, `usa` e `can`,respectivamente. Realize",
"In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () # ##",
"= athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe() # In[30]: bra.isna().sum() # In[31]: usa['height'].describe()",
"o qq-plot para essa variável e a analise. # * Existe algum nível",
"# In[10]: def q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1)",
"sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]:",
"6 # # Repita o procedimento da questão 5, mas agora entre as",
"as alturas são normalmente distribuídas com base nesse teste (ao nível de significância",
"questão 3 e repita o mesmo procedimento. Podemos afirmar a normalidade da variável",
"variação populaciona print('stat= {}, p={}'.format(stat,p)) if p > 0.05: print('Probably the same distribution')",
"boolean (`True` ou `False`). # In[16]: def q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42)",
"# # Desafio 4 # # Neste desafio, vamos praticar um pouco sobre",
"n=100, seed=42): \"\"\"Get a sample from a column of a dataframe. It drops",
"Plote o qq-plot para essa variável e a analise. # * Existe algum",
"de normalidade de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos afirmar que os pesos",
"a seguir considere todos testes efetuados ao nível de significância de 5%__. #",
"teste t independente com variancias semelhantes: df = n1 + n2 - 2",
"def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat, p = sct.normaltest(amostra_q3) print('stat= {},",
"# In[26]: sns.boxplot(data = amostra_q4_transformada) # > __Para as questão 5 6 e",
"import statsmodels.api as sm # In[2]: #%matplotlib inline from IPython.core.pylabtools import figsize figsize(12,",
"get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show () # In[14]:",
"alturas são normalmente distribuídas (ao nível de significância de 5%)? Responda com um",
"histograma dessa variável (com, por exemplo, `bins=25`). A forma do gráfico e o",
"n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) #",
"# In[47]: can.isna().sum() # In[33]: def q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var",
"sns import statsmodels.api as sm # In[2]: #%matplotlib inline from IPython.core.pylabtools import figsize",
"é legal). # In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25,",
"# * Você esperava um resultado diferente agora? # In[25]: amostra_q4 = get_sample(athletes,'weight',",
"= 'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau de liberdade para o teste",
"3 # # Considerando agora uma amostra de tamanho 3000 da coluna `weight`",
"variável e a analise. # * Existe algum nível de significância razoável que",
"(`True` ou `False`). # In[48]: def q6(): stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var",
"Questão 7 # # Repita o procedimento da questão 6, mas agora entre",
"para amostras independentes e variâncias diferentes com a função `scipy.stats.ttest_ind()` entre `bra` e",
"afirmar a normalidade da variável transformada ao nível de significância de 5%? Responda",
"plt import numpy as np import scipy.stats as sct import seaborn as sns",
"consegue interpretar esse p-valor? # * Você consegue chegar a esse valor de",
"de hipóteses para comparação das médias das alturas (`height`) para amostras independentes e",
"print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[24]: q4() # __Para refletir__: #",
"# Considerando uma amostra de tamanho 3000 da coluna `height` obtida com a",
"de liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf) # In[77]:",
"(EDA). # # > Obs.: Por favor, não modifique o nome das funções",
"um boolean (`True` ou `False`). # In[10]: def q1(): amostra_q1 = get_sample(athletes,'height', n=3000,",
"um teste de hipóteses para comparação das médias das alturas (`height`) para amostras",
"Questão 2 # # Repita o mesmo procedimento acima, mas agora utilizando o",
"return bool(p> 0.05) # In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA')",
"4 # # Neste desafio, vamos praticar um pouco sobre testes de hipóteses.",
"q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False,",
"q7(): stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy = 'omit') #False:",
"geral # In[1]: import pandas as pd import matplotlib.pyplot as plt import numpy",
"(`True` ou `False`). # In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat,",
"hist_kws={\"density\": True}) plt.show () # In[22]: sns.boxplot(data = amostra_q3) # ## Questão 4",
"for those who haven't seen yet. Parameters ---------- df : pandas.DataFrame Source dataframe.",
"amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat, p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return",
"um boolean (`True` ou `False`). # In[48]: def q6(): stat, p = sct.ttest_ind(bra['height'],",
"get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show () #",
"pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats",
"stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se",
"= get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p>",
"# * O resultado faz sentido? # * Você consegue interpretar esse p-valor?",
"get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) p > 0.0000001 # ## Questão",
"line=\"45\") plt.show () # ## Questão 3 # # Considerando agora uma amostra",
"__Para refletir__: # # * Plote o histograma dessa variável (com, por exemplo,",
"# In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat,",
"import figsize figsize(12, 8) sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info()",
"is 42. Returns ------- pandas.Series Sample of size n from dataframe's column. \"\"\"",
"especialmente interessados nas variáveis numéricas altura (`height`) e peso (`weight`). As análises feitas",
"> 0.0000001 # ## Questão 2 # # Repita o mesmo procedimento acima,",
"{}, p={}'.format(stat,p)) if p > 0.05: print('Probably the same distribution') else: print('Probably different",
"size. Default is 100. seed : int Random seed. Default is 42. Returns",
"def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p =",
"parte de uma Análise Exploratória de Dados (EDA). # # > Obs.: Por",
"() # ## Questão 3 # # Considerando agora uma amostra de tamanho",
"# ## Questão 6 # # Repita o procedimento da questão 5, mas",
"aqui. # ## Questão 1 # # Considerando uma amostra de tamanho 3000",
"prática. Isso é chamado _p-value hacking_, e não é legal). # In[12]: amostra_q1",
"0.05) # In[17]: q2() # __Para refletir__: # # * Esse resultado faz",
"p={}'.format(stat,p)) return bool(p> 0.05) # In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True,",
"peso (`weight`). As análises feitas aqui são parte de uma Análise Exploratória de",
"Análise Exploratória de Dados (EDA). # # > Obs.: Por favor, não modifique",
"com a função `get_sample()`, execute o teste de normalidade de Shapiro-Wilk com a",
"plt.show () # In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1)",
"mas agora entre as alturas de `bra` e `can`. Podemos afimar agora que",
"de uma distribuição normal ao nível de significância de 5%? Responda com um",
"faz sentido? # In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show",
"o teste de normalidade de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos afirmar que",
"arredondado para oito casas decimais. # In[87]: def q7(): stat, p = sct.ttest_ind(usa['height'],",
"# In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () # In[15]: amostra_q1 = get_sample(athletes,'height', n=3000,",
"função `scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos afirmar que as médias são estatisticamente",
"amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return",
"das alturas (`height`) para amostras independentes e variâncias diferentes com a função `scipy.stats.ttest_ind()`",
"In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') # ##",
"# # Realize uma transformação logarítmica em na amostra de `weight` da questão",
"p={}'.format(stat,p)) return bool(p> 0.05) # In[24]: q4() # __Para refletir__: # # *",
"In[20]: q3() # __Para refletir__: # # * Plote o histograma dessa variável",
"um boolean (`True` ou `False`). # In[16]: def q2(): amostra_q2 = get_sample(athletes,'height', n=3000,",
"column to be sampled. n : int Sample size. Default is 100. seed",
"## Questão 1 # # Considerando uma amostra de tamanho 3000 da coluna",
"_box plot_ também poderia ajudar a entender a resposta. # In[21]: amostra_q3 =",
"6, mas agora entre as alturas de `usa` e `can`. Qual o valor",
"Realize uma transformação logarítmica em na amostra de `weight` da questão 3 e",
"fit=True, line=\"45\") plt.show () # In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p",
"populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[49]: q6() # In[50]: sns.distplot(bra['height'],",
"# In[17]: q2() # __Para refletir__: # # * Esse resultado faz sentido?",
"entries before sampling. The sampling is performed without replacement. Example of numpydoc for",
"seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True,",
"#grau de liberdade para o teste t independente com variancias semelhantes: df =",
"n2 - 2 gl = len(usa) + len(can) - 2 print(f\"Graus de liberdade:",
"sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute o",
"de significância de 5%)? Responda com um boolean (`True` ou `False`). # In[10]:",
"que as alturas são normalmente distribuídas (ao nível de significância de 5%)? Responda",
"nome das funções de resposta. # ## _Setup_ geral # In[1]: import pandas",
"ajudar a entender a resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3,",
"# ## Questão 4 # # Realize uma transformação logarítmica em na amostra",
"Welch, que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05)",
"escalar arredondado para oito casas decimais. # In[87]: def q7(): stat, p =",
"procedimento acima, mas agora utilizando o teste de normalidade de Jarque-Bera através da",
"# In[16]: def q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2)",
"sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[11]: q1() # __Para refletir__:",
"consegue chegar a esse valor de p-valor a partir da variável de estatística?",
"com um boolean (`True` ou `False`). # In[27]: athletes.columns # In[45]: athletes[(athletes.nationality ==",
"seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p>",
"athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality == 'USA') | (athletes.nationality ==",
"liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'],",
"de `weight` da questão 3 e repita o mesmo procedimento. Podemos afirmar a",
"In[46]: can['height'].describe() # In[47]: can.isna().sum() # In[33]: def q5(): stat, p = sct.ttest_ind(bra['height'],",
"falso, execute o teste t de Welch, que não assume igual variação populaciona",
"poderia ajudar a entender a resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42)",
"#False: se falso, execute o teste t de Welch, que não assume igual",
"Dados (EDA). # # > Obs.: Por favor, não modifique o nome das",
"# * Plote o qq-plot para essa variável e a analise. # *",
"dataframe's column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array com",
"um boolean (`True` ou `False`). # In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000,",
"= get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {},",
"return bool(p> 0.05) # In[17]: q2() # __Para refletir__: # # * Esse",
"significância de 5%)? Responda com um boolean (`True` ou `False`). # In[10]: def",
"Parameters ---------- df : pandas.DataFrame Source dataframe. col_name : str Name of the",
"Inicia sua análise a partir daqui # In[9]: # Sua análise começa aqui.",
"Rio de Janeiro. # # Esse _data set_ conta com informações gerais sobre",
"() # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () # In[15]: amostra_q1 = get_sample(athletes,'height',",
"# Sua análise começa aqui. # ## Questão 1 # # Considerando uma",
"amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () # ## Questão",
"from a column of a dataframe. It drops any numpy.nan entries before sampling.",
"nesse teste (ao nível de significância de 5%)? Responda com um boolean (`True`",
"np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array com index das colunas return df.loc[random_idx, col_name]",
"= get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) p > 0.0000001 # ##",
"scipy.stats as sct import seaborn as sns import statsmodels.api as sm # In[2]:",
"figsize(12, 8) sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]:",
"`scipy.stats.jarque_bera()`. Agora podemos afirmar que as alturas são normalmente distribuídas (ao nível de",
"ao nível de significância de 5%? Responda com um boolean (`True` ou `False`).",
"be sampled. n : int Sample size. Default is 100. seed : int",
"o valor do p-valor retornado? Responda como um único escalar arredondado para oito",
"() # In[26]: sns.boxplot(data = amostra_q4_transformada) # > __Para as questão 5 6",
"# In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') #",
"sct import seaborn as sns import statsmodels.api as sm # In[2]: #%matplotlib inline",
"resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show",
"False, nan_policy = 'omit') #False: se falso, execute o teste t de Welch,",
"para oito casas decimais. # In[87]: def q7(): stat, p = sct.ttest_ind(usa['height'], can['height'],",
"da função `scipy.stats.jarque_bera()`. Agora podemos afirmar que as alturas são normalmente distribuídas (ao",
"Source dataframe. col_name : str Name of the column to be sampled. n",
"de 5%? Responda com um boolean (`True` ou `False`). # In[19]: def q3():",
"distribuídas (ao nível de significância de 5%)? Responda com um boolean (`True` ou",
"0.05) # In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25,",
"athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() #",
"colunas return df.loc[random_idx, col_name] #retorna uma series com index e valor da coluna",
"altura, peso e esporte praticado. Estaremos especialmente interessados nas variáveis numéricas altura (`height`)",
"hist=False, rug=True, label='USA') # ## Questão 6 # # Repita o procedimento da",
"no teste? (Não faça isso na prática. Isso é chamado _p-value hacking_, e",
"ou `False`). # In[27]: athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality ==",
"Qual o valor do p-valor retornado? Responda como um único escalar arredondado para",
"print(f\"Graus de liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf) #",
"teste de normalidade de Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora podemos afirmar que",
"médias são estatisticamente iguais? Reponda com um boolean (`True` ou `False`). # In[48]:",
"# # > Obs.: Por favor, não modifique o nome das funções de",
"Plote o histograma dessa variável (com, por exemplo, `bins=25`). A forma do gráfico",
"print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25,",
"# __Para refletir__: # # * O resultado faz sentido? # * Você",
"e `can`,respectivamente. Realize um teste de hipóteses para comparação das médias das alturas",
"index e valor da coluna # ## Inicia sua análise a partir daqui",
"p = sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy = 'omit') #False: se falso,",
"In[17]: q2() # __Para refletir__: # # * Esse resultado faz sentido? #",
"peso e esporte praticado. Estaremos especialmente interessados nas variáveis numéricas altura (`height`) e",
"3000 da coluna `weight` obtida com a função `get_sample()`. Faça o teste de",
"entender a resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\":",
"In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True,",
"seed. Default is 42. Returns ------- pandas.Series Sample of size n from dataframe's",
"seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show () # In[26]: sns.boxplot(data",
"independentes e variâncias diferentes com a função `scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos",
"# # Considerando agora uma amostra de tamanho 3000 da coluna `weight` obtida",
"# In[27]: athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality == 'USA') |",
"'CAN'] # In[29]: bra['height'].describe() # In[30]: bra.isna().sum() # In[31]: usa['height'].describe() # In[32]: usa.isna().sum()",
"p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[20]: q3() #",
"amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show",
"In[29]: bra['height'].describe() # In[30]: bra.isna().sum() # In[31]: usa['height'].describe() # In[32]: usa.isna().sum() # In[46]:",
"único escalar arredondado para oito casas decimais. # In[87]: def q7(): stat, p",
"utf-8 # # Desafio 4 # # Neste desafio, vamos praticar um pouco",
"teste de hipóteses para comparação das médias das alturas (`height`) para amostras independentes",
"são estatisticamente iguais? Reponda com um boolean (`True` ou `False`). # In[48]: def",
"p > 0.05: print('Probably the same distribution') else: print('Probably different distributions') return float(np.round(p,",
"razoável que nos dê outro resultado no teste? (Não faça isso na prática.",
"str Name of the column to be sampled. n : int Sample size.",
"`scipy.stats.normaltest()`. Podemos afirmar que os pesos vêm de uma distribuição normal ao nível",
"def get_sample(df, col_name, n=100, seed=42): \"\"\"Get a sample from a column of a",
"yet. Parameters ---------- df : pandas.DataFrame Source dataframe. col_name : str Name of",
"rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') # ## Questão 7 # #",
"col_name, n=100, seed=42): \"\"\"Get a sample from a column of a dataframe. It",
"o teste t de Welch, que não assume igual variação populaciona print('stat= {},",
"t de Welch, que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) if",
"In[26]: sns.boxplot(data = amostra_q4_transformada) # > __Para as questão 5 6 e 7",
"In[11]: q1() # __Para refletir__: # # * Plote o histograma dessa variável",
"semelhantes: df = n1 + n2 - 2 gl = len(usa) + len(can)",
"teste de normalidade de Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos afirmar que as",
"dados sobre os atletas das Olimpíadas de 2016 no Rio de Janeiro. #",
"5%__. # ## Questão 5 # # Obtenha todos atletas brasileiros, norte-americanos e",
"pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist()",
"de Welch, que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p>",
"== 'BRA'] usa = athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality == 'CAN'] #",
"Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora podemos afirmar que as alturas são normalmente",
"5%)? Responda com um boolean (`True` ou `False`). # In[16]: def q2(): amostra_q2",
"# In[88]: q7() # __Para refletir__: # # * O resultado faz sentido?",
"gráfico e o resultado do teste são condizentes? Por que? # * Plote",
"bool(p> 0.05) # In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'],",
"igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[49]: q6() #",
"as sct import seaborn as sns import statsmodels.api as sm # In[2]: #%matplotlib",
"sampled. n : int Sample size. Default is 100. seed : int Random",
"`height` obtida com a função `get_sample()`, execute o teste de normalidade de Shapiro-Wilk",
"{}, p={}'.format(stat,p)) return bool(p> 0.05) # In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False,",
"partir da variável de estatística? # In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var",
"3000 da coluna `height` obtida com a função `get_sample()`, execute o teste de",
"por exemplo, `bins=25`). A forma do gráfico e o resultado do teste são",
"# * Esse resultado faz sentido? # In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42)",
"uma series com index e valor da coluna # ## Inicia sua análise",
"= get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show ()",
"As análises feitas aqui são parte de uma Análise Exploratória de Dados (EDA).",
"normal ao nível de significância de 5%? Responda com um boolean (`True` ou",
"sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () # ## Questão 3 # # Considerando agora",
"mesmo procedimento. Podemos afirmar a normalidade da variável transformada ao nível de significância",
"de liberdade para o teste t independente com variancias semelhantes: df = n1",
"athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality == 'CAN']",
"bool(p> 0.05) # In[11]: q1() # __Para refletir__: # # * Plote o",
"# In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name, n=100, seed=42): \"\"\"Get a sample",
"Podemos afirmar que as alturas são normalmente distribuídas com base nesse teste (ao",
"# * Existe algum nível de significância razoável que nos dê outro resultado",
"() # In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) p",
"= sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[17]: q2() # __Para",
"desafio, vamos praticar um pouco sobre testes de hipóteses. Utilizaremos o _data set_",
"da coluna `height` obtida com a função `get_sample()`, execute o teste de normalidade",
"que as alturas são normalmente distribuídas com base nesse teste (ao nível de",
"normalidade de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos afirmar que os pesos vêm",
"um boolean (`True` ou `False`). # In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000,",
"In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name, n=100, seed=42): \"\"\"Get",
"bool(p> 0.05) # In[24]: q4() # __Para refletir__: # # * Plote o",
"amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show () # In[26]: sns.boxplot(data =",
"amostras independentes e variâncias diferentes com a função `scipy.stats.ttest_ind()` entre `bra` e `usa`.",
"== 'BRA') | (athletes.nationality == 'USA') | (athletes.nationality == 'CAN')] # In[28]: bra",
"== 'USA'] can = athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe() # In[30]: bra.isna().sum()",
"rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') # ## Questão 6 # #",
"int Random seed. Default is 42. Returns ------- pandas.Series Sample of size n",
"from dataframe's column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array",
"teste de normalidade de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos afirmar que os",
"Questão 6 # # Repita o procedimento da questão 5, mas agora entre",
"significância razoável que nos dê outro resultado no teste? (Não faça isso na",
"o procedimento da questão 5, mas agora entre as alturas de `bra` e",
"q1() # __Para refletir__: # # * Plote o histograma dessa variável (com,",
"todos atletas brasileiros, norte-americanos e canadenses em `DataFrame`s chamados `bra`, `usa` e `can`,respectivamente.",
"p-valor retornado? Responda como um único escalar arredondado para oito casas decimais. #",
"pesos vêm de uma distribuição normal ao nível de significância de 5%? Responda",
"nan_policy = 'omit') #False: se falso, execute o teste t de Welch, que",
"a função `get_sample()`. Faça o teste de normalidade de D'Agostino-Pearson utilizando a função",
"{}, p={}'.format(stat,p)) return bool(p> 0.05) # In[11]: q1() # __Para refletir__: # #",
"com um boolean (`True` ou `False`). # In[48]: def q6(): stat, p =",
"= False, nan_policy = 'omit') #False: se falso, execute o teste t de",
"Responda com um boolean (`True` ou `False`). # In[10]: def q1(): amostra_q1 =",
"seaborn as sns import statsmodels.api as sm # In[2]: #%matplotlib inline from IPython.core.pylabtools",
"de 5%? Responda com um boolean (`True` ou `False`). # In[23]: def q4():",
"print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[17]: q2() # __Para refletir__: #",
"np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[24]:",
"pandas.Series Sample of size n from dataframe's column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index,",
"= amostra_q4_transformada) # > __Para as questão 5 6 e 7 a seguir",
"It drops any numpy.nan entries before sampling. The sampling is performed without replacement.",
"afirmar que as alturas são normalmente distribuídas (ao nível de significância de 5%)?",
"transformação logarítmica em na amostra de `weight` da questão 3 e repita o",
"# # Repita o procedimento da questão 5, mas agora entre as alturas",
"questão 5, mas agora entre as alturas de `bra` e `can`. Podemos afimar",
"hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') # ## Questão 7 #",
"seen yet. Parameters ---------- df : pandas.DataFrame Source dataframe. col_name : str Name",
"int Sample size. Default is 100. seed : int Random seed. Default is",
"Olimpíadas de 2016 no Rio de Janeiro. # # Esse _data set_ conta",
"1 # # Considerando uma amostra de tamanho 3000 da coluna `height` obtida",
"> Obs.: Por favor, não modifique o nome das funções de resposta. #",
"\"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array com index das",
"if p > 0.05: print('Probably the same distribution') else: print('Probably different distributions') return",
"sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show () # In[22]: sns.boxplot(data = amostra_q3) # ##",
"_data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os",
"de significância razoável que nos dê outro resultado no teste? (Não faça isso",
"without replacement. Example of numpydoc for those who haven't seen yet. Parameters ----------",
"(`height`) e peso (`weight`). As análises feitas aqui são parte de uma Análise",
"(athletes.nationality == 'CAN')] # In[28]: bra = athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality",
"bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') # ## Questão 7",
"return float(np.round(p, 8)) # In[88]: q7() # __Para refletir__: # # * O",
"partir daqui # In[9]: # Sua análise começa aqui. # ## Questão 1",
"bins=25, hist_kws={\"density\": True}) plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () #",
"o mesmo procedimento acima, mas agora utilizando o teste de normalidade de Jarque-Bera",
"amostra_q3) # ## Questão 4 # # Realize uma transformação logarítmica em na",
"bins=25, hist=False, rug=True, label='CAN') # ## Questão 7 # # Repita o procedimento",
"p-valor? # * Você consegue chegar a esse valor de p-valor a partir",
"figsize figsize(12, 8) sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() #",
"amostra de tamanho 3000 da coluna `weight` obtida com a função `get_sample()`. Faça",
"= sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute",
"= get_sample(athletes,'weight', n=3000, seed=42) stat, p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p>",
"tamanho 3000 da coluna `weight` obtida com a função `get_sample()`. Faça o teste",
"> 0.05: print('Probably the same distribution') else: print('Probably different distributions') return float(np.round(p, 8))",
"de tamanho 3000 da coluna `weight` obtida com a função `get_sample()`. Faça o",
"as sns import statsmodels.api as sm # In[2]: #%matplotlib inline from IPython.core.pylabtools import",
"sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') # ## Questão 6 # # Repita o",
"# ## Questão 3 # # Considerando agora uma amostra de tamanho 3000",
"# # * Esse resultado faz sentido? # In[18]: amostra_q2 = get_sample(athletes,'height', n=3000,",
"seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[17]:",
"In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () # In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42)",
"print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[20]: q3() # __Para refletir__: #",
"igual variação populaciona print('stat= {}, p={}'.format(stat,p)) if p > 0.05: print('Probably the same",
"In[87]: def q7(): stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy =",
"import matplotlib.pyplot as plt import numpy as np import scipy.stats as sct import",
"bool(p> 0.05) # In[20]: q3() # __Para refletir__: # # * Plote o",
"`False`). # In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat, p =",
"Exploratória de Dados (EDA). # # > Obs.: Por favor, não modifique o",
"# In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\")",
"can['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute o teste",
"Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das Olimpíadas",
"podemos afirmar que as alturas são normalmente distribuídas (ao nível de significância de",
"resultado faz sentido? # In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\")",
"Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') sns.distplot(can['height'], bins=25, hist=False, rug=True,",
"= sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p)) #",
"* Existe algum nível de significância razoável que nos dê outro resultado no",
"# In[2]: #%matplotlib inline from IPython.core.pylabtools import figsize figsize(12, 8) sns.set() # In[3]:",
"__Para as questão 5 6 e 7 a seguir considere todos testes efetuados",
"`scipy.stats.shapiro()`. Podemos afirmar que as alturas são normalmente distribuídas com base nesse teste",
"mesmo procedimento acima, mas agora utilizando o teste de normalidade de Jarque-Bera através",
"series com index e valor da coluna # ## Inicia sua análise a",
"q2() # __Para refletir__: # # * Esse resultado faz sentido? # In[18]:",
"com a função `scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos afirmar que as médias",
"alturas de `bra` e `can`. Podemos afimar agora que as médias são estatisticamente",
"procedimento da questão 6, mas agora entre as alturas de `usa` e `can`.",
"faça isso na prática. Isso é chamado _p-value hacking_, e não é legal).",
"`weight` obtida com a função `get_sample()`. Faça o teste de normalidade de D'Agostino-Pearson",
"estatisticamente iguais? Reponda com um boolean (`True` ou `False`). # In[48]: def q6():",
"valor do p-valor retornado? Responda como um único escalar arredondado para oito casas",
"Name of the column to be sampled. n : int Sample size. Default",
"significância de 5%)? Responda com um boolean (`True` ou `False`). # In[16]: def",
"de resposta. # ## _Setup_ geral # In[1]: import pandas as pd import",
"com informações gerais sobre 11538 atletas como nome, nacionalidade, altura, peso e esporte",
"variável (com, por exemplo, `bins=25`). A forma do gráfico e o resultado do",
"com a função `scipy.stats.shapiro()`. Podemos afirmar que as alturas são normalmente distribuídas com",
"* Você consegue interpretar esse p-valor? # * Você consegue chegar a esse",
"com um boolean (`True` ou `False`). # In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight',",
"len(usa) + len(can) - 2 print(f\"Graus de liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2",
"`bra` e `can`. Podemos afimar agora que as médias são estatisticamente iguais? Reponda",
"In[8]: def get_sample(df, col_name, n=100, seed=42): \"\"\"Get a sample from a column of",
"# In[8]: def get_sample(df, col_name, n=100, seed=42): \"\"\"Get a sample from a column",
"iguais? Responda com um boolean (`True` ou `False`). # In[27]: athletes.columns # In[45]:",
"100. seed : int Random seed. Default is 42. Returns ------- pandas.Series Sample",
"o nome das funções de resposta. # ## _Setup_ geral # In[1]: import",
"line=\"45\") plt.show () # In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p =",
"obtida com a função `get_sample()`. Faça o teste de normalidade de D'Agostino-Pearson utilizando",
"bool(p> 0.05) # In[17]: q2() # __Para refletir__: # # * Esse resultado",
"são estatisticamente iguais? Responda com um boolean (`True` ou `False`). # In[27]: athletes.columns",
"n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) #",
"médias são estatisticamente iguais? Responda com um boolean (`True` ou `False`). # In[27]:",
"não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[49]:",
"8)) # In[88]: q7() # __Para refletir__: # # * O resultado faz",
"In[4]: athletes.info() # In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]:",
"a column of a dataframe. It drops any numpy.nan entries before sampling. The",
"pandas.DataFrame Source dataframe. col_name : str Name of the column to be sampled.",
"n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show () # In[26]:",
"da questão 5, mas agora entre as alturas de `bra` e `can`. Podemos",
"hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') # ## Questão 6 #",
"Questão 3 # # Considerando agora uma amostra de tamanho 3000 da coluna",
"contém dados sobre os atletas das Olimpíadas de 2016 no Rio de Janeiro.",
"ou `False`). # In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat, p",
"4 # # Realize uma transformação logarítmica em na amostra de `weight` da",
"rug=True, label='CAN') # ## Questão 7 # # Repita o procedimento da questão",
"refletir__: # # * Esse resultado faz sentido? # In[18]: amostra_q2 = get_sample(athletes,'height',",
"[2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das",
"# Neste desafio, vamos praticar um pouco sobre testes de hipóteses. Utilizaremos o",
"`usa` e `can`. Qual o valor do p-valor retornado? Responda como um único",
"* Plote o histograma dessa variável (com, por exemplo, `bins=25`). A forma do",
"# In[19]: def q3(): amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) stat, p = sct.normaltest(amostra_q3)",
"In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True,",
"e o resultado do teste são condizentes? Por que? # * Um _box",
"funções de resposta. # ## _Setup_ geral # In[1]: import pandas as pd",
"uma transformação logarítmica em na amostra de `weight` da questão 3 e repita",
"# ## Questão 2 # # Repita o mesmo procedimento acima, mas agora",
"is 100. seed : int Random seed. Default is 42. Returns ------- pandas.Series",
"de significância de 5%__. # ## Questão 5 # # Obtenha todos atletas",
"Janeiro. # # Esse _data set_ conta com informações gerais sobre 11538 atletas",
"gl)*2 #Para Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') sns.distplot(can['height'],",
"brasileiros, norte-americanos e canadenses em `DataFrame`s chamados `bra`, `usa` e `can`,respectivamente. Realize um",
"# __Para refletir__: # # * Plote o histograma dessa variável (com, por",
"um resultado diferente agora? # In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada =",
"True}) plt.show () # In[26]: sns.boxplot(data = amostra_q4_transformada) # > __Para as questão",
"esperava um resultado diferente agora? # In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada",
"um boolean (`True` ou `False`). # In[27]: athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA')",
"da questão 6, mas agora entre as alturas de `usa` e `can`. Qual",
"refletir__: # # * O resultado faz sentido? # * Você consegue interpretar",
"seed=42) stat, p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[11]:",
"sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[17]: q2() # __Para refletir__:",
"+ len(can) - 2 print(f\"Graus de liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para",
"= 'omit') #False: se falso, execute o teste t de Welch, que não",
"= pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]:",
": int Random seed. Default is 42. Returns ------- pandas.Series Sample of size",
"coding: utf-8 # # Desafio 4 # # Neste desafio, vamos praticar um",
"amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat=",
"print('Probably different distributions') return float(np.round(p, 8)) # In[88]: q7() # __Para refletir__: #",
"e peso (`weight`). As análises feitas aqui são parte de uma Análise Exploratória",
"# In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name, n=100, seed=42):",
"nacionalidade, altura, peso e esporte praticado. Estaremos especialmente interessados nas variáveis numéricas altura",
"sm # In[2]: #%matplotlib inline from IPython.core.pylabtools import figsize figsize(12, 8) sns.set() #",
"acima, mas agora utilizando o teste de normalidade de Jarque-Bera através da função",
"Podemos afirmar a normalidade da variável transformada ao nível de significância de 5%?",
"matplotlib.pyplot as plt import numpy as np import scipy.stats as sct import seaborn",
"In[2]: #%matplotlib inline from IPython.core.pylabtools import figsize figsize(12, 8) sns.set() # In[3]: athletes",
"p={}'.format(stat,p)) return bool(p> 0.05) # In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True,",
"= get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () # ## Questão 3",
"before sampling. The sampling is performed without replacement. Example of numpydoc for those",
"{gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25,",
"get_sample(athletes,'weight', n=3000, seed=42) stat, p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05)",
"fit=True, line=\"45\") plt.show () # ## Questão 3 # # Considerando agora uma",
"`usa` e `can`,respectivamente. Realize um teste de hipóteses para comparação das médias das",
"equal_var = False, nan_policy = 'omit') #False: se falso, execute o teste t",
"estatisticamente iguais? Responda com um boolean (`True` ou `False`). # In[27]: athletes.columns #",
"com index e valor da coluna # ## Inicia sua análise a partir",
"de Dados (EDA). # # > Obs.: Por favor, não modifique o nome",
"# ## Inicia sua análise a partir daqui # In[9]: # Sua análise",
"sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') # ## Questão",
"que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) #",
"e o resultado do teste são condizentes? Por que? # * Você esperava",
"a função `scipy.stats.normaltest()`. Podemos afirmar que os pesos vêm de uma distribuição normal",
"= athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality ==",
"0.05) # In[24]: q4() # __Para refletir__: # # * Plote o histograma",
"Obtenha todos atletas brasileiros, norte-americanos e canadenses em `DataFrame`s chamados `bra`, `usa` e",
"interpretar esse p-valor? # * Você consegue chegar a esse valor de p-valor",
"In[16]: def q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat=",
"## Questão 7 # # Repita o procedimento da questão 6, mas agora",
"- 2 print(f\"Graus de liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal",
"= sct.shapiro(amostra_q1) p > 0.0000001 # ## Questão 2 # # Repita o",
"in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das Olimpíadas de",
"chamado _p-value hacking_, e não é legal). # In[12]: amostra_q1 = get_sample(athletes,'height', n=3000,",
"em na amostra de `weight` da questão 3 e repita o mesmo procedimento.",
"In[33]: def q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy =",
"0.05: print('Probably the same distribution') else: print('Probably different distributions') return float(np.round(p, 8)) #",
"utilizando o teste de normalidade de Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora podemos",
"amostra_q4_transformada) # > __Para as questão 5 6 e 7 a seguir considere",
"3 e repita o mesmo procedimento. Podemos afirmar a normalidade da variável transformada",
"com um boolean (`True` ou `False`). # In[16]: def q2(): amostra_q2 = get_sample(athletes,'height',",
"{}, p={}'.format(stat,p)) return bool(p> 0.05) # In[34]: q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False,",
"# ## Questão 5 # # Obtenha todos atletas brasileiros, norte-americanos e canadenses",
"# In[1]: import pandas as pd import matplotlib.pyplot as plt import numpy as",
"| (athletes.nationality == 'CAN')] # In[28]: bra = athletes[athletes.nationality == 'BRA'] usa =",
"algum nível de significância razoável que nos dê outro resultado no teste? (Não",
"Repita o procedimento da questão 5, mas agora entre as alturas de `bra`",
"interessados nas variáveis numéricas altura (`height`) e peso (`weight`). As análises feitas aqui",
"= sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False, rug=True,",
"11538 atletas como nome, nacionalidade, altura, peso e esporte praticado. Estaremos especialmente interessados",
"Desafio 4 # # Neste desafio, vamos praticar um pouco sobre testes de",
"como nome, nacionalidade, altura, peso e esporte praticado. Estaremos especialmente interessados nas variáveis",
"n from dataframe's column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma",
"of the column to be sampled. n : int Sample size. Default is",
": str Name of the column to be sampled. n : int Sample",
"n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () # ## Questão 3 # #",
"# Repita o procedimento da questão 5, mas agora entre as alturas de",
"Repita o procedimento da questão 6, mas agora entre as alturas de `usa`",
"faz sentido? # * Você consegue interpretar esse p-valor? # * Você consegue",
"(`True` ou `False`). # In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada",
"Um _box plot_ também poderia ajudar a entender a resposta. # In[21]: amostra_q3",
"n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) p > 0.0000001 # ## Questão 2",
"n=3000, seed=42) stat, p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) #",
"teste são condizentes? Por que? # * Um _box plot_ também poderia ajudar",
"Por que? # * Você esperava um resultado diferente agora? # In[25]: amostra_q4",
"que as médias são estatisticamente iguais? Responda com um boolean (`True` ou `False`).",
"import seaborn as sns import statsmodels.api as sm # In[2]: #%matplotlib inline from",
"boolean (`True` ou `False`). # In[27]: athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA') |",
"ao nível de significância de 5%__. # ## Questão 5 # # Obtenha",
"'BRA') | (athletes.nationality == 'USA') | (athletes.nationality == 'CAN')] # In[28]: bra =",
"## Questão 2 # # Repita o mesmo procedimento acima, mas agora utilizando",
"# # Repita o mesmo procedimento acima, mas agora utilizando o teste de",
"sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show () # In[26]: sns.boxplot(data = amostra_q4_transformada) # >",
"considere todos testes efetuados ao nível de significância de 5%__. # ## Questão",
"= np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) #",
"a resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True})",
"# In[48]: def q6(): stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy",
"5%? Responda com um boolean (`True` ou `False`). # In[23]: def q4(): amostra_q4",
"e não é legal). # In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) # In[13]:",
"agora entre as alturas de `bra` e `can`. Podemos afimar agora que as",
"sobre 11538 atletas como nome, nacionalidade, altura, peso e esporte praticado. Estaremos especialmente",
"de tamanho 3000 da coluna `height` obtida com a função `get_sample()`, execute o",
"# * Você consegue chegar a esse valor de p-valor a partir da",
"logarítmica em na amostra de `weight` da questão 3 e repita o mesmo",
"atletas como nome, nacionalidade, altura, peso e esporte praticado. Estaremos especialmente interessados nas",
"haven't seen yet. Parameters ---------- df : pandas.DataFrame Source dataframe. col_name : str",
"any numpy.nan entries before sampling. The sampling is performed without replacement. Example of",
"os pesos vêm de uma distribuição normal ao nível de significância de 5%?",
"teste (ao nível de significância de 5%)? Responda com um boolean (`True` ou",
"p = sct.shapiro(amostra_q1) p > 0.0000001 # ## Questão 2 # # Repita",
"= amostra_q3) # ## Questão 4 # # Realize uma transformação logarítmica em",
"`bins=25`). A forma do gráfico e o resultado do teste são condizentes? Por",
"plt.show () # In[22]: sns.boxplot(data = amostra_q3) # ## Questão 4 # #",
"athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name, n=100, seed=42): \"\"\"Get a sample from a",
"np import scipy.stats as sct import seaborn as sns import statsmodels.api as sm",
"gerais sobre 11538 atletas como nome, nacionalidade, altura, peso e esporte praticado. Estaremos",
"da coluna `weight` obtida com a função `get_sample()`. Faça o teste de normalidade",
"5%)? Responda com um boolean (`True` ou `False`). # In[10]: def q1(): amostra_q1",
"# # Repita o procedimento da questão 6, mas agora entre as alturas",
"can['height'].describe() # In[47]: can.isna().sum() # In[33]: def q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'],",
"q4() # __Para refletir__: # # * Plote o histograma dessa variável (com,",
"`can`,respectivamente. Realize um teste de hipóteses para comparação das médias das alturas (`height`)",
"A forma do gráfico e o resultado do teste são condizentes? Por que?",
"else: print('Probably different distributions') return float(np.round(p, 8)) # In[88]: q7() # __Para refletir__:",
"Utilizaremos o _data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados",
"#retorna uma array com index das colunas return df.loc[random_idx, col_name] #retorna uma series",
": int Sample size. Default is 100. seed : int Random seed. Default",
"a função `scipy.stats.shapiro()`. Podemos afirmar que as alturas são normalmente distribuídas com base",
"de significância de 5%? Responda com um boolean (`True` ou `False`). # In[23]:",
"print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN')",
"## Inicia sua análise a partir daqui # In[9]: # Sua análise começa",
"agora uma amostra de tamanho 3000 da coluna `weight` obtida com a função",
"import pandas as pd import matplotlib.pyplot as plt import numpy as np import",
"bra = athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality",
"# In[46]: can['height'].describe() # In[47]: can.isna().sum() # In[33]: def q5(): stat, p =",
"ou `False`). # In[10]: def q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p",
"Questão 1 # # Considerando uma amostra de tamanho 3000 da coluna `height`",
"bool(p> 0.05) # In[49]: q6() # In[50]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(can['height'],",
"#Para Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') sns.distplot(can['height'], bins=25,",
"resultado do teste são condizentes? Por que? # * Plote o qq-plot para",
"{}, p={}'.format(stat,p)) # In[69]: #grau de liberdade para o teste t independente com",
"stat, p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[20]: q3()",
"é chamado _p-value hacking_, e não é legal). # In[12]: amostra_q1 = get_sample(athletes,'height',",
"populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[34]: q5() # In[35]: sns.distplot(bra['height'],",
"`can`. Qual o valor do p-valor retornado? Responda como um único escalar arredondado",
"de 5%__. # ## Questão 5 # # Obtenha todos atletas brasileiros, norte-americanos",
"chegar a esse valor de p-valor a partir da variável de estatística? #",
"resultado do teste são condizentes? Por que? # * Um _box plot_ também",
"athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe() # In[30]:",
"as médias são estatisticamente iguais? Responda com um boolean (`True` ou `False`). #",
"outro resultado no teste? (Não faça isso na prática. Isso é chamado _p-value",
"q5() # In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA')",
"pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as sct",
"distribuição normal ao nível de significância de 5%? Responda com um boolean (`True`",
"amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show () # In[22]:",
"vamos praticar um pouco sobre testes de hipóteses. Utilizaremos o _data set_ [2016",
"forma do gráfico e o resultado do teste são condizentes? Por que? #",
"= True, nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau de liberdade",
"amostra de `weight` da questão 3 e repita o mesmo procedimento. Podemos afirmar",
"sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () # In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat,",
"# # Neste desafio, vamos praticar um pouco sobre testes de hipóteses. Utilizaremos",
"da questão 3 e repita o mesmo procedimento. Podemos afirmar a normalidade da",
"return bool(p> 0.05) # In[24]: q4() # __Para refletir__: # # * Plote",
"= sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute",
"essa variável e a analise. # * Existe algum nível de significância razoável",
"p = sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se falso,",
"das funções de resposta. # ## _Setup_ geral # In[1]: import pandas as",
"sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show ()",
"Esse resultado faz sentido? # In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True,",
"the column to be sampled. n : int Sample size. Default is 100.",
"`weight` da questão 3 e repita o mesmo procedimento. Podemos afirmar a normalidade",
"são parte de uma Análise Exploratória de Dados (EDA). # # > Obs.:",
"sua análise a partir daqui # In[9]: # Sua análise começa aqui. #",
"`get_sample()`. Faça o teste de normalidade de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos",
"# In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True})",
"`False`). # In[16]: def q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat, p =",
"def q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy = 'omit')",
"variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[49]: q6() # In[50]:",
"replace=False) #retorna uma array com index das colunas return df.loc[random_idx, col_name] #retorna uma",
"(`True` ou `False`). # In[10]: def q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat,",
"utilizando a função `scipy.stats.normaltest()`. Podemos afirmar que os pesos vêm de uma distribuição",
"of size n from dataframe's column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False)",
"o teste de normalidade de Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos afirmar que",
"(`weight`). As análises feitas aqui são parte de uma Análise Exploratória de Dados",
"p-valor a partir da variável de estatística? # In[72]: stat, p = sct.ttest_ind(usa['height'],",
"uma amostra de tamanho 3000 da coluna `weight` obtida com a função `get_sample()`.",
": pandas.DataFrame Source dataframe. col_name : str Name of the column to be",
"Neste desafio, vamos praticar um pouco sobre testes de hipóteses. Utilizaremos o _data",
"distributions') return float(np.round(p, 8)) # In[88]: q7() # __Para refletir__: # # *",
"== 'CAN'] # In[29]: bra['height'].describe() # In[30]: bra.isna().sum() # In[31]: usa['height'].describe() # In[32]:",
"who haven't seen yet. Parameters ---------- df : pandas.DataFrame Source dataframe. col_name :",
"coluna # ## Inicia sua análise a partir daqui # In[9]: # Sua",
"diferente agora? # In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada,",
"teste? (Não faça isso na prática. Isso é chamado _p-value hacking_, e não",
"as alturas de `bra` e `can`. Podemos afimar agora que as médias são",
"estatística? # In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy =",
"0.05) # In[20]: q3() # __Para refletir__: # # * Plote o histograma",
"amostra de tamanho 3000 da coluna `height` obtida com a função `get_sample()`, execute",
"In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') # ##",
"de significância de 5%? Responda com um boolean (`True` ou `False`). # In[19]:",
"## Questão 5 # # Obtenha todos atletas brasileiros, norte-americanos e canadenses em",
"= sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[11]: q1() # __Para",
"p={}'.format(stat,p)) if p > 0.05: print('Probably the same distribution') else: print('Probably different distributions')",
"e `usa`. Podemos afirmar que as médias são estatisticamente iguais? Responda com um",
"dê outro resultado no teste? (Não faça isso na prática. Isso é chamado",
"Você consegue interpretar esse p-valor? # * Você consegue chegar a esse valor",
"In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name, n=100, seed=42): \"\"\"Get a sample from",
"# # * O resultado faz sentido? # * Você consegue interpretar esse",
"Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos afirmar que as alturas são normalmente distribuídas",
"() # In[22]: sns.boxplot(data = amostra_q3) # ## Questão 4 # # Realize",
"de normalidade de Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora podemos afirmar que as",
"não modifique o nome das funções de resposta. # ## _Setup_ geral #",
"2016 no Rio de Janeiro. # # Esse _data set_ conta com informações",
"Por que? # * Plote o qq-plot para essa variável e a analise.",
"__Para refletir__: # # * O resultado faz sentido? # * Você consegue",
"hipóteses. Utilizaremos o _data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém",
"sct.t.sf(stat, gl)*2 #Para Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA')",
"In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality == 'USA') | (athletes.nationality == 'CAN')] #",
"= get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p>",
"nível de significância de 5%)? Responda com um boolean (`True` ou `False`). #",
"True}) plt.show () # In[22]: sns.boxplot(data = amostra_q3) # ## Questão 4 #",
"das colunas return df.loc[random_idx, col_name] #retorna uma series com index e valor da",
"Default is 100. seed : int Random seed. Default is 42. Returns -------",
"return bool(p> 0.05) # In[11]: q1() # __Para refletir__: # # * Plote",
"se falso, execute o teste t de Welch, que não assume igual variação",
"can = athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe() # In[30]: bra.isna().sum() # In[31]:",
"Responda com um boolean (`True` ou `False`). # In[16]: def q2(): amostra_q2 =",
"o _data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre",
"do teste são condizentes? Por que? # * Um _box plot_ também poderia",
"(ao nível de significância de 5%)? Responda com um boolean (`True` ou `False`).",
"normalmente distribuídas com base nesse teste (ao nível de significância de 5%)? Responda",
"que contém dados sobre os atletas das Olimpíadas de 2016 no Rio de",
"de 5%)? Responda com um boolean (`True` ou `False`). # In[16]: def q2():",
"athletes[(athletes.nationality == 'BRA') | (athletes.nationality == 'USA') | (athletes.nationality == 'CAN')] # In[28]:",
"Random seed. Default is 42. Returns ------- pandas.Series Sample of size n from",
"Welch, que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) if p >",
"variável de estatística? # In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = True,",
"index das colunas return df.loc[random_idx, col_name] #retorna uma series com index e valor",
"In[31]: usa['height'].describe() # In[32]: usa.isna().sum() # In[46]: can['height'].describe() # In[47]: can.isna().sum() # In[33]:",
"from IPython.core.pylabtools import figsize figsize(12, 8) sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\") #",
"que? # * Plote o qq-plot para essa variável e a analise. #",
"random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array com index das colunas return",
"normalmente distribuídas (ao nível de significância de 5%)? Responda com um boolean (`True`",
"replacement. Example of numpydoc for those who haven't seen yet. Parameters ---------- df",
"# Considerando agora uma amostra de tamanho 3000 da coluna `weight` obtida com",
"0.0000001 # ## Questão 2 # # Repita o mesmo procedimento acima, mas",
"das Olimpíadas de 2016 no Rio de Janeiro. # # Esse _data set_",
"# In[33]: def q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy",
"column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array com index",
"modifique o nome das funções de resposta. # ## _Setup_ geral # In[1]:",
"7 a seguir considere todos testes efetuados ao nível de significância de 5%__.",
"# In[87]: def q7(): stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = False, nan_policy",
"print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau de liberdade para o teste t independente",
"array com index das colunas return df.loc[random_idx, col_name] #retorna uma series com index",
"nível de significância razoável que nos dê outro resultado no teste? (Não faça",
"True, nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau de liberdade para",
"todos testes efetuados ao nível de significância de 5%__. # ## Questão 5",
"resultado no teste? (Não faça isso na prática. Isso é chamado _p-value hacking_,",
"efetuados ao nível de significância de 5%__. # ## Questão 5 # #",
"variável transformada ao nível de significância de 5%? Responda com um boolean (`True`",
"testes efetuados ao nível de significância de 5%__. # ## Questão 5 #",
"# In[30]: bra.isna().sum() # In[31]: usa['height'].describe() # In[32]: usa.isna().sum() # In[46]: can['height'].describe() #",
"len(can) - 2 print(f\"Graus de liberdade: {gl}\") q7_sf = sct.t.sf(stat, gl)*2 #Para Hipótese",
"# # Considerando uma amostra de tamanho 3000 da coluna `height` obtida com",
"Realize um teste de hipóteses para comparação das médias das alturas (`height`) para",
"gráfico e o resultado do teste são condizentes? Por que? # * Você",
"mas agora entre as alturas de `usa` e `can`. Qual o valor do",
"42. Returns ------- pandas.Series Sample of size n from dataframe's column. \"\"\" np.random.seed(seed)",
"can['height'], equal_var = True, nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau",
"# In[24]: q4() # __Para refletir__: # # * Plote o histograma dessa",
"são condizentes? Por que? # * Plote o qq-plot para essa variável e",
"inline from IPython.core.pylabtools import figsize figsize(12, 8) sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\")",
"gráfico e o resultado do teste são condizentes? Por que? # * Um",
"do teste são condizentes? Por que? # * Você esperava um resultado diferente",
"condizentes? Por que? # * Plote o qq-plot para essa variável e a",
"# In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) p >",
"que as médias são estatisticamente iguais? Reponda com um boolean (`True` ou `False`).",
"n : int Sample size. Default is 100. seed : int Random seed.",
"entre as alturas de `usa` e `can`. Qual o valor do p-valor retornado?",
"usa['height'].describe() # In[32]: usa.isna().sum() # In[46]: can['height'].describe() # In[47]: can.isna().sum() # In[33]: def",
"stat, p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[17]: q2()",
"0.05) # In[11]: q1() # __Para refletir__: # # * Plote o histograma",
"In[1]: import pandas as pd import matplotlib.pyplot as plt import numpy as np",
"informações gerais sobre 11538 atletas como nome, nacionalidade, altura, peso e esporte praticado.",
"hacking_, e não é legal). # In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) #",
"da variável transformada ao nível de significância de 5%? Responda com um boolean",
"p > 0.0000001 # ## Questão 2 # # Repita o mesmo procedimento",
"# Desafio 4 # # Neste desafio, vamos praticar um pouco sobre testes",
"nível de significância de 5%__. # ## Questão 5 # # Obtenha todos",
"coluna `weight` obtida com a função `get_sample()`. Faça o teste de normalidade de",
"que nos dê outro resultado no teste? (Não faça isso na prática. Isso",
"stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[24]: q4()",
"p={}'.format(stat,p)) return bool(p> 0.05) # In[11]: q1() # __Para refletir__: # # *",
"dessa variável (com, por exemplo, `bins=25`). A forma do gráfico e o resultado",
"np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show () # In[26]: sns.boxplot(data = amostra_q4_transformada) #",
"`bra` e `usa`. Podemos afirmar que as médias são estatisticamente iguais? Responda com",
"In[48]: def q6(): stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy =",
"| (athletes.nationality == 'USA') | (athletes.nationality == 'CAN')] # In[28]: bra = athletes[athletes.nationality",
"p = sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se falso,",
"equal_var = True, nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau de",
"= n1 + n2 - 2 gl = len(usa) + len(can) - 2",
"e a analise. # * Existe algum nível de significância razoável que nos",
"2 gl = len(usa) + len(can) - 2 print(f\"Graus de liberdade: {gl}\") q7_sf",
"são normalmente distribuídas (ao nível de significância de 5%)? Responda com um boolean",
"* Você consegue chegar a esse valor de p-valor a partir da variável",
"canadenses em `DataFrame`s chamados `bra`, `usa` e `can`,respectivamente. Realize um teste de hipóteses",
"get_sample(df, col_name, n=100, seed=42): \"\"\"Get a sample from a column of a dataframe.",
"In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p",
"In[32]: usa.isna().sum() # In[46]: can['height'].describe() # In[47]: can.isna().sum() # In[33]: def q5(): stat,",
"de normalidade de Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos afirmar que as alturas",
"Agora podemos afirmar que as alturas são normalmente distribuídas (ao nível de significância",
"# In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality == 'USA') | (athletes.nationality == 'CAN')]",
"# > Obs.: Por favor, não modifique o nome das funções de resposta.",
"teste são condizentes? Por que? # * Você esperava um resultado diferente agora?",
"a entender a resposta. # In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25,",
"* Esse resultado faz sentido? # In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2,",
"In[27]: athletes.columns # In[45]: athletes[(athletes.nationality == 'BRA') | (athletes.nationality == 'USA') | (athletes.nationality",
"aqui são parte de uma Análise Exploratória de Dados (EDA). # # >",
"boolean (`True` ou `False`). # In[48]: def q6(): stat, p = sct.ttest_ind(bra['height'], can['height'],",
"um único escalar arredondado para oito casas decimais. # In[87]: def q7(): stat,",
"sampling is performed without replacement. Example of numpydoc for those who haven't seen",
"a função `get_sample()`, execute o teste de normalidade de Shapiro-Wilk com a função",
"In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show () #",
"`scipy.stats.ttest_ind()` entre `bra` e `usa`. Podemos afirmar que as médias são estatisticamente iguais?",
"de Welch, que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) if p",
"Obs.: Por favor, não modifique o nome das funções de resposta. # ##",
"Existe algum nível de significância razoável que nos dê outro resultado no teste?",
"Por favor, não modifique o nome das funções de resposta. # ## _Setup_",
"Faça o teste de normalidade de D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos afirmar",
"sns.boxplot(data = amostra_q3) # ## Questão 4 # # Realize uma transformação logarítmica",
"= np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\": True}) plt.show () # In[26]: sns.boxplot(data = amostra_q4_transformada)",
"== 'USA') | (athletes.nationality == 'CAN')] # In[28]: bra = athletes[athletes.nationality == 'BRA']",
"8) sns.set() # In[3]: athletes = pd.read_csv(\"athletes.csv\") # In[4]: athletes.info() # In[5]: athletes.head()",
"In[30]: bra.isna().sum() # In[31]: usa['height'].describe() # In[32]: usa.isna().sum() # In[46]: can['height'].describe() # In[47]:",
"# In[69]: #grau de liberdade para o teste t independente com variancias semelhantes:",
"get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05)",
"usa = athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe()",
"amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) p > 0.0000001 #",
"# Esse _data set_ conta com informações gerais sobre 11538 atletas como nome,",
"label='CAN') # ## Questão 7 # # Repita o procedimento da questão 6,",
"retornado? Responda como um único escalar arredondado para oito casas decimais. # In[87]:",
"médias das alturas (`height`) para amostras independentes e variâncias diferentes com a função",
"plt.show () # In[26]: sns.boxplot(data = amostra_q4_transformada) # > __Para as questão 5",
"Default is 42. Returns ------- pandas.Series Sample of size n from dataframe's column.",
"da variável de estatística? # In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var =",
"não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[34]:",
"(Não faça isso na prática. Isso é chamado _p-value hacking_, e não é",
"# * Um _box plot_ também poderia ajudar a entender a resposta. #",
"uma Análise Exploratória de Dados (EDA). # # > Obs.: Por favor, não",
"valor da coluna # ## Inicia sua análise a partir daqui # In[9]:",
"set_ conta com informações gerais sobre 11538 atletas como nome, nacionalidade, altura, peso",
"2 # # Repita o mesmo procedimento acima, mas agora utilizando o teste",
"# In[35]: sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') #",
"5, mas agora entre as alturas de `bra` e `can`. Podemos afimar agora",
"## Questão 6 # # Repita o procedimento da questão 5, mas agora",
"stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy = 'omit') print('stat= {},",
"D'Agostino-Pearson utilizando a função `scipy.stats.normaltest()`. Podemos afirmar que os pesos vêm de uma",
"col_name : str Name of the column to be sampled. n : int",
"Podemos afirmar que os pesos vêm de uma distribuição normal ao nível de",
"In[24]: q4() # __Para refletir__: # # * Plote o histograma dessa variável",
"'BRA'] usa = athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality == 'CAN'] # In[29]:",
"df = n1 + n2 - 2 gl = len(usa) + len(can) -",
"n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show () # In[22]: sns.boxplot(data = amostra_q3)",
"# > __Para as questão 5 6 e 7 a seguir considere todos",
"sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[24]: q4() # __Para refletir__:",
"'omit') #False: se falso, execute o teste t de Welch, que não assume",
"igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[34]: q5() #",
"a partir da variável de estatística? # In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'],",
"p={}'.format(stat,p)) # In[69]: #grau de liberdade para o teste t independente com variancias",
"e valor da coluna # ## Inicia sua análise a partir daqui #",
"hist_kws={\"density\": True}) plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () # In[15]:",
"alturas de `usa` e `can`. Qual o valor do p-valor retornado? Responda como",
"agora entre as alturas de `usa` e `can`. Qual o valor do p-valor",
"_Setup_ geral # In[1]: import pandas as pd import matplotlib.pyplot as plt import",
"size=n, replace=False) #retorna uma array com index das colunas return df.loc[random_idx, col_name] #retorna",
"praticado. Estaremos especialmente interessados nas variáveis numéricas altura (`height`) e peso (`weight`). As",
"# In[5]: athletes.head() # In[6]: athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df,",
"q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p))",
"ou `False`). # In[16]: def q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat, p",
"is performed without replacement. Example of numpydoc for those who haven't seen yet.",
"na prática. Isso é chamado _p-value hacking_, e não é legal). # In[12]:",
"pouco sobre testes de hipóteses. Utilizaremos o _data set_ [2016 Olympics in Rio",
"análises feitas aqui são parte de uma Análise Exploratória de Dados (EDA). #",
"sentido? # In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show ()",
"'CAN')] # In[28]: bra = athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality == 'USA']",
"5 # # Obtenha todos atletas brasileiros, norte-americanos e canadenses em `DataFrame`s chamados",
"sns.boxplot(data = amostra_q4_transformada) # > __Para as questão 5 6 e 7 a",
"label='BRA') sns.distplot(can['height'], bins=25, hist=False, rug=True, label='CAN') # ## Questão 7 # # Repita",
"Por que? # * Um _box plot_ também poderia ajudar a entender a",
"condizentes? Por que? # * Um _box plot_ também poderia ajudar a entender",
"numéricas altura (`height`) e peso (`weight`). As análises feitas aqui são parte de",
"amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show ()",
"são condizentes? Por que? # * Um _box plot_ também poderia ajudar a",
"athletes[['height','weight']].describe() # In[7]: athletes[['height','weight']].hist() # In[8]: def get_sample(df, col_name, n=100, seed=42): \"\"\"Get a",
"uma amostra de tamanho 3000 da coluna `height` obtida com a função `get_sample()`,",
"# # * Plote o histograma dessa variável (com, por exemplo, `bins=25`). A",
"teste são condizentes? Por que? # * Plote o qq-plot para essa variável",
"para essa variável e a analise. # * Existe algum nível de significância",
"o resultado do teste são condizentes? Por que? # * Você esperava um",
"hipóteses para comparação das médias das alturas (`height`) para amostras independentes e variâncias",
"praticar um pouco sobre testes de hipóteses. Utilizaremos o _data set_ [2016 Olympics",
"conta com informações gerais sobre 11538 atletas como nome, nacionalidade, altura, peso e",
"função `scipy.stats.normaltest()`. Podemos afirmar que os pesos vêm de uma distribuição normal ao",
"p = sct.jarque_bera(amostra_q2) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[17]: q2() #",
"assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[49]: q6()",
"de estatística? # In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy",
"sct.shapiro(amostra_q1) p > 0.0000001 # ## Questão 2 # # Repita o mesmo",
"get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05)",
"def q6(): stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy = 'omit')",
"sentido? # * Você consegue interpretar esse p-valor? # * Você consegue chegar",
"no Rio de Janeiro. # # Esse _data set_ conta com informações gerais",
"# In[31]: usa['height'].describe() # In[32]: usa.isna().sum() # In[46]: can['height'].describe() # In[47]: can.isna().sum() #",
"assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[34]: q5()",
"= get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show () # In[22]: sns.boxplot(data",
"nos dê outro resultado no teste? (Não faça isso na prática. Isso é",
"#retorna uma series com index e valor da coluna # ## Inicia sua",
"= athletes[athletes.nationality == 'USA'] can = athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe() #",
"bins=25, hist=False, rug=True, label='USA') # ## Questão 6 # # Repita o procedimento",
"np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n, replace=False) #retorna uma array com index das colunas",
"## Questão 3 # # Considerando agora uma amostra de tamanho 3000 da",
"get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () # ## Questão 3 #",
"repita o mesmo procedimento. Podemos afirmar a normalidade da variável transformada ao nível",
"= get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show () #",
"na amostra de `weight` da questão 3 e repita o mesmo procedimento. Podemos",
"Example of numpydoc for those who haven't seen yet. Parameters ---------- df :",
"Sample size. Default is 100. seed : int Random seed. Default is 42.",
"que? # * Você esperava um resultado diferente agora? # In[25]: amostra_q4 =",
"O resultado faz sentido? # * Você consegue interpretar esse p-valor? # *",
"e o resultado do teste são condizentes? Por que? # * Plote o",
"procedimento. Podemos afirmar a normalidade da variável transformada ao nível de significância de",
"refletir__: # # * Plote o histograma dessa variável (com, por exemplo, `bins=25`).",
"(`height`) para amostras independentes e variâncias diferentes com a função `scipy.stats.ttest_ind()` entre `bra`",
"'USA') | (athletes.nationality == 'CAN')] # In[28]: bra = athletes[athletes.nationality == 'BRA'] usa",
"as questão 5 6 e 7 a seguir considere todos testes efetuados ao",
"(com, por exemplo, `bins=25`). A forma do gráfico e o resultado do teste",
"{}, p={}'.format(stat,p)) return bool(p> 0.05) # In[20]: q3() # __Para refletir__: # #",
"sampling. The sampling is performed without replacement. Example of numpydoc for those who",
"as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as",
"q5(): stat, p = sct.ttest_ind(bra['height'], usa['height'], equal_var = False, nan_policy = 'omit') #False:",
"assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) if p > 0.05: print('Probably the",
"{}, p={}'.format(stat,p)) return bool(p> 0.05) # In[17]: q2() # __Para refletir__: # #",
"#!/usr/bin/env python # coding: utf-8 # # Desafio 4 # # Neste desafio,",
"get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) stat, p = sct.normaltest(amostra_q4_transformada) print('stat= {}, p={}'.format(stat,p))",
"# In[29]: bra['height'].describe() # In[30]: bra.isna().sum() # In[31]: usa['height'].describe() # In[32]: usa.isna().sum() #",
"gl = len(usa) + len(can) - 2 print(f\"Graus de liberdade: {gl}\") q7_sf =",
"seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () # ## Questão 3 # # Considerando",
"nível de significância de 5%? Responda com um boolean (`True` ou `False`). #",
"não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) if p > 0.05: print('Probably",
"exemplo, `bins=25`). A forma do gráfico e o resultado do teste são condizentes?",
"seed=42) stat, p = sct.shapiro(amostra_q1) p > 0.0000001 # ## Questão 2 #",
"In[28]: bra = athletes[athletes.nationality == 'BRA'] usa = athletes[athletes.nationality == 'USA'] can =",
"questão 5 6 e 7 a seguir considere todos testes efetuados ao nível",
"#%matplotlib inline from IPython.core.pylabtools import figsize figsize(12, 8) sns.set() # In[3]: athletes =",
"Isso é chamado _p-value hacking_, e não é legal). # In[12]: amostra_q1 =",
"__Para refletir__: # # * Esse resultado faz sentido? # In[18]: amostra_q2 =",
"def q2(): amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.jarque_bera(amostra_q2) print('stat= {},",
"# In[18]: amostra_q2 = get_sample(athletes,'height', n=3000, seed=42) sm.qqplot(amostra_q2, fit=True, line=\"45\") plt.show () #",
"---------- df : pandas.DataFrame Source dataframe. col_name : str Name of the column",
"# # Esse _data set_ conta com informações gerais sobre 11538 atletas como",
"In[15]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) p > 0.0000001",
"transformada ao nível de significância de 5%? Responda com um boolean (`True` ou",
"* Você esperava um resultado diferente agora? # In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000,",
"def q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p = sct.shapiro(amostra_q1) print('stat= {},",
"## Questão 4 # # Realize uma transformação logarítmica em na amostra de",
"o mesmo procedimento. Podemos afirmar a normalidade da variável transformada ao nível de",
"# In[32]: usa.isna().sum() # In[46]: can['height'].describe() # In[47]: can.isna().sum() # In[33]: def q5():",
"nan_policy = 'omit') print('stat= {}, p={}'.format(stat,p)) # In[69]: #grau de liberdade para o",
"q6(): stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy = 'omit') #False:",
"analise. # * Existe algum nível de significância razoável que nos dê outro",
"plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () # In[15]: amostra_q1 =",
"Repita o mesmo procedimento acima, mas agora utilizando o teste de normalidade de",
"In[69]: #grau de liberdade para o teste t independente com variancias semelhantes: df",
"condizentes? Por que? # * Você esperava um resultado diferente agora? # In[25]:",
"In[12]: amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show",
"n=3000, seed=42) # In[13]: sns.distplot(amostra_q1, bins=25, hist_kws={\"density\": True}) plt.show () # In[14]: sm.qqplot(amostra_q1,",
"testes de hipóteses. Utilizaremos o _data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/),",
"True}) plt.show () # In[14]: sm.qqplot(amostra_q1, fit=True, line=\"45\") plt.show () # In[15]: amostra_q1",
"* Um _box plot_ também poderia ajudar a entender a resposta. # In[21]:",
"casas decimais. # In[87]: def q7(): stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var =",
"chamados `bra`, `usa` e `can`,respectivamente. Realize um teste de hipóteses para comparação das",
"{}, p={}'.format(stat,p)) return bool(p> 0.05) # In[24]: q4() # __Para refletir__: # #",
"Questão 5 # # Obtenha todos atletas brasileiros, norte-americanos e canadenses em `DataFrame`s",
"variação populaciona print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[34]: q5() # In[35]:",
"rug=True, label='USA') # ## Questão 6 # # Repita o procedimento da questão",
"de Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos afirmar que as alturas são normalmente",
"o teste t independente com variancias semelhantes: df = n1 + n2 -",
"seguir considere todos testes efetuados ao nível de significância de 5%__. # ##",
"sns.distplot(bra['height'], bins=25, hist=False, rug=True, label='BRA') sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') # ## Questão",
"de Janeiro. # # Esse _data set_ conta com informações gerais sobre 11538",
"athletes[athletes.nationality == 'CAN'] # In[29]: bra['height'].describe() # In[30]: bra.isna().sum() # In[31]: usa['height'].describe() #",
"t de Welch, que não assume igual variação populaciona print('stat= {}, p={}'.format(stat,p)) return",
"`False`). # In[23]: def q4(): amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4)",
"normalidade de Jarque-Bera através da função `scipy.stats.jarque_bera()`. Agora podemos afirmar que as alturas",
"populaciona print('stat= {}, p={}'.format(stat,p)) if p > 0.05: print('Probably the same distribution') else:",
"usa['height'], equal_var = False, nan_policy = 'omit') #False: se falso, execute o teste",
"# In[21]: amostra_q3 = get_sample(athletes,'weight', n=3000, seed=42) sns.distplot(amostra_q3, bins=25, hist_kws={\"density\": True}) plt.show ()",
"stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var = False, nan_policy = 'omit') #False: se",
"# In[72]: stat, p = sct.ttest_ind(usa['height'], can['height'], equal_var = True, nan_policy = 'omit')",
"uma array com index das colunas return df.loc[random_idx, col_name] #retorna uma series com",
"hist=False, rug=True, label='CAN') # ## Questão 7 # # Repita o procedimento da",
"# In[25]: amostra_q4 = get_sample(athletes,'weight', n=3000, seed=42) amostra_q4_transformada = np.log(amostra_q4) sns.distplot(amostra_q4_transformada, bins=25, hist_kws={\"density\":",
"> __Para as questão 5 6 e 7 a seguir considere todos testes",
"In[22]: sns.boxplot(data = amostra_q3) # ## Questão 4 # # Realize uma transformação",
"e `can`. Qual o valor do p-valor retornado? Responda como um único escalar",
"o resultado do teste são condizentes? Por que? # * Um _box plot_",
"same distribution') else: print('Probably different distributions') return float(np.round(p, 8)) # In[88]: q7() #",
"Sample of size n from dataframe's column. \"\"\" np.random.seed(seed) random_idx = np.random.choice(df[col_name].dropna().index, size=n,",
"print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[11]: q1() # __Para refletir__: #",
"plt.show () # ## Questão 3 # # Considerando agora uma amostra de",
"seed=42) stat, p = sct.normaltest(amostra_q3) print('stat= {}, p={}'.format(stat,p)) return bool(p> 0.05) # In[20]:",
"afirmar que os pesos vêm de uma distribuição normal ao nível de significância",
"afirmar que as médias são estatisticamente iguais? Responda com um boolean (`True` ou",
"ou `False`). # In[48]: def q6(): stat, p = sct.ttest_ind(bra['height'], can['height'], equal_var =",
"com variancias semelhantes: df = n1 + n2 - 2 gl = len(usa)",
"Responda com um boolean (`True` ou `False`). # In[19]: def q3(): amostra_q3 =",
"# ## Questão 1 # # Considerando uma amostra de tamanho 3000 da",
"o procedimento da questão 6, mas agora entre as alturas de `usa` e",
"Hipótese Bicaudal print(q7_sf) # In[77]: sns.distplot(usa['height'], bins=25, hist=False, rug=True, label='USA') sns.distplot(can['height'], bins=25, hist=False,",
"a analise. # * Existe algum nível de significância razoável que nos dê",
"alturas são normalmente distribuídas com base nesse teste (ao nível de significância de",
"dataframe. It drops any numpy.nan entries before sampling. The sampling is performed without",
"`get_sample()`, execute o teste de normalidade de Shapiro-Wilk com a função `scipy.stats.shapiro()`. Podemos",
"em `DataFrame`s chamados `bra`, `usa` e `can`,respectivamente. Realize um teste de hipóteses para",
"`False`). # In[10]: def q1(): amostra_q1 = get_sample(athletes,'height', n=3000, seed=42) stat, p =",
"que? # * Um _box plot_ também poderia ajudar a entender a resposta."
] |
[
"editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')),",
"'0002_post_likes'), ] operations = [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی ها',",
"'دسته بندی', 'verbose_name_plural': 'دسته بندی ها', }, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'),",
"class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'), ] operations = [ migrations.CreateModel( name='Categories',",
"editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural':",
"'verbose_name_plural': 'دسته بندی ها', }, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'), ), migrations.AlterUniqueTogether(",
"from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields",
"verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True,",
"django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [",
"('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,",
"'دسته بندی ها', }, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'), ), migrations.AlterUniqueTogether( name='categories',",
"<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-04",
"related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی ها', }, ),",
"to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی ها', }, ), migrations.AddField(",
"migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'),",
"# Generated by Django 1.11.20 on 2019-05-04 08:06 from __future__ import unicode_literals from",
"editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name':",
"models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'), ]",
"migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft',",
"operations = [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)),",
"mptt.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'), ] operations = [ migrations.CreateModel(",
"1.11.20 on 2019-05-04 08:06 from __future__ import unicode_literals from django.db import migrations, models",
"options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی ها', }, ), migrations.AddField( model_name='post', name='categories',",
"-*- # Generated by Django 1.11.20 on 2019-05-04 08:06 from __future__ import unicode_literals",
"coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-04 08:06 from __future__",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id',",
"models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی',",
"بندی ها', }, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'), ), migrations.AlterUniqueTogether( name='categories', unique_together=set([('parent',",
"on 2019-05-04 08:06 from __future__ import unicode_literals from django.db import migrations, models import",
"unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies",
"('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True,",
"-*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-04 08:06 from",
"بندی', 'verbose_name_plural': 'دسته بندی ها', }, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'), ),",
"import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'), ] operations",
"('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent',",
"django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'), ] operations =",
"], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی ها', }, ), migrations.AddField( model_name='post',",
"models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={",
"utf-8 -*- # Generated by Django 1.11.20 on 2019-05-04 08:06 from __future__ import",
"Django 1.11.20 on 2019-05-04 08:06 from __future__ import unicode_literals from django.db import migrations,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True,",
"'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی ها', }, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories',",
"Generated by Django 1.11.20 on 2019-05-04 08:06 from __future__ import unicode_literals from django.db",
"mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی",
"by Django 1.11.20 on 2019-05-04 08:06 from __future__ import unicode_literals from django.db import",
"2019-05-04 08:06 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion",
"('blog', '0002_post_likes'), ] operations = [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"ها', }, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'), ), migrations.AlterUniqueTogether( name='categories', unique_together=set([('parent', 'slug')]),",
"}, ), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'), ), migrations.AlterUniqueTogether( name='categories', unique_together=set([('parent', 'slug')]), ),",
"dependencies = [ ('blog', '0002_post_likes'), ] operations = [ migrations.CreateModel( name='Categories', fields=[ ('id',",
"from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies =",
"[ ('blog', '0002_post_likes'), ] operations = [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)),",
"= [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug',",
"models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True,",
"models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)),",
"), migrations.AddField( model_name='post', name='categories', field=mptt.fields.TreeManyToManyField(related_name='categories', to='blog.Categories'), ), migrations.AlterUniqueTogether( name='categories', unique_together=set([('parent', 'slug')]), ), ]",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)),",
"__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields class",
"('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته",
"('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ],",
"# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-04 08:06",
"Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'), ] operations = [ migrations.CreateModel( name='Categories', fields=[",
"editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True,",
"('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته",
"models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='category',",
"= [ ('blog', '0002_post_likes'), ] operations = [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True,",
"[ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)),",
"import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('blog',",
"import unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration):",
"name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True,",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght',",
"on_delete=django.db.models.deletion.CASCADE, related_name='category', to='blog.Categories')), ], options={ 'verbose_name': 'دسته بندی', 'verbose_name_plural': 'دسته بندی ها', },",
"08:06 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import",
"('name', models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),",
"import mptt.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_likes'), ] operations = [",
"] operations = [ migrations.CreateModel( name='Categories', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"models.CharField(max_length=50)), ('slug', models.SlugField(allow_unicode=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level',"
] |
[
"\"\"\"Print hello World.\"\"\" print(\"Hello, I am a cautious invention\") def add(x, y): \"\"\"Add",
"the utilities of cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello,",
"= 4 def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I am a cautious invention\")",
"-*- \"\"\"Contain the utilities of cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world(): \"\"\"Print hello",
"am a cautious invention\") def add(x, y): \"\"\"Add two numbers together.\"\"\" return x+y",
"World.\"\"\" print(\"Hello, I am a cautious invention\") def add(x, y): \"\"\"Add two numbers",
"def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I am a cautious invention\") def add(x,",
"print(\"Hello, I am a cautious invention\") def add(x, y): \"\"\"Add two numbers together.\"\"\"",
"4 def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I am a cautious invention\") def",
"\"\"\"Contain the utilities of cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world(): \"\"\"Print hello World.\"\"\"",
"utilities of cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I",
"# -*- coding: utf-8 -*- \"\"\"Contain the utilities of cautious-invention.\"\"\" my_awesome_constant = 4",
"of cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I am",
"my_awesome_constant = 4 def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I am a cautious",
"coding: utf-8 -*- \"\"\"Contain the utilities of cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world():",
"hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I am a cautious invention\") def add(x, y):",
"utf-8 -*- \"\"\"Contain the utilities of cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world(): \"\"\"Print",
"cautious-invention.\"\"\" my_awesome_constant = 4 def hello_world(): \"\"\"Print hello World.\"\"\" print(\"Hello, I am a",
"-*- coding: utf-8 -*- \"\"\"Contain the utilities of cautious-invention.\"\"\" my_awesome_constant = 4 def",
"I am a cautious invention\") def add(x, y): \"\"\"Add two numbers together.\"\"\" return",
"hello World.\"\"\" print(\"Hello, I am a cautious invention\") def add(x, y): \"\"\"Add two"
] |
[
"if(x <= 1) : return 1 if(x <= 2) : return 2 if(x",
"float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda",
"return 3 if(x <= 4) : return 4 else : return 5 def",
"pyspark import SparkConf, SparkContext def rating(x): if(x <= 1) : return 1 if(x",
"ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1])))",
"<gh_stars>0 from pyspark import SparkConf, SparkContext def rating(x): if(x <= 1) : return",
"import SparkConf, SparkContext def rating(x): if(x <= 1) : return 1 if(x <=",
"x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD",
"return 2 if(x <= 3) : return 3 if(x <= 4) : return",
"= SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf) input = sc.textFile(\"ratings.csv\") movieRating(input) if __name__",
"= SparkContext(conf = conf) input = sc.textFile(\"ratings.csv\") movieRating(input) if __name__ == '__main__': main()",
": return 4 else : return 5 def movieRating(input): ratingsRDD = input.map(lambda x:",
"= ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0],",
"= ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\")",
"from pyspark import SparkConf, SparkContext def rating(x): if(x <= 1) : return 1",
"def rating(x): if(x <= 1) : return 1 if(x <= 2) : return",
"ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating')",
"SparkConf, SparkContext def rating(x): if(x <= 1) : return 1 if(x <= 2)",
"conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf) input = sc.textFile(\"ratings.csv\") movieRating(input) if",
"3 if(x <= 4) : return 4 else : return 5 def movieRating(input):",
"ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf) input =",
"rating(x): if(x <= 1) : return 1 if(x <= 2) : return 2",
": return 1 if(x <= 2) : return 2 if(x <= 3) :",
"x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD =",
"= input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey()",
"3) : return 3 if(x <= 4) : return 4 else : return",
"<= 4) : return 4 else : return 5 def movieRating(input): ratingsRDD =",
"rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf)",
"main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf) input = sc.textFile(\"ratings.csv\") movieRating(input)",
"def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf) input = sc.textFile(\"ratings.csv\")",
"2) : return 2 if(x <= 3) : return 3 if(x <= 4)",
"x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main():",
"ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf) input",
"<= 1) : return 1 if(x <= 2) : return 2 if(x <=",
"(x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD =",
"1 if(x <= 2) : return 2 if(x <= 3) : return 3",
"ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey()",
"def movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2])))",
"return 5 def movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x:",
"movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD",
"sc = SparkContext(conf = conf) input = sc.textFile(\"ratings.csv\") movieRating(input) if __name__ == '__main__':",
"if(x <= 3) : return 3 if(x <= 4) : return 4 else",
"4) : return 4 else : return 5 def movieRating(input): ratingsRDD = input.map(lambda",
"= ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0],",
"4 else : return 5 def movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD",
"if(x <= 2) : return 2 if(x <= 3) : return 3 if(x",
"return 4 else : return 5 def movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\"))",
"x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda",
"ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc =",
"input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD",
"<= 2) : return 2 if(x <= 3) : return 3 if(x <=",
"(x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf",
"2 if(x <= 3) : return 3 if(x <= 4) : return 4",
"1) : return 1 if(x <= 2) : return 2 if(x <= 3)",
"<= 3) : return 3 if(x <= 4) : return 4 else :",
"5 def movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1],",
"ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x:",
"SparkContext def rating(x): if(x <= 1) : return 1 if(x <= 2) :",
"ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD =",
"x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf",
"ratingsRDD = ratingsRDD.map(lambda x: (x[1], float(x[2]))) ratingsRDD = ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x:",
"return 1 if(x <= 2) : return 2 if(x <= 3) : return",
"SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf = conf) input = sc.textFile(\"ratings.csv\") movieRating(input) if __name__ ==",
"if(x <= 4) : return 4 else : return 5 def movieRating(input): ratingsRDD",
": return 3 if(x <= 4) : return 4 else : return 5",
": return 5 def movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD = ratingsRDD.map(lambda",
"ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def",
": return 2 if(x <= 3) : return 3 if(x <= 4) :",
"= ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc",
"ratingsRDD.groupByKey().sortByKey() ratingsRDD = ratingsRDD.map(lambda x: (x[0], sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1]))))",
"else : return 5 def movieRating(input): ratingsRDD = input.map(lambda x: x.split(\",\")) ratingsRDD =",
"(x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf = SparkConf().setMaster('local').setAppName('MovieRating') sc = SparkContext(conf =",
"sum(list(x[1]))/len(x[1]))) ratingsRDD = ratingsRDD.map(lambda x: (x[0], rating(float(x[1])))) ratingsRDD.sortByKey() ratingsRDD.saveAsTextFile(\"output\") def main(): conf ="
] |
[
"'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags =",
"= Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12)",
"FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo in enumerate(self.combos): tags = [] for atom",
"'.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description='",
"BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\"",
"obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two )",
"q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(),",
"['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags",
"6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name)",
"> 0) tag_result = results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for",
"= Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12)",
"q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(),",
"'.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\",",
"in enumerate(self.combos): tags = [] for atom in combo: tag, created = Tag.objects.get_or_create(name=atom,",
"a wrench\", foo=\"bar\", feature_type=ft_one ) # We need to let the index refresh",
"one\", content.feature_type.name) def test_content_subclasses(self): # We created one of each subclass per combination",
"response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with",
"self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\")",
"= TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw a wrench\", foo=\"bar\", feature_type=ft_one ) #",
"import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\"",
"content.feature_type.name) def test_content_subclasses(self): # We created one of each subclass per combination so",
"'.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create(",
"tags = [] for atom in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag)",
"itertools import datetime from django.utils import timezone from django.test.client import Client from django.template.defaultfilters",
"picks up available doctypes from installed apps, but in this case, our test",
"= [] for atom in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag)",
"# The 12, plus the unpublished one q = Content.search_objects.search() self.assertEqual(q.count(), 12) q",
"content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results =",
"let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12,",
"test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content",
"1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client = Client() response",
"Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): #",
"test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses =",
"from tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally,",
"self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(),",
"foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just",
"obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw a wrench\", foo=\"bar\", feature_type=ft_one",
"so we'll hack them on. \"\"\" # generate some data one_hour_ago = timezone.now()",
"= Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(),",
"Normally, the \"Content\" class picks up available doctypes from installed apps, but in",
"self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c in Content.objects.all()] results =",
"1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client = Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200)",
"self).setUp() \"\"\" Normally, the \"Content\" class picks up available doctypes from installed apps,",
"= Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q =",
"len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client = Client() response = client.get('/content_list_one.html')",
"obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw a wrench\", foo=\"bar\", feature_type=ft_one )",
"created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)),",
"12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12)",
"each subclass per combination so the following should be true: self.assertEqual(Content.objects.count(), (len(self.combos) *",
"in a real app, so we'll hack them on. \"\"\" # generate some",
"our test models don't exist in a real app, so we'll hack them",
"+ 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client = Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code,",
"for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count",
"= Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q =",
"The 12, plus the unpublished one q = Content.search_objects.search() self.assertEqual(q.count(), 12) q =",
"6) for content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): # We created",
"q = Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"])",
"+ 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client = Client()",
"we'll hack them on. \"\"\" # generate some data one_hour_ago = timezone.now() -",
"def test_content_list_view(self): client = Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos)",
"obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two",
"test_content_subclasses(self): # We created one of each subclass per combination so the following",
"one of each subclass per combination so the following should be true: self.assertEqual(Content.objects.count(),",
"up available doctypes from installed apps, but in this case, our test models",
"self.assertEqual(q.count(), 1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(),",
"from installed apps, but in this case, our test models don't exist in",
"per combination so the following should be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) +",
"bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to",
"= Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full():",
"title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create(",
"Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result = results[0] self.assertIsInstance(tag_result, Tag)",
"2)) self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\",",
"= client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1",
"new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank')",
"self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full():",
"of each subclass per combination so the following should be true: self.assertEqual(Content.objects.count(), (len(self.combos)",
"content_ids = [c.id for c in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses = tuple(Content.__subclasses__())",
"\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\")",
"django.utils import timezone from django.test.client import Client from django.template.defaultfilters import slugify from bulbs.content.models",
"datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now()",
"self.assertEqual(q.count(), 12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(),",
"setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\" class picks up available doctypes from",
"in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses = tuple(Content.__subclasses__()) for result in results.values(): self.assertIsInstance(result,",
"the \"Content\" class picks up available doctypes from installed apps, but in this",
"django.template.defaultfilters import slugify from bulbs.content.models import Content, Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase",
"[] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i,",
"tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one )",
") obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw a wrench\",",
"self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for",
"one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words = ['spam',",
"enumerate(self.combos): tags = [] for atom in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom))",
"truck', 'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags = [] ft_one",
"def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo))",
"import absolute_import import itertools import datetime from django.utils import timezone from django.test.client import",
"tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo), description='",
"0) tag_result = results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c",
"= Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result = results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids",
"Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses = tuple(Content.__subclasses__()) for result in results.values(): self.assertIsInstance(result, subclasses)",
"title=\"Unpublished draft\", description=\"Just to throw a wrench\", foo=\"bar\", feature_type=ft_one ) # We need",
"= Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() -",
"the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12, plus",
"Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"])",
"q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True))",
"import slugify from bulbs.content.models import Content, Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from",
"= Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0],",
"self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj,",
"TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12, plus the unpublished one q",
"self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client =",
"= results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c in Content.objects.all()]",
"a real app, so we'll hack them on. \"\"\" # generate some data",
"def test_content_subclasses(self): # We created one of each subclass per combination so the",
"for i, combo in enumerate(self.combos): tags = [] for atom in combo: tag,",
"following should be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) +",
"- datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos",
"tag_result = results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c in",
"content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q =",
"- datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck',",
"in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now())",
"12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4))",
"Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q",
"TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw a wrench\", foo=\"bar\", feature_type=ft_one ) # We",
"client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 +",
"import datetime from django.utils import timezone from django.test.client import Client from django.template.defaultfilters import",
"from django.template.defaultfilters import slugify from bulbs.content.models import Content, Tag, FeatureType from elastimorphic.tests.base import",
"be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(),",
"from django.test.client import Client from django.template.defaultfilters import slugify from bulbs.content.models import Content, Tag,",
"flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name)",
"Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results",
"but in this case, our test models don't exist in a real app,",
"self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): # We created one of each subclass per",
"obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags)",
"6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6)",
"test models don't exist in a real app, so we'll hack them on.",
"import Client from django.template.defaultfilters import slugify from bulbs.content.models import Content, Tag, FeatureType from",
"200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for",
"test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count",
"\"\"\" Normally, the \"Content\" class picks up available doctypes from installed apps, but",
"generate some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2)",
"self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag =",
"slugify from bulbs.content.models import Content, Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models",
"TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 =",
"feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw a",
"Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertNotEqual(\"Obj",
"self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertTrue(\"spam\" in",
"the unpublished one q = Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6)",
"q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now()",
"in this case, our test models don't exist in a real app, so",
"test_content_list_view(self): client = Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) *",
"self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for content",
"self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertNotEqual(\"Obj one\",",
"datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"])",
"def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def",
"them on. \"\"\" # generate some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago",
"= Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q =",
"test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def",
"q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q",
"index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12, plus the",
"content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for",
"self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags)",
"Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase):",
"= FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo in",
"len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for content in Content.objects.all():",
"from __future__ import absolute_import import itertools import datetime from django.utils import timezone from",
"TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\" class",
"(len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self):",
"self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses):",
"# generate some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() -",
"so the following should be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(),",
"self.assertEqual(q.count(), 6) for content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(),",
"TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\" class picks",
"true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos))",
"from django.utils import timezone from django.test.client import Client from django.template.defaultfilters import slugify from",
"len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result =",
"list(itertools.combinations(words, 2)) self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj",
"results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c in Content.objects.all()] results",
"foo=\"bar\", feature_type=ft_one ) # We need to let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh()",
"= Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh()",
"test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result = results[0] self.assertIsInstance(tag_result,",
"self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0]",
"self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() -",
"[c.id for c in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses = tuple(Content.__subclasses__()) for result",
"12, plus the unpublished one q = Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\")",
"= timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses =",
"q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(),",
"FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo in enumerate(self.combos):",
"don't exist in a real app, so we'll hack them on. \"\"\" #",
"should be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1)",
"original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results)",
"Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self):",
"Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[",
"= Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q",
"content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q =",
"= timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver',",
"need to let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) #",
"wrench\", foo=\"bar\", feature_type=ft_one ) # We need to let the index refresh TestContentObj.search_objects.refresh()",
"# We created one of each subclass per combination so the following should",
"2 self.combos = list(itertools.combinations(words, 2)) self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\")",
"self.assertEqual(Content.objects.count(), 13) # The 12, plus the unpublished one q = Content.search_objects.search() self.assertEqual(q.count(),",
"= ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2))",
"Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag",
"timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2",
"# We need to let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(),",
"ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo in enumerate(self.combos): tags = []",
"django.test.client import Client from django.template.defaultfilters import slugify from bulbs.content.models import Content, Tag, FeatureType",
"foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo),",
"self.assertEqual(q.count(), 6) for content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): # We",
"q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q",
"datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck', 'restaurant']",
"def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12, plus the unpublished one q =",
"Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4))",
"c in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses = tuple(Content.__subclasses__()) for result in results.values():",
"published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw",
"* self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content,",
"'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags = []",
"client = Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses)",
"original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags']))",
"content = Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count +",
"created one of each subclass per combination so the following should be true:",
"12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6)",
"data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words =",
"self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12)",
"= Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q =",
"Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q",
"throw a wrench\", foo=\"bar\", feature_type=ft_one ) # We need to let the index",
"\"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q =",
"self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q =",
"this case, our test models don't exist in a real app, so we'll",
"test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self):",
"absolute_import import itertools import datetime from django.utils import timezone from django.test.client import Client",
"def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result = results[0]",
"= FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo in enumerate(self.combos): tags = [] for",
"for c in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses = tuple(Content.__subclasses__()) for result in",
"Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now()",
"content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): # We created one of",
"q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in",
"one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q",
"subclass per combination so the following should be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses)",
"to let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The",
"obj = TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index()",
"one q = Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q =",
"= 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj one\",",
"+ 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) >",
"q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q",
"q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in",
"len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self):",
"self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def",
"datetime from django.utils import timezone from django.test.client import Client from django.template.defaultfilters import slugify",
"i, combo in enumerate(self.combos): tags = [] for atom in combo: tag, created",
"Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result = results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids =",
"= Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self):",
"= Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q =",
"datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos =",
"(TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat')",
"apps, but in this case, our test models don't exist in a real",
"content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count =",
"\"\"\" # generate some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now()",
"from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self):",
"Client from django.template.defaultfilters import slugify from bulbs.content.models import Content, Tag, FeatureType from elastimorphic.tests.base",
"Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"])",
"1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6)",
"def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses",
"feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i,",
"q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q",
"import itertools import datetime from django.utils import timezone from django.test.client import Client from",
"12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1)",
"slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo in enumerate(self.combos): tags =",
"for content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6) q",
"unpublished one q = Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q",
"in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title='",
"= Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self):",
"def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for",
"len(self.combos)) def test_content_list_view(self): client = Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']),",
"= [c.id for c in Content.objects.all()] results = Content.objects.in_bulk(content_ids) subclasses = tuple(Content.__subclasses__()) for",
"words = ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words,",
"combo in enumerate(self.combos): tags = [] for atom in combo: tag, created =",
"Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q",
"Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago,",
"Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(), 6) q = Content.search_objects.search(feature_types=[\"-obj-one\"])",
"in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content",
"class picks up available doctypes from installed apps, but in this case, our",
"Content, Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo class",
"6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6)",
"self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client = Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual(",
"self.assertNumQueries(1 + self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content",
"in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count = len(content.tags.all())",
"timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver', 'dump",
"for atom in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj =",
"case, our test models don't exist in a real app, so we'll hack",
"exist in a real app, so we'll hack them on. \"\"\" # generate",
") # We need to let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self):",
"obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished draft\", description=\"Just to throw a wrench\", foo=\"bar\",",
"bulbs.content.models import Content, Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import TestContentObj,",
"'restaurant'] self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags = [] ft_one =",
"from bulbs.content.models import Content, Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import",
"Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6)",
"content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertEqual(\"Obj one\",",
"slug=\"obj-two\") for i, combo in enumerate(self.combos): tags = [] for atom in combo:",
"= len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def",
"q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def",
"some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago = timezone.now() - datetime.timedelta(days=2) words",
"to throw a wrench\", foo=\"bar\", feature_type=ft_one ) # We need to let the",
"TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj",
"Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q =",
"test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12, plus the unpublished one q = Content.search_objects.search()",
"self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full()",
"13) # The 12, plus the unpublished one q = Content.search_objects.search() self.assertEqual(q.count(), 12)",
"for content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6)",
"= Client() response = client.get('/content_list_one.html') self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context['object_list']), len(self.combos) * self.num_subclasses) def",
"combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo),",
"elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase,",
"= [] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for",
"two\", slug=\"obj-two\") for i, combo in enumerate(self.combos): tags = [] for atom in",
"PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\" class picks up available",
"q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in",
"6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\",",
"def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\" class picks up available doctypes",
"class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\" class picks up",
"self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(),",
"the following should be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos)",
"feature_type=ft_one ) # We need to let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def",
"q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\") self.assertEqual(q.count(),",
"published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1],",
"for content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): # We created one",
"ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo",
"We created one of each subclass per combination so the following should be",
"- datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q =",
"self.assertEqual(q.count(), 6) for content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"])",
"Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q",
"TestContentObjTwo)) def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag)",
"6) for content in q.full(): self.assertTrue(\"spam\" in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(),",
"atom in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create(",
"q = Content.search_objects.search(feature_types=[\"-obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def",
"= TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index()",
"real app, so we'll hack them on. \"\"\" # generate some data one_hour_ago",
"FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def",
"self.combos = list(itertools.combinations(words, 2)) self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two",
"+ self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self): content =",
"We need to let the index refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13)",
"= Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1)",
"self.assertEqual(q.count(), 6) q = Content.search_objects.search(before=timezone.now()) self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(),",
"plus the unpublished one q = Content.search_objects.search() self.assertEqual(q.count(), 12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(),",
"in q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): # We created one of each",
"self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result",
"app, so we'll hack them on. \"\"\" # generate some data one_hour_ago =",
"= TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2",
"6) for content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q = Content.search_objects.search(types=[\"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 6)",
"timezone from django.test.client import Client from django.template.defaultfilters import slugify from bulbs.content.models import Content,",
"self.assertEqual(q.count(), 12) q = Content.search_objects.search(status=\"draft\") self.assertEqual(q.count(), 1) def test_negative_filters(self): q = Content.search_objects.search(tags=[\"-spam\"]) self.assertEqual(q.count(),",
"with self.assertNumQueries(1 + self.num_subclasses): for content in Content.objects.all(): self.assertIsInstance(content, (TestContentObj, TestContentObjTwo)) def test_add_remove_tags(self):",
"Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()), original_tag_count + 1) self.assertEqual(len(content.tags.all()),",
"len(response.context['object_list']), len(self.combos) * self.num_subclasses) def test_num_polymorphic_queries(self): with self.assertNumQueries(1 + self.num_subclasses): for content in",
"- datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full() self.assertEqual(q.count(), 6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\",",
"[] for atom in combo: tag, created = Tag.objects.get_or_create(name=atom, slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj",
"q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertEqual(\"Obj one\", content.feature_type.name) q",
"results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result = results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self):",
"description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj = TestContentObj.objects.create( title=\"Unpublished",
"doctypes from installed apps, but in this case, our test models don't exist",
") obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago,",
"self.assertTrue(len(results) > 0) tag_result = results[0] self.assertIsInstance(tag_result, Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id",
"import Content, Tag, FeatureType from elastimorphic.tests.base import BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo",
"hack them on. \"\"\" # generate some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1)",
"\"Content\" class picks up available doctypes from installed apps, but in this case,",
"installed apps, but in this case, our test models don't exist in a",
"on. \"\"\" # generate some data one_hour_ago = timezone.now() - datetime.timedelta(hours=1) two_days_ago =",
"available doctypes from installed apps, but in this case, our test models don't",
"1) self.assertEqual(len(content.tags.all()), len(content.extract_document()['tags'])) def test_search_exact_name_tags(self): Tag.objects.create(name='Beeftank') Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0)",
"- datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q =",
"'.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title='",
"draft\", description=\"Just to throw a wrench\", foo=\"bar\", feature_type=ft_one ) # We need to",
"= list(itertools.combinations(words, 2)) self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj one\", slug=\"obj-one\") ft_two =",
"6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40))",
"6) q = Content.search_objects.search(types=[ \"testcontent_testcontentobjtwo\", \"testcontent_testcontentobj\"]) self.assertEqual(q.count(), 12) def test_status_filter(self): q = Content.search_objects.search(status=\"final\")",
"datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(days=40)) self.assertEqual(q.count(), 12) q = Content.search_objects.search(types=[\"testcontent_testcontentobjtwo\"]).full()",
"q.full(): self.assertNotEqual(\"Obj one\", content.feature_type.name) def test_content_subclasses(self): # We created one of each subclass",
"tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp() \"\"\" Normally, the",
"def test_add_remove_tags(self): content = Content.objects.all()[0] original_tag_count = len(content.tags.all()) new_tag = Tag.objects.create(name='crankdat') content.tags.add(new_tag) self.assertEqual(len(content.tags.all()),",
"Tag.search_objects.refresh() results = Tag.search_objects.query(name__match='beeftank').full() self.assertTrue(len(results) > 0) tag_result = results[0] self.assertIsInstance(tag_result, Tag) def",
"self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client = Client() response =",
"__future__ import absolute_import import itertools import datetime from django.utils import timezone from django.test.client",
"in content.tags.values_list(\"slug\", flat=True)) q = Content.search_objects.search(feature_types=[\"obj-one\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertEqual(\"Obj",
"self.num_subclasses = 2 self.combos = list(itertools.combinations(words, 2)) self.all_tags = [] ft_one = FeatureType.objects.create(name=\"Obj",
"TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12, plus the unpublished one",
"description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one ) obj.tags.add(*tags) obj.index() obj2 = TestContentObjTwo.objects.create( title=' '.join(reversed(combo)),",
"Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in q.full(): self.assertTrue(\"spam\"",
"description=\"Just to throw a wrench\", foo=\"bar\", feature_type=ft_one ) # We need to let",
"= Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content in q.full():",
"super(PolyContentTestCase, self).setUp() \"\"\" Normally, the \"Content\" class picks up available doctypes from installed",
"import timezone from django.test.client import Client from django.template.defaultfilters import slugify from bulbs.content.models import",
"two_days_ago = timezone.now() - datetime.timedelta(days=2) words = ['spam', 'driver', 'dump truck', 'restaurant'] self.num_subclasses",
"refresh TestContentObj.search_objects.refresh() TestContentObjTwo.search_objects.refresh() def test_filter_search_content(self): self.assertEqual(Content.objects.count(), 13) # The 12, plus the unpublished",
"Tag) def test_in_bulk_performs_polymorphic_query(self): content_ids = [c.id for c in Content.objects.all()] results = Content.objects.in_bulk(content_ids)",
"combination so the following should be true: self.assertEqual(Content.objects.count(), (len(self.combos) * self.num_subclasses) + 1)",
"= Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6)",
"models don't exist in a real app, so we'll hack them on. \"\"\"",
"import BaseIndexableTestCase from tests.testcontent.models import TestContentObj, TestContentObjTwo class PolyContentTestCase(BaseIndexableTestCase): def setUp(self): super(PolyContentTestCase, self).setUp()",
"one\", slug=\"obj-one\") ft_two = FeatureType.objects.create(name=\"Obj two\", slug=\"obj-two\") for i, combo in enumerate(self.combos): tags",
"slug=slugify(atom)) tags.append(tag) self.all_tags.append(tag) obj = TestContentObj.objects.create( title=' '.join(combo), description=' '.join(reversed(combo)), foo=combo[0], published=one_hour_ago, feature_type=ft_one",
"* self.num_subclasses) + 1) self.assertEqual(TestContentObj.objects.count(), len(self.combos) + 1) self.assertEqual(TestContentObjTwo.objects.count(), len(self.combos)) def test_content_list_view(self): client",
"title=' '.join(reversed(combo)), description=' '.join(combo), foo=combo[1], bar=i, published=two_days_ago, feature_type=ft_two ) obj2.tags.add(*tags) obj2.index() obj =",
"12) q = Content.search_objects.search(query=\"spam\") self.assertEqual(q.count(), 6) q = Content.search_objects.search(tags=[\"spam\"]) self.assertEqual(q.count(), 6) for content",
"self.assertEqual(q.count(), 12) q = Content.search_objects.search(before=timezone.now() - datetime.timedelta(hours=4)) self.assertEqual(q.count(), 6) q = Content.search_objects.search(after=timezone.now() -"
] |
[
"b = [], [] for item in seq: (a if condition(item) else b).append(item)",
"= [], [] for item in seq: (a if condition(item) else b).append(item) return",
"split_on_condition(seq, condition): a, b = [], [] for item in seq: (a if",
"def split_on_condition(seq, condition): a, b = [], [] for item in seq: (a",
"[] for item in seq: (a if condition(item) else b).append(item) return a, b",
"[], [] for item in seq: (a if condition(item) else b).append(item) return a,",
"<gh_stars>0 def split_on_condition(seq, condition): a, b = [], [] for item in seq:",
"a, b = [], [] for item in seq: (a if condition(item) else",
"condition): a, b = [], [] for item in seq: (a if condition(item)"
] |
[
"into mcbryde coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib import",
"received a copy of the GNU General Public License along with this program;",
"Floor, Boston, MA 02110-1301 USA \"\"\" class map(object): \"\"\" \"\"\" def __init__(self, observation,",
"check if sun is up if limitingMag.mean() < -9 : self.probMap = np.zeros(ligo.size)",
"5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting from distance to distance modulus dm_var =",
"scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is done in mapsAtTimeT.probabilityMaps",
"= \"kn-gaussian\" # LIGO O1 and O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO O3",
"that we can add guassians to get a gaussian. absMag_mean = self.absMagMean absMag_var",
"= self.absMagMean absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel == \"apparent\" :",
"\"dark\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma =",
"True) : import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi= \"\" # telescopeLimits",
"absolute magnitude # so that we can add guassians to get a gaussian.",
"self.modelAbsoluteMagnitudeSigma = 0 else : # this can be used to scale the",
"hourangle == False : xmin = obs.x.min(); xmax = obs.x.max() ymin = obs.y.min();",
"xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500) if type == \"ligo\" : probMap =",
"obs.map*self.probMap if hourangle == False : x = obs.x; y = obs.y else",
"== \"apparent\" : # implementing this in Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag",
"= obs.y else : x = obs.hx; y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi)",
"import scipy.stats import mags import hp2np import warnings license=\"\"\" Copyright (C) 2014 <NAME>",
"# telescopeLimits = self.limits limitingMag = self.limitingMag # check if sun is up",
"= obs.y.min(); ymax = obs.y.max() else : xmin = obs.hx.min(); xmax = obs.hx.max()",
"np import os import scipy.stats import mags import hp2np import warnings license=\"\"\" Copyright",
"if self.lumModel == \"apparent\" : # implementing this in Feb 2020 prob_map =",
"observation.pra self.pdec = observation.pdec self.precog = observation.precog # keep the answer self.probMap =",
"type == \"dark\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5",
"it down.) This program is distributed in the hope that it will be",
"& (limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting from",
"FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more",
"= ans[1] # calculate prob mag_min, mag_max = 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density,",
"* telescopeLimits self.probMap = prob_map return 1 # # This is a gaussian",
"np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var ) : #print m, mag_mean, mag_var",
"the magnitudes from the source model # this can be done as the",
"done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO O1 and O2 #self.modelAbsoluteMagnitude =",
"absMag_var + dm_var ic = 0 prob_map = np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0]",
"data around self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self, ligo,",
"import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi= \"\" # telescopeLimits = self.limits",
"= 0.5 else : # we can't afford to do every pixel. #",
"pix in np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var = ap_mag_var[ic] # Now we",
"= obs.x.max() ymin = obs.y.min(); ymax = obs.y.max() else : xmin = obs.hx.min();",
"x = obs.hx; y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi =",
"brings the number of pixels # down from 196,608 to 10^4 ix =",
"= -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else : raise Exception ( \"only trigger types",
"+= 1 print \"\\t probMap: made for source absMag {:.1f}\".format(absMag_mean) # probability of",
"or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for",
"r^2 (itself # trasformed into a distance modulus (i.e. magnitude) # # Now",
"to 10^4 ix = (ligo_spatial > 1e-8) & (ligo_d_mean > 0) & (limitingMag",
"= \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else : raise Exception (",
"should have received a copy of the GNU General Public License along with",
"ligo_distance_sigma, verbose = True) : import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi=",
"this is done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO O1 and O2",
"and/or modify it under the terms of version 3 of the GNU General",
"to assuming we are going # to renormalize by integrating from 0 to",
"General Public License for more details. You should have received a copy of",
"= 0 else : # this can be used to scale the magnitudes",
"\",type if hourangle == False : xmin = obs.x.min(); xmax = obs.x.max() ymin",
"import os import scipy.stats import mags import hp2np import warnings license=\"\"\" Copyright (C)",
"not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,",
"Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA",
"map(object): \"\"\" \"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir =",
"= observation.precog # keep the answer self.probMap = \"\" # for plotting contours,",
"self.probMap = \"\" # for plotting contours, keep the intermediate data around self.xi,",
"\"apparent\" : # implementing this in Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag =",
"probability per unit volume # We will also drop constants, equivalent to assuming",
"is free software; you can redistribute it and/or modify it under the terms",
"else : xmin = obs.hx.min(); xmax = obs.hx.max() ymin = obs.hy.min(); ymax =",
"absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel == \"apparent\"",
"self.yi, self.zi = xi,yi,zi self.lastCtype = type if not whiteLine : plt.contour(self.xi,self.yi,self.zi,con_levels,linewidths=3,colors=\"k\") plt.contour(self.xi,self.yi,self.zi,con_levels,linewidths=0.66,colors=\"w\")",
"it and/or modify it under the terms of version 3 of the GNU",
"More to the points- this code is science code: buggy, barely working, with",
"contours # or the ligo*obs_prob contours # type=\"ligo\" type=\"ls\" # houranlge chooses HA",
"196,608 to 10^4 ix = (ligo_spatial > 1e-8) & (ligo_d_mean > 0) &",
"= ligo_distance_sigma**2 # we are going to change variables to distance modulus (magnitude),",
"but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS",
"the source abs magnitude for calculations # is taken from self.absMagMean, self.absMagSigma #",
"\"bright\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma =",
"= 0 prob_map = np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] : mag = ap_mag_mean[ic]",
"r^2 dr , thus assuming equal probability per unit volume # We will",
"also drop constants, equivalent to assuming we are going # to renormalize by",
"that it will be useful, but WITHOUT ANY WARRANTY; without even the implied",
": x = obs.hx; y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi",
"point prob_map = prob_map * telescopeLimits self.probMap = prob_map return 1 # #",
"type == \"ls\" : probMap = obs.map*self.probMap if hourangle == False : x",
"Foundation. More to the points- this code is science code: buggy, barely working,",
"houranlge chooses HA instead of RA projected into mcbryde coords def plotLigoContours(self, obs,",
"var = ap_mag_var[ic] # Now we weight by r^2 dr , thus assuming",
"__init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim",
"propgation on converting from distance to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume",
"True if type == \"bright\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude",
"mag_var ) : #print m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m",
"#self.modelAbsoluteMagnitude = -11.1 # LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif",
"# # This is a gaussian in apparent magnitude, weighted by r^2 (itself",
"apparent_mag = absMag_mean ix, = np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0 ix, =",
"the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301",
"in the the alpine fast & light style. (Note the rate at which",
"= np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, = np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0",
"obs.hx; y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype",
"# check if sun is up if limitingMag.mean() < -9 : self.probMap =",
"prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, = np.where(apparent_mag < limitingMag) prob_map[ix] =",
"= obs.hx.min(); xmax = obs.hx.max() ymin = obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax,",
"USA \"\"\" class map(object): \"\"\" \"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\"",
"21.5 self.modelAbsoluteMagnitudeSigma = 0 else : # fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude",
"implementing this in Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, =",
"= prob/norm prob_map[pix] = prob ic += 1 print \"\\t probMap: made for",
"FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.",
"ans[0]; prob_error = ans[1] prob = prob/norm prob_map[pix] = prob ic += 1",
") : #print m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean))",
"is taken from self.absMagMean, self.absMagSigma # whereas we're setting the absolute scale here",
"+ absMag_mean ap_mag_var = absMag_var + dm_var ic = 0 prob_map = np.copy(ligo_spatial)*0.0",
"to plot the ligo contours # or the ligo*obs_prob contours # type=\"ligo\" type=\"ls\"",
"we weight by r^2 dr , thus assuming equal probability per unit volume",
"assume gaussians, so adding gaussians to get a gaussian ap_mag_mean = distance_mod +",
"apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else : # this can be used to scale",
"limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5 else : # we can't",
"# to renormalize by integrating from 0 to infinity # normalize norm_min, norm_max",
"magnitude # so that we can add guassians to get a gaussian. absMag_mean",
"warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General",
"25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var ) ) norm",
"if type == \"ligo\" : probMap = obs.map if type == \"ls\" :",
"# We will also drop constants, equivalent to assuming we are going #",
"# This is a gaussian in apparent magnitude, weighted by r^2 (itself #",
"in absolute magnitude # so that we can add guassians to get a",
"# one can choose to plot the ligo contours # or the ligo*obs_prob",
"False : xmin = obs.x.min(); xmax = obs.x.max() ymin = obs.y.min(); ymax =",
"dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding gaussians to get a gaussian",
"tryApparent = True if type == \"bright\" : if tryApparent : self.lumModel =",
"norm_max = 7.0, 25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var",
"\"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose = True) : import scipy.integrate warnings.filterwarnings(\"ignore\")",
"= np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0 ix, = np.where((apparent_mag >= limitingMag) &",
"prob = ans[0]; prob_error = ans[1] prob = prob/norm prob_map[pix] = prob ic",
"adding gaussians to get a gaussian ap_mag_mean = distance_mod + absMag_mean ap_mag_var =",
"= observation.limits tryApparent = True if type == \"bright\" : if tryApparent :",
"will also drop constants, equivalent to assuming we are going # to renormalize",
"by r^2 dr , thus assuming equal probability per unit volume # probability_density",
"style. (Note the rate at which people who stand on the summit of",
"# we can't afford to do every pixel. # for res= 128, a",
"else : # this can be used to scale the magnitudes from the",
"02110-1301 USA \"\"\" class map(object): \"\"\" \"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) :",
"observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits",
"down.) This program is distributed in the hope that it will be useful,",
"var ) ) norm = ans[0]; norm_error = ans[1] # calculate prob mag_min,",
"This program is free software; you can redistribute it and/or modify it under",
"= 1.0 else : raise Exception ( \"only trigger types known are bright",
"prob_map * telescopeLimits self.probMap = prob_map return 1 # # This is a",
"or no documentation. Science code in the the alpine fast & light style.",
"is a gaussian in apparent magnitude, weighted by r^2 (itself # trasformed into",
"copy of the GNU General Public License along with this program; if not,",
": xmin = obs.x.min(); xmax = obs.x.max() ymin = obs.y.min(); ymax = obs.y.max()",
"PURPOSE. See the GNU General Public License for more details. You should have",
"obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype = type if",
"hp2np import warnings license=\"\"\" Copyright (C) 2014 <NAME> This program is free software;",
"self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else : raise Exception ( \"only trigger",
"= prob_map * self.precog # finally, eliminate every where the telescope cannot point",
"obs.x.min(); xmax = obs.x.max() ymin = obs.y.min(); ymax = obs.y.max() else : xmin",
"as the source abs magnitude for calculations # is taken from self.absMagMean, self.absMagSigma",
"from 196,608 to 10^4 ix = (ligo_spatial > 1e-8) & (ligo_d_mean > 0)",
"dr , thus assuming equal probability per unit volume # probability_density = np.exp(",
"xmax = obs.x.max() ymin = obs.y.min(); ymax = obs.y.max() else : xmin =",
"version 3 of the GNU General Public License as published by the Free",
"else : raise Exception ( \"only trigger types known are bright and dark,",
"of pixels # down from 196,608 to 10^4 ix = (ligo_spatial > 1e-8)",
"obs.map if type == \"ls\" : probMap = obs.map*self.probMap if hourangle == False",
"= ans[0]; norm_error = ans[1] # calculate prob mag_min, mag_max = 7.0, limitingMag[pix]",
"so adding gaussians to get a gaussian ap_mag_mean = distance_mod + absMag_mean ap_mag_var",
"= (ligo_spatial > 1e-8) & (ligo_d_mean > 0) & (limitingMag > 0) distance_mod",
"np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0 ix, = np.where((apparent_mag >= limitingMag) & (apparent_mag",
"Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\" class map(object): \"\"\" \"\"\"",
"equal probability per unit volume # We will also drop constants, equivalent to",
"args=(mag, var ) ) norm = ans[0]; norm_error = ans[1] # calculate prob",
"if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else",
"so that we can add guassians to get a gaussian. absMag_mean = self.absMagMean",
"else : # fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma =",
"= obs.y.max() else : xmin = obs.hx.min(); xmax = obs.hx.max() ymin = obs.hy.min();",
"make it down.) This program is distributed in the hope that it will",
"= np.where((apparent_mag >= limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5 else :",
"ligo, ligo_distance, ligo_distance_sigma, verbose = True) : import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for",
"as published by the Free Software Foundation. More to the points- this code",
"print \"\\t calculating contours for type = \",type if hourangle == False :",
"np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one can choose to",
"choose to plot the ligo contours # or the ligo*obs_prob contours # type=\"ligo\"",
"is gaussian in DM and in absolute magnitude # so that we can",
"xmin = obs.x.min(); xmax = obs.x.max() ymin = obs.y.min(); ymax = obs.y.max() else",
"P_recognition self.pra = observation.pra self.pdec = observation.pdec self.precog = observation.precog # keep the",
"self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra = observation.pra self.pdec = observation.pdec",
"if sun is up if limitingMag.mean() < -9 : self.probMap = np.zeros(ligo.size) return",
"ans[0]; norm_error = ans[1] # calculate prob mag_min, mag_max = 7.0, limitingMag[pix] ans",
"{:.1f}\".format(absMag_mean) # probability of recognition propto star density prob_map = prob_map * self.precog",
"trasformed into a distance modulus (i.e. magnitude) # # Now we weight by",
"of the GNU General Public License along with this program; if not, write",
"from distance to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding",
"np.zeros(ligo.size) return 0 # realwork ligo_spatial = ligo ligo_d_mean = ligo_distance ligo_d_var =",
"* self.precog # finally, eliminate every where the telescope cannot point prob_map =",
": x = obs.x; y = obs.y else : x = obs.hx; y",
"can add guassians to get a gaussian. absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2",
"self.zi == \"\" or self.lastCtype != type: print \"\\t calculating contours for type",
"zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype = type if not",
": # this can be used to scale the magnitudes from the source",
"for source absMag {:.1f}\".format(absMag_mean) # probability of recognition propto star density prob_map =",
"# probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean))",
"and O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma =",
"mag = ap_mag_mean[ic] var = ap_mag_var[ic] # Now we weight by r^2 dr",
"probability per unit volume # probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\",
"self.limits limitingMag = self.limitingMag # check if sun is up if limitingMag.mean() <",
"ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2 # we are going to change variables",
"ymax, 500) if type == \"ligo\" : probMap = obs.map if type ==",
"# down from 196,608 to 10^4 ix = (ligo_spatial > 1e-8) & (ligo_d_mean",
"normalize norm_min, norm_max = 7.0, 25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max,",
"mag_mean, mag_var ) : #print m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\",
"Fifth Floor, Boston, MA 02110-1301 USA \"\"\" class map(object): \"\"\" \"\"\" def __init__(self,",
"r^2 dr , thus assuming equal probability per unit volume # probability_density =",
"ix = (ligo_spatial > 1e-8) & (ligo_d_mean > 0) & (limitingMag > 0)",
"= apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else : # this can be used to",
"= ligo_d_var.sum() if self.lumModel == \"apparent\" : # implementing this in Feb 2020",
"to distance modulus (magnitude), # then, assume error is gaussian in DM and",
"self.lastCtype != type: print \"\\t calculating contours for type = \",type if hourangle",
"apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits = observation.limits",
"# or the ligo*obs_prob contours # type=\"ligo\" type=\"ls\" # houranlge chooses HA instead",
"mag_min, mag_max = 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var )",
"gaussians to get a gaussian ap_mag_mean = distance_mod + absMag_mean ap_mag_var = absMag_var",
"return 0 # realwork ligo_spatial = ligo ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2",
"Boston, MA 02110-1301 USA \"\"\" class map(object): \"\"\" \"\"\" def __init__(self, observation, type=\"bright\",",
"code in the the alpine fast & light style. (Note the rate at",
"is up if limitingMag.mean() < -9 : self.probMap = np.zeros(ligo.size) return 0 #",
") ) prob = ans[0]; prob_error = ans[1] prob = prob/norm prob_map[pix] =",
"for more details. You should have received a copy of the GNU General",
"\"\"\" class map(object): \"\"\" \"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\"",
"self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose =",
"Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\"",
"on converting from distance to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians,",
"ap_mag_mean = distance_mod + absMag_mean ap_mag_var = absMag_var + dm_var ic = 0",
"Now we weight by r^2 dr , thus assuming equal probability per unit",
"magnitude) # # Now we weight by r^2 dr , thus assuming equal",
"points- this code is science code: buggy, barely working, with little or no",
"code is science code: buggy, barely working, with little or no documentation. Science",
"in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO O1 and O2 #self.modelAbsoluteMagnitude = -11.1",
"# we are going to change variables to distance modulus (magnitude), # then,",
"the GNU General Public License along with this program; if not, write to",
"made for source absMag {:.1f}\".format(absMag_mean) # probability of recognition propto star density prob_map",
"MA 02110-1301 USA \"\"\" class map(object): \"\"\" \"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5)",
"ic = 0 prob_map = np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] : mag =",
"prob_map = prob_map * self.precog # finally, eliminate every where the telescope cannot",
"a gaussian in apparent magnitude, weighted by r^2 (itself # trasformed into a",
"the terms of version 3 of the GNU General Public License as published",
"(ligo_spatial > 1e-8) & (ligo_d_mean > 0) & (limitingMag > 0) distance_mod =",
"calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose = True) : import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping",
"-(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one can choose to plot",
"cut at > 1e-8 brings the number of pixels # down from 196,608",
"raise Exception ( \"only trigger types known are bright and dark, not {}\".format(type))",
"self.lastCtype = \"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose = True) : import",
"propto star density prob_map = prob_map * self.precog # finally, eliminate every where",
"alpine fast & light style. (Note the rate at which people who stand",
"fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else :",
", thus assuming equal probability per unit volume # We will also drop",
"& light style. (Note the rate at which people who stand on the",
"128, a cut at > 1e-8 brings the number of pixels # down",
"the summit of K2 successfully make it down.) This program is distributed in",
"obs.y else : x = obs.hx; y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi,",
": # we can't afford to do every pixel. # for res= 128,",
"probMap = obs.map*self.probMap if hourangle == False : x = obs.x; y =",
"= obs.hx; y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi",
"successfully make it down.) This program is distributed in the hope that it",
"buggy, barely working, with little or no documentation. Science code in the the",
"See the GNU General Public License for more details. You should have received",
"code: buggy, barely working, with little or no documentation. Science code in the",
"assuming we are going # to renormalize by integrating from 0 to infinity",
"this can be done as the source abs magnitude for calculations # is",
"ligo_distance, ligo_distance_sigma, verbose = True) : import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting",
"\"ligo\" : probMap = obs.map if type == \"ls\" : probMap = obs.map*self.probMap",
"are bright and dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma #",
"magnitudes from the source model # this can be done as the source",
"ligo contours # or the ligo*obs_prob contours # type=\"ligo\" type=\"ls\" # houranlge chooses",
"xmin = obs.hx.min(); xmax = obs.hx.max() ymin = obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin,",
"self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" #",
"= self.limits limitingMag = self.limitingMag # check if sun is up if limitingMag.mean()",
"def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib import matplotlib.pyplot as plt",
"in np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var = ap_mag_var[ic] # Now we weight",
"you can redistribute it and/or modify it under the terms of version 3",
"limitingMag) prob_map[ix] = 1.0 ix, = np.where((apparent_mag >= limitingMag) & (apparent_mag < limitingMag+0.5))",
"it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty",
"get a gaussian. absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum() if",
"scale the magnitudes from the source model # this can be done as",
"Exception ( \"only trigger types known are bright and dark, not {}\".format(type)) self.absMagMean",
"we are going to change variables to distance modulus (magnitude), # then, assume",
"program is free software; you can redistribute it and/or modify it under the",
"can't afford to do every pixel. # for res= 128, a cut at",
"# type=\"ligo\" type=\"ls\" # houranlge chooses HA instead of RA projected into mcbryde",
"np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var = ap_mag_var[ic] #",
"np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var = ap_mag_var[ic] # Now we weight by",
": probMap = obs.map if type == \"ls\" : probMap = obs.map*self.probMap if",
"without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"absMag_mean ix, = np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0 ix, = np.where((apparent_mag >=",
"little or no documentation. Science code in the the alpine fast & light",
"mag_max = 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var ) )",
"source model # this can be done as the source abs magnitude for",
"barely working, with little or no documentation. Science code in the the alpine",
"error propgation on converting from distance to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) #",
"prob_map[ix] = 0.5 else : # we can't afford to do every pixel.",
"> 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting from distance to",
"matplotlib import matplotlib.pyplot as plt con_levels=10 if self.zi == \"\" or self.lastCtype !=",
"= 0 else : # fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0",
"scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi= \"\" # telescopeLimits = self.limits limitingMag",
"-9 : self.probMap = np.zeros(ligo.size) return 0 # realwork ligo_spatial = ligo ligo_d_mean",
": if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0",
"# np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var ) : #print m, mag_mean,",
"self.modelAbsoluteMagnitudeSigma # Currently this is done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO",
"self.modelAbsoluteMagnitudeSigma = 1.0 elif type == \"dark\" : if tryApparent : self.lumModel =",
"K2 successfully make it down.) This program is distributed in the hope that",
"== \"ls\" : probMap = obs.map*self.probMap if hourangle == False : x =",
"LIGO O1 and O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO O3 self.modelAbsoluteMagnitude = -15.5",
"for pix in np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var = ap_mag_var[ic] # Now",
"self.modelAbsoluteMagnitudeSigma = 0 else : # fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude =",
"plt con_levels=10 if self.zi == \"\" or self.lastCtype != type: print \"\\t calculating",
"distance_mod + absMag_mean ap_mag_var = absMag_var + dm_var ic = 0 prob_map =",
"y = obs.y else : x = obs.hx; y = obs.hy zi =",
"WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else : raise",
"whereas we're setting the absolute scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently",
"= prob_map return 1 # # This is a gaussian in apparent magnitude,",
"to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding gaussians to",
"\"\\t probMap: made for source absMag {:.1f}\".format(absMag_mean) # probability of recognition propto star",
"m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd #",
"hourangle=False) : import matplotlib import matplotlib.pyplot as plt con_levels=10 if self.zi == \"\"",
"norm = ans[0]; norm_error = ans[1] # calculate prob mag_min, mag_max = 7.0,",
"type=\"ls\" # houranlge chooses HA instead of RA projected into mcbryde coords def",
"mag_max, args=(mag, var ) ) prob = ans[0]; prob_error = ans[1] prob =",
"afford to do every pixel. # for res= 128, a cut at >",
"light style. (Note the rate at which people who stand on the summit",
"the the alpine fast & light style. (Note the rate at which people",
"= \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0 else : # fixed luminosity",
"ap_mag_var[ic] # Now we weight by r^2 dr , thus assuming equal probability",
"self.modelAbsoluteMagnitudeSigma = 1.0 else : raise Exception ( \"only trigger types known are",
"2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, = np.where(apparent_mag < limitingMag) prob_map[ix]",
"this in Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, = np.where(apparent_mag",
"abs magnitude for calculations # is taken from self.absMagMean, self.absMagSigma # whereas we're",
"1.0 ix, = np.where((apparent_mag >= limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5",
"self.probMap = prob_map return 1 # # This is a gaussian in apparent",
"every pixel. # for res= 128, a cut at > 1e-8 brings the",
"prob_error = ans[1] prob = prob/norm prob_map[pix] = prob ic += 1 print",
"limitingMag.mean() < -9 : self.probMap = np.zeros(ligo.size) return 0 # realwork ligo_spatial =",
"Public License as published by the Free Software Foundation. More to the points-",
"type == \"ligo\" : probMap = obs.map if type == \"ls\" : probMap",
"if type == \"bright\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude =",
"the hope that it will be useful, but WITHOUT ANY WARRANTY; without even",
"will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of",
"= obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500) if type == \"ligo\" :",
"realwork ligo_spatial = ligo ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2 # we are",
"# assume gaussians, so adding gaussians to get a gaussian ap_mag_mean = distance_mod",
"1 # # This is a gaussian in apparent magnitude, weighted by r^2",
": xmin = obs.hx.min(); xmax = obs.hx.max() ymin = obs.hy.min(); ymax = obs.y.max()",
"# self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\"",
"per unit volume # probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\ #",
"are going # to renormalize by integrating from 0 to infinity # normalize",
"7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var ) ) prob =",
"the telescope cannot point prob_map = prob_map * telescopeLimits self.probMap = prob_map return",
"\"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag",
"= self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel == \"apparent\" : # implementing this",
"observation.limits tryApparent = True if type == \"bright\" : if tryApparent : self.lumModel",
"= self.limitingMag # check if sun is up if limitingMag.mean() < -9 :",
"matplotlib.pyplot as plt con_levels=10 if self.zi == \"\" or self.lastCtype != type: print",
"documentation. Science code in the the alpine fast & light style. (Note the",
"license=\"\"\" Copyright (C) 2014 <NAME> This program is free software; you can redistribute",
"apparent magnitude, weighted by r^2 (itself # trasformed into a distance modulus (i.e.",
"obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib import matplotlib.pyplot as plt con_levels=10 if",
"get the P_recognition self.pra = observation.pra self.pdec = observation.pdec self.precog = observation.precog #",
"the source model # this can be done as the source abs magnitude",
"var ) ) prob = ans[0]; prob_error = ans[1] prob = prob/norm prob_map[pix]",
"\"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else : raise Exception ( \"only",
"variables to distance modulus (magnitude), # then, assume error is gaussian in DM",
"mcbryde coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib import matplotlib.pyplot",
"# whereas we're setting the absolute scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma #",
"norm_max, args=(mag, var ) ) norm = ans[0]; norm_error = ans[1] # calculate",
"#print m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd",
"self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type == \"dark\" : if tryApparent",
"> 1e-8) & (ligo_d_mean > 0) & (limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.)",
"1e-8 brings the number of pixels # down from 196,608 to 10^4 ix",
"ans[1] # calculate prob mag_min, mag_max = 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min,",
": self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else : #",
"weight by r^2 dr , thus assuming equal probability per unit volume #",
"assuming equal probability per unit volume # We will also drop constants, equivalent",
"mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one",
"into a distance modulus (i.e. magnitude) # # Now we weight by r^2",
"of version 3 of the GNU General Public License as published by the",
"thus assuming equal probability per unit volume # We will also drop constants,",
"of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public",
"ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500) if type == \"ligo\"",
"observation.pdec self.precog = observation.precog # keep the answer self.probMap = \"\" # for",
"modulus (i.e. magnitude) # # Now we weight by r^2 dr , thus",
"by the Free Software Foundation. More to the points- this code is science",
"Public License along with this program; if not, write to the Free Software",
"if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0 else",
"going to change variables to distance modulus (magnitude), # then, assume error is",
"GNU General Public License along with this program; if not, write to the",
"\"\" # telescopeLimits = self.limits limitingMag = self.limitingMag # check if sun is",
"# keep the answer self.probMap = \"\" # for plotting contours, keep the",
"= ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding gaussians to get a gaussian ap_mag_mean",
"dr , thus assuming equal probability per unit volume # We will also",
"= 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var ) ) prob",
"program is distributed in the hope that it will be useful, but WITHOUT",
"1.0 elif type == \"dark\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude",
"1 print \"\\t probMap: made for source absMag {:.1f}\".format(absMag_mean) # probability of recognition",
"xmax, 500) yi=np.linspace(ymin, ymax, 500) if type == \"ligo\" : probMap = obs.map",
"probMap = obs.map if type == \"ls\" : probMap = obs.map*self.probMap if hourangle",
"by integrating from 0 to infinity # normalize norm_min, norm_max = 7.0, 25.0",
"mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO O1 and O2 #self.modelAbsoluteMagnitude = -11.1 #",
"gaussian in apparent magnitude, weighted by r^2 (itself # trasformed into a distance",
"(magnitude), # then, assume error is gaussian in DM and in absolute magnitude",
"to renormalize by integrating from 0 to infinity # normalize norm_min, norm_max =",
"obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500) if type == \"ligo\" : probMap",
"the rate at which people who stand on the summit of K2 successfully",
"self.absMagMean absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel == \"apparent\" : #",
"O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type == \"dark\" : if",
"number of pixels # down from 196,608 to 10^4 ix = (ligo_spatial >",
"0 else : # this can be used to scale the magnitudes from",
"# is taken from self.absMagMean, self.absMagSigma # whereas we're setting the absolute scale",
"dm_var ic = 0 prob_map = np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] : mag",
"prob = prob/norm prob_map[pix] = prob ic += 1 print \"\\t probMap: made",
": import matplotlib import matplotlib.pyplot as plt con_levels=10 if self.zi == \"\" or",
"ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var ) : #print m, mag_mean, mag_var pd= np.exp(",
"0) & (limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting",
"self.pdec = observation.pdec self.precog = observation.precog # keep the answer self.probMap = \"\"",
"3 of the GNU General Public License as published by the Free Software",
"telescopeLimits = self.limits limitingMag = self.limitingMag # check if sun is up if",
"obs.hx.min(); xmax = obs.hx.max() ymin = obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500)",
"0 # realwork ligo_spatial = ligo ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2 #",
"are going to change variables to distance modulus (magnitude), # then, assume error",
"plotting contours, keep the intermediate data around self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype",
"is done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO O1 and O2 #self.modelAbsoluteMagnitude",
"self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra = observation.pra self.pdec =",
"mag_min, mag_max, args=(mag, var ) ) prob = ans[0]; prob_error = ans[1] prob",
"thus assuming equal probability per unit volume # probability_density = np.exp( (m -",
"matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype = type if not whiteLine :",
"plotting self.zi= \"\" # telescopeLimits = self.limits limitingMag = self.limitingMag # check if",
"self.probMap = np.zeros(ligo.size) return 0 # realwork ligo_spatial = ligo ligo_d_mean = ligo_distance",
"obs.y.min(); ymax = obs.y.max() else : xmin = obs.hx.min(); xmax = obs.hx.max() ymin",
"= matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype = type if not whiteLine",
"stand on the summit of K2 successfully make it down.) This program is",
"= self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra = observation.pra self.pdec = observation.pdec self.precog",
"(apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5 else : # we can't afford to",
"to the points- this code is science code: buggy, barely working, with little",
"be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY",
"self.zi= \"\" # telescopeLimits = self.limits limitingMag = self.limitingMag # check if sun",
"# realwork ligo_spatial = ligo ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2 # we",
"where the telescope cannot point prob_map = prob_map * telescopeLimits self.probMap = prob_map",
"for res= 128, a cut at > 1e-8 brings the number of pixels",
"probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def",
"type=\"ligo\" type=\"ls\" # houranlge chooses HA instead of RA projected into mcbryde coords",
"data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits = observation.limits tryApparent = True if",
"def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag =",
"working, with little or no documentation. Science code in the the alpine fast",
"ligo_distance_sigma**2 # we are going to change variables to distance modulus (magnitude), #",
"(C) 2014 <NAME> This program is free software; you can redistribute it and/or",
"hourangle == False : x = obs.x; y = obs.y else : x",
"Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\" class map(object):",
"prob_map[pix] = prob ic += 1 print \"\\t probMap: made for source absMag",
"cannot point prob_map = prob_map * telescopeLimits self.probMap = prob_map return 1 #",
"absolute scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is done in",
"the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"absMag {:.1f}\".format(absMag_mean) # probability of recognition propto star density prob_map = prob_map *",
"if type == \"ls\" : probMap = obs.map*self.probMap if hourangle == False :",
"& (apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5 else : # we can't afford",
"ligo*obs_prob contours # type=\"ligo\" type=\"ls\" # houranlge chooses HA instead of RA projected",
"summit of K2 successfully make it down.) This program is distributed in the",
"( \"only trigger types known are bright and dark, not {}\".format(type)) self.absMagMean =",
", thus assuming equal probability per unit volume # probability_density = np.exp( (m",
"# get the P_recognition self.pra = observation.pra self.pdec = observation.pdec self.precog = observation.precog",
"by r^2 dr , thus assuming equal probability per unit volume # We",
"> 1e-8 brings the number of pixels # down from 196,608 to 10^4",
"ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var ) ) prob = ans[0]; prob_error",
"# normalize norm_min, norm_max = 7.0, 25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min,",
"keep the intermediate data around self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\"",
"equivalent to assuming we are going # to renormalize by integrating from 0",
"# LIGO O1 and O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO O3 self.modelAbsoluteMagnitude =",
"51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\" class map(object): \"\"\"",
"= ligo ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2 # we are going to",
"norm_error = ans[1] # calculate prob mag_min, mag_max = 7.0, limitingMag[pix] ans =",
"from self.absMagMean, self.absMagSigma # whereas we're setting the absolute scale here with #",
": #print m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return",
": \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits = observation.limits tryApparent",
"\\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var ) : #print m,",
"This program is distributed in the hope that it will be useful, but",
"absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel == \"apparent\" : # implementing",
"warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi= \"\" # telescopeLimits = self.limits limitingMag =",
"= ans[0]; prob_error = ans[1] prob = prob/norm prob_map[pix] = prob ic +=",
"taken from self.absMagMean, self.absMagSigma # whereas we're setting the absolute scale here with",
"in DM and in absolute magnitude # so that we can add guassians",
"type: print \"\\t calculating contours for type = \",type if hourangle == False",
"assuming equal probability per unit volume # probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var)",
"along with this program; if not, write to the Free Software Foundation, Inc.,",
"a copy of the GNU General Public License along with this program; if",
"= os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits = observation.limits tryApparent = True if type",
"-25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else : raise Exception ( \"only trigger types known",
"coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib import matplotlib.pyplot as",
"= obs.map if type == \"ls\" : probMap = obs.map*self.probMap if hourangle ==",
"= 1.0 ix, = np.where((apparent_mag >= limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix] =",
"Free Software Foundation. More to the points- this code is science code: buggy,",
"= np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var = ap_mag_var[ic]",
"License as published by the Free Software Foundation. More to the points- this",
"can be done as the source abs magnitude for calculations # is taken",
"# error propgation on converting from distance to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix])",
"O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0",
"ligo_d_var.sum() if self.lumModel == \"apparent\" : # implementing this in Feb 2020 prob_map",
"args=(mag, var ) ) prob = ans[0]; prob_error = ans[1] prob = prob/norm",
"= obs.hx.max() ymin = obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax,",
"per unit volume # We will also drop constants, equivalent to assuming we",
"Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\" class",
"source abs magnitude for calculations # is taken from self.absMagMean, self.absMagSigma # whereas",
"> 0) & (limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on",
"can be used to scale the magnitudes from the source model # this",
"License for more details. You should have received a copy of the GNU",
"import matplotlib.pyplot as plt con_levels=10 if self.zi == \"\" or self.lastCtype != type:",
"= obs.x.min(); xmax = obs.x.max() ymin = obs.y.min(); ymax = obs.y.max() else :",
"== \"ligo\" : probMap = obs.map if type == \"ls\" : probMap =",
"= 1.0 elif type == \"dark\" : if tryApparent : self.lumModel = \"apparent\"",
"# then, assume error is gaussian in DM and in absolute magnitude #",
"10^4 ix = (ligo_spatial > 1e-8) & (ligo_d_mean > 0) & (limitingMag >",
"distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting from distance to distance modulus",
"== False : x = obs.x; y = obs.y else : x =",
"observation.precog # keep the answer self.probMap = \"\" # for plotting contours, keep",
"volume # We will also drop constants, equivalent to assuming we are going",
"volume # probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m -",
"False : x = obs.x; y = obs.y else : x = obs.hx;",
"\\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one can choose to plot the ligo",
"import matplotlib import matplotlib.pyplot as plt con_levels=10 if self.zi == \"\" or self.lastCtype",
"General Public License along with this program; if not, write to the Free",
"details. You should have received a copy of the GNU General Public License",
"= observation.pra self.pdec = observation.pdec self.precog = observation.precog # keep the answer self.probMap",
"do every pixel. # for res= 128, a cut at > 1e-8 brings",
"= prob ic += 1 print \"\\t probMap: made for source absMag {:.1f}\".format(absMag_mean)",
"(i.e. magnitude) # # Now we weight by r^2 dr , thus assuming",
"if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth",
"and dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the",
"redistribute it and/or modify it under the terms of version 3 of the",
"\"\" # for plotting contours, keep the intermediate data around self.xi, self.yi, self.zi",
"# implementing this in Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix,",
"if self.zi == \"\" or self.lastCtype != type: print \"\\t calculating contours for",
"\"only trigger types known are bright and dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude",
"as plt con_levels=10 if self.zi == \"\" or self.lastCtype != type: print \"\\t",
"tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0 else :",
"prob_map return 1 # # This is a gaussian in apparent magnitude, weighted",
"plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib import matplotlib.pyplot as plt con_levels=10",
"for plotting contours, keep the intermediate data around self.xi, self.yi, self.zi = [\"\",\"\",\"\"]",
"St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\" class map(object): \"\"\" \"\"\" def",
") prob = ans[0]; prob_error = ans[1] prob = prob/norm prob_map[pix] = prob",
"people who stand on the summit of K2 successfully make it down.) This",
"\"\" or self.lastCtype != type: print \"\\t calculating contours for type = \",type",
"here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is done in mapsAtTimeT.probabilityMaps self.lumModel",
"distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;",
"GNU General Public License for more details. You should have received a copy",
"plot the ligo contours # or the ligo*obs_prob contours # type=\"ligo\" type=\"ls\" #",
"obs.x.max() ymin = obs.y.min(); ymax = obs.y.max() else : xmin = obs.hx.min(); xmax",
"= \"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose = True) : import scipy.integrate",
"from 0 to infinity # normalize norm_min, norm_max = 7.0, 25.0 # magnitudes",
"pixel. # for res= 128, a cut at > 1e-8 brings the number",
"= True) : import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi= \"\" #",
"WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR",
"& (ligo_d_mean > 0) & (limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error",
"Currently this is done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO O1 and",
": import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi= \"\" # telescopeLimits =",
"-15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type == \"dark\" : if tryApparent : self.lumModel",
"# magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var ) ) norm =",
"= np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m,",
"= 7.0, 25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var )",
": mag = ap_mag_mean[ic] var = ap_mag_var[ic] # Now we weight by r^2",
"< -9 : self.probMap = np.zeros(ligo.size) return 0 # realwork ligo_spatial = ligo",
"a distance modulus (i.e. magnitude) # # Now we weight by r^2 dr",
"norm_min, norm_max, args=(mag, var ) ) norm = ans[0]; norm_error = ans[1] #",
"O1 and O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma",
"= \"\" # for plotting contours, keep the intermediate data around self.xi, self.yi,",
"return pd # one can choose to plot the ligo contours # or",
">= limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5 else : # we",
"xmax = obs.hx.max() ymin = obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin,",
"contours # type=\"ligo\" type=\"ls\" # houranlge chooses HA instead of RA projected into",
"at > 1e-8 brings the number of pixels # down from 196,608 to",
"{}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra =",
"warnings license=\"\"\" Copyright (C) 2014 <NAME> This program is free software; you can",
"prob/norm prob_map[pix] = prob ic += 1 print \"\\t probMap: made for source",
"< limitingMag+0.5)) prob_map[ix] = 0.5 else : # we can't afford to do",
"a cut at > 1e-8 brings the number of pixels # down from",
"distance to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding gaussians",
"probMap: made for source absMag {:.1f}\".format(absMag_mean) # probability of recognition propto star density",
"magnitude for calculations # is taken from self.absMagMean, self.absMagSigma # whereas we're setting",
"by r^2 (itself # trasformed into a distance modulus (i.e. magnitude) # #",
"ligo_distance ligo_d_var = ligo_distance_sigma**2 # we are going to change variables to distance",
"distance modulus (magnitude), # then, assume error is gaussian in DM and in",
"rate at which people who stand on the summit of K2 successfully make",
"we can't afford to do every pixel. # for res= 128, a cut",
"probability_density(self,m, mag_mean, mag_var ) : #print m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) *",
"implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU",
"* \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one can choose to plot the",
"even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"500) if type == \"ligo\" : probMap = obs.map if type == \"ls\"",
"PARTICULAR PURPOSE. See the GNU General Public License for more details. You should",
"= True if type == \"bright\" : if tryApparent : self.lumModel = \"apparent\"",
"self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma,",
"self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0 else : # fixed",
"np.where((apparent_mag >= limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5 else : #",
"down from 196,608 to 10^4 ix = (ligo_spatial > 1e-8) & (ligo_d_mean >",
"software; you can redistribute it and/or modify it under the terms of version",
"= observation.maglim self.limits = observation.limits tryApparent = True if type == \"bright\" :",
"x = obs.x; y = obs.y else : x = obs.hx; y =",
"model # this can be done as the source abs magnitude for calculations",
"\"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits = observation.limits tryApparent =",
"numpy as np import os import scipy.stats import mags import hp2np import warnings",
"self.lumModel = \"kn-gaussian\" # LIGO O1 and O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO",
": self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0 else : #",
"known are bright and dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma",
"= np.zeros(ligo.size) return 0 # realwork ligo_spatial = ligo ligo_d_mean = ligo_distance ligo_d_var",
"Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, = np.where(apparent_mag < limitingMag)",
"if hourangle == False : x = obs.x; y = obs.y else :",
"type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits =",
"ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var ) :",
"== \"\" or self.lastCtype != type: print \"\\t calculating contours for type =",
"A PARTICULAR PURPOSE. See the GNU General Public License for more details. You",
"We will also drop constants, equivalent to assuming we are going # to",
"the absolute scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is done",
"# so that we can add guassians to get a gaussian. absMag_mean =",
"else : x = obs.hx; y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi,",
"with little or no documentation. Science code in the the alpine fast &",
"ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var ) ) norm = ans[0]; norm_error",
"res= 128, a cut at > 1e-8 brings the number of pixels #",
"for type = \",type if hourangle == False : xmin = obs.x.min(); xmax",
"\"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else : # this can be",
"the P_recognition self.pra = observation.pra self.pdec = observation.pdec self.precog = observation.precog # keep",
"# trasformed into a distance modulus (i.e. magnitude) # # Now we weight",
"terms of version 3 of the GNU General Public License as published by",
"for calculations # is taken from self.absMagMean, self.absMagSigma # whereas we're setting the",
"LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type == \"dark\" :",
"def probability_density(self,m, mag_mean, mag_var ) : #print m, mag_mean, mag_var pd= np.exp( -(m-mag_mean)/2/mag_var)",
"up if limitingMag.mean() < -9 : self.probMap = np.zeros(ligo.size) return 0 # realwork",
"(ligo_d_mean > 0) & (limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation",
"# this can be used to scale the magnitudes from the source model",
"= obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype = type",
"the alpine fast & light style. (Note the rate at which people who",
"self.precog = observation.precog # keep the answer self.probMap = \"\" # for plotting",
"# finally, eliminate every where the telescope cannot point prob_map = prob_map *",
"self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else : # this can be used",
"self.limits = observation.limits tryApparent = True if type == \"bright\" : if tryApparent",
": if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0",
"and in absolute magnitude # so that we can add guassians to get",
"who stand on the summit of K2 successfully make it down.) This program",
"whiteLine=\"False\", hourangle=False) : import matplotlib import matplotlib.pyplot as plt con_levels=10 if self.zi ==",
"1e-8) & (ligo_d_mean > 0) & (limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) #",
"# houranlge chooses HA instead of RA projected into mcbryde coords def plotLigoContours(self,",
"setting the absolute scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is",
"# for plotting contours, keep the intermediate data around self.xi, self.yi, self.zi =",
"else : # we can't afford to do every pixel. # for res=",
"ligo_d_var = ligo_distance_sigma**2 # we are going to change variables to distance modulus",
"contours for type = \",type if hourangle == False : xmin = obs.x.min();",
"y = obs.hy zi = matplotlib.mlab.griddata(x,y,probMap,xi,yi) self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype =",
"we're setting the absolute scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this",
"write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,",
"of K2 successfully make it down.) This program is distributed in the hope",
"assume error is gaussian in DM and in absolute magnitude # so that",
"0.5 else : # we can't afford to do every pixel. # for",
"self.pra = observation.pra self.pdec = observation.pdec self.precog = observation.precog # keep the answer",
"infinity # normalize norm_min, norm_max = 7.0, 25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density,",
"type == \"bright\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source",
"telescopeLimits self.probMap = prob_map return 1 # # This is a gaussian in",
"= scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var ) ) norm = ans[0]; norm_error =",
"this code is science code: buggy, barely working, with little or no documentation.",
"print \"\\t probMap: made for source absMag {:.1f}\".format(absMag_mean) # probability of recognition propto",
"== \"bright\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma",
"# fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else",
"under the terms of version 3 of the GNU General Public License as",
"be used to scale the magnitudes from the source model # this can",
"(m - ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var",
"def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose = True) : import scipy.integrate warnings.filterwarnings(\"ignore\") #",
"Software Foundation. More to the points- this code is science code: buggy, barely",
"= [\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose = True)",
"self.xi, self.yi, self.zi = xi,yi,zi self.lastCtype = type if not whiteLine : plt.contour(self.xi,self.yi,self.zi,con_levels,linewidths=3,colors=\"k\")",
"DM and in absolute magnitude # so that we can add guassians to",
"ymin = obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500) if",
"with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma # Currently this is done in mapsAtTimeT.probabilityMaps self.lumModel =",
"= -11.1 # LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type",
": # implementing this in Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean",
"Public License for more details. You should have received a copy of the",
"gaussian ap_mag_mean = distance_mod + absMag_mean ap_mag_var = absMag_var + dm_var ic =",
"= absMag_var + dm_var ic = 0 prob_map = np.copy(ligo_spatial)*0.0 for pix in",
"obs.y.max() else : xmin = obs.hx.min(); xmax = obs.hx.max() ymin = obs.hy.min(); ymax",
"ix, = np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0 ix, = np.where((apparent_mag >= limitingMag)",
"test_sum = ligo_d_var.sum() if self.lumModel == \"apparent\" : # implementing this in Feb",
"telescope cannot point prob_map = prob_map * telescopeLimits self.probMap = prob_map return 1",
"# # Now we weight by r^2 dr , thus assuming equal probability",
"- ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var ) : #print m, mag_mean, mag_var pd=",
"self.absMagMean, self.absMagSigma # whereas we're setting the absolute scale here with # self.modelAbsoluteMagnitude,",
"np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one can choose to plot the ligo contours",
"to infinity # normalize norm_min, norm_max = 7.0, 25.0 # magnitudes ans =",
"scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var ) ) norm = ans[0]; norm_error = ans[1]",
"self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra = observation.pra",
"integrating from 0 to infinity # normalize norm_min, norm_max = 7.0, 25.0 #",
"free software; you can redistribute it and/or modify it under the terms of",
"os import scipy.stats import mags import hp2np import warnings license=\"\"\" Copyright (C) 2014",
"self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel == \"apparent\" : # implementing this in",
"density prob_map = prob_map * self.precog # finally, eliminate every where the telescope",
"# calculate prob mag_min, mag_max = 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max,",
"every where the telescope cannot point prob_map = prob_map * telescopeLimits self.probMap =",
") norm = ans[0]; norm_error = ans[1] # calculate prob mag_min, mag_max =",
"# Now we weight by r^2 dr , thus assuming equal probability per",
"-mag_mean)) return pd # one can choose to plot the ligo contours #",
"bookkeeping for plotting self.zi= \"\" # telescopeLimits = self.limits limitingMag = self.limitingMag #",
"converting from distance to distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so",
"to scale the magnitudes from the source model # this can be done",
"no documentation. Science code in the the alpine fast & light style. (Note",
"self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose",
"drop constants, equivalent to assuming we are going # to renormalize by integrating",
"not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra",
"limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var ) ) prob = ans[0];",
"0 else : # fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma",
"the points- this code is science code: buggy, barely working, with little or",
"obs.x; y = obs.y else : x = obs.hx; y = obs.hy zi",
"= ap_mag_mean[ic] var = ap_mag_var[ic] # Now we weight by r^2 dr ,",
"ic += 1 print \"\\t probMap: made for source absMag {:.1f}\".format(absMag_mean) # probability",
"a gaussian. absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel",
"= absMag_mean ix, = np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0 ix, = np.where((apparent_mag",
"self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra = observation.pra self.pdec = observation.pdec self.precog =",
"to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA",
"= ap_mag_var[ic] # Now we weight by r^2 dr , thus assuming equal",
"prob ic += 1 print \"\\t probMap: made for source absMag {:.1f}\".format(absMag_mean) #",
"recognition propto star density prob_map = prob_map * self.precog # finally, eliminate every",
"return 1 # # This is a gaussian in apparent magnitude, weighted by",
"modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding gaussians to get a",
"we can add guassians to get a gaussian. absMag_mean = self.absMagMean absMag_var =",
"is science code: buggy, barely working, with little or no documentation. Science code",
"ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A",
"gaussians, so adding gaussians to get a gaussian ap_mag_mean = distance_mod + absMag_mean",
"fast & light style. (Note the rate at which people who stand on",
"(itself # trasformed into a distance modulus (i.e. magnitude) # # Now we",
"of the GNU General Public License as published by the Free Software Foundation.",
"0 prob_map = np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var",
"error is gaussian in DM and in absolute magnitude # so that we",
"science code: buggy, barely working, with little or no documentation. Science code in",
"finally, eliminate every where the telescope cannot point prob_map = prob_map * telescopeLimits",
"import warnings license=\"\"\" Copyright (C) 2014 <NAME> This program is free software; you",
"which people who stand on the summit of K2 successfully make it down.)",
"intermediate data around self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self,",
"== False : xmin = obs.x.min(); xmax = obs.x.max() ymin = obs.y.min(); ymax",
": probMap = obs.map*self.probMap if hourangle == False : x = obs.x; y",
"modulus (magnitude), # then, assume error is gaussian in DM and in absolute",
"eliminate every where the telescope cannot point prob_map = prob_map * telescopeLimits self.probMap",
"magnitude, weighted by r^2 (itself # trasformed into a distance modulus (i.e. magnitude)",
"gaussian. absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum() if self.lumModel ==",
"in apparent magnitude, weighted by r^2 (itself # trasformed into a distance modulus",
"a gaussian ap_mag_mean = distance_mod + absMag_mean ap_mag_var = absMag_var + dm_var ic",
"used to scale the magnitudes from the source model # this can be",
"(limitingMag > 0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting from distance",
"the Free Software Foundation. More to the points- this code is science code:",
"0) distance_mod = 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting from distance to distance",
"ap_mag_var = absMag_var + dm_var ic = 0 prob_map = np.copy(ligo_spatial)*0.0 for pix",
"GNU General Public License as published by the Free Software Foundation. More to",
"prob_map = np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] : mag = ap_mag_mean[ic] var =",
"can redistribute it and/or modify it under the terms of version 3 of",
"ap_mag_mean[ic] var = ap_mag_var[ic] # Now we weight by r^2 dr , thus",
"+ dm_var ic = 0 prob_map = np.copy(ligo_spatial)*0.0 for pix in np.nonzero(ix)[0] :",
"prob mag_min, mag_max = 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var",
"500) yi=np.linspace(ymin, ymax, 500) if type == \"ligo\" : probMap = obs.map if",
"General Public License as published by the Free Software Foundation. More to the",
"# LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type == \"dark\"",
"np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean,",
"to do every pixel. # for res= 128, a cut at > 1e-8",
"self.lumModel == \"apparent\" : # implementing this in Feb 2020 prob_map = np.zeros(ligo_spatial.size)",
"# Currently this is done in mapsAtTimeT.probabilityMaps self.lumModel = \"kn-gaussian\" # LIGO O1",
"one can choose to plot the ligo contours # or the ligo*obs_prob contours",
": self.probMap = np.zeros(ligo.size) return 0 # realwork ligo_spatial = ligo ligo_d_mean =",
"limitingMag = self.limitingMag # check if sun is up if limitingMag.mean() < -9",
"can choose to plot the ligo contours # or the ligo*obs_prob contours #",
"obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500) if type ==",
"# this can be done as the source abs magnitude for calculations #",
"to get a gaussian. absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2 test_sum = ligo_d_var.sum()",
"= obs.map*self.probMap if hourangle == False : x = obs.x; y = obs.y",
"in the hope that it will be useful, but WITHOUT ANY WARRANTY; without",
"ligo ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2 # we are going to change",
"os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits = observation.limits tryApparent = True if type ==",
"types known are bright and dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma =",
"to get a gaussian ap_mag_mean = distance_mod + absMag_mean ap_mag_var = absMag_var +",
"at which people who stand on the summit of K2 successfully make it",
"have received a copy of the GNU General Public License along with this",
"the answer self.probMap = \"\" # for plotting contours, keep the intermediate data",
"of RA projected into mcbryde coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) :",
"if limitingMag.mean() < -9 : self.probMap = np.zeros(ligo.size) return 0 # realwork ligo_spatial",
"ans[1] prob = prob/norm prob_map[pix] = prob ic += 1 print \"\\t probMap:",
": # fixed luminosity self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0",
"dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the P_recognition",
"= 5*np.log10(ligo_d_mean[ix]*1e6/10.) # error propgation on converting from distance to distance modulus dm_var",
"instead of RA projected into mcbryde coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False)",
"change variables to distance modulus (magnitude), # then, assume error is gaussian in",
"keep the answer self.probMap = \"\" # for plotting contours, keep the intermediate",
"norm_min, norm_max = 7.0, 25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag,",
"guassians to get a gaussian. absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2 test_sum =",
"self.precog # finally, eliminate every where the telescope cannot point prob_map = prob_map",
"= -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type == \"dark\" : if tryApparent :",
"prob_map = prob_map * telescopeLimits self.probMap = prob_map return 1 # # This",
"- ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var )",
"[\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self, ligo, ligo_distance, ligo_distance_sigma, verbose = True) :",
"scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var ) ) prob = ans[0]; prob_error = ans[1]",
"more details. You should have received a copy of the GNU General Public",
"1.0 else : raise Exception ( \"only trigger types known are bright and",
"done as the source abs magnitude for calculations # is taken from self.absMagMean,",
"* \\ # np.exp(0.6*np.log(10.)*(m - ap_mag_mean)) def probability_density(self,m, mag_mean, mag_var ) : #print",
"on the summit of K2 successfully make it down.) This program is distributed",
"renormalize by integrating from 0 to infinity # normalize norm_min, norm_max = 7.0,",
"weighted by r^2 (itself # trasformed into a distance modulus (i.e. magnitude) #",
"7.0, 25.0 # magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var ) )",
"\"kn-gaussian\" # LIGO O1 and O2 #self.modelAbsoluteMagnitude = -11.1 # LIGO O3 self.modelAbsoluteMagnitude",
"= \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else : # this can",
"= obs.x; y = obs.y else : x = obs.hx; y = obs.hy",
"program; if not, write to the Free Software Foundation, Inc., 51 Franklin St,",
"class map(object): \"\"\" \"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir",
"\"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"] self.limitingMag = observation.maglim self.limits = observation.limits tryApparent = True",
"self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else : # this",
"== \"dark\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma",
"self.lumModel = \"bh-gaussian\" self.modelAbsoluteMagnitude = -25.0 self.modelAbsoluteMagnitudeSigma = 1.0 else : raise Exception",
"= self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get the P_recognition self.pra = observation.pra self.pdec",
"\"ls\" : probMap = obs.map*self.probMap if hourangle == False : x = obs.x;",
"to change variables to distance modulus (magnitude), # then, assume error is gaussian",
"= distance_mod + absMag_mean ap_mag_var = absMag_var + dm_var ic = 0 prob_map",
"gaussian in DM and in absolute magnitude # so that we can add",
"ymin = obs.y.min(); ymax = obs.y.max() else : xmin = obs.hx.min(); xmax =",
"distance modulus (i.e. magnitude) # # Now we weight by r^2 dr ,",
"# for res= 128, a cut at > 1e-8 brings the number of",
"Science code in the the alpine fast & light style. (Note the rate",
"scipy.stats import mags import hp2np import warnings license=\"\"\" Copyright (C) 2014 <NAME> This",
"prob_map[ix] = 1.0 ix, = np.where((apparent_mag >= limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix]",
"Copyright (C) 2014 <NAME> This program is free software; you can redistribute it",
"mag_var pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one can",
"RA projected into mcbryde coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import",
"self.limitingMag # check if sun is up if limitingMag.mean() < -9 : self.probMap",
"probability of recognition propto star density prob_map = prob_map * self.precog # finally,",
"= ans[1] prob = prob/norm prob_map[pix] = prob ic += 1 print \"\\t",
"\"\"\" \"\"\" def __init__(self, observation, type=\"bright\", apparent_mag_source=21.5) : \"\"\" \"\"\" data_dir = os.environ[\"DESGW_DATA_DIR\"]",
"or the ligo*obs_prob contours # type=\"ligo\" type=\"ls\" # houranlge chooses HA instead of",
") ) norm = ans[0]; norm_error = ans[1] # calculate prob mag_min, mag_max",
"self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0 else : # fixed luminosity self.lumModel =",
"equal probability per unit volume # probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var) *",
"chooses HA instead of RA projected into mcbryde coords def plotLigoContours(self, obs, type=\"ligo\",",
"the intermediate data around self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\" def",
"get a gaussian ap_mag_mean = distance_mod + absMag_mean ap_mag_var = absMag_var + dm_var",
"unit volume # We will also drop constants, equivalent to assuming we are",
"answer self.probMap = \"\" # for plotting contours, keep the intermediate data around",
"You should have received a copy of the GNU General Public License along",
"<NAME> This program is free software; you can redistribute it and/or modify it",
"self.limitingMag = observation.maglim self.limits = observation.limits tryApparent = True if type == \"bright\"",
"calculating contours for type = \",type if hourangle == False : xmin =",
"source absMag {:.1f}\".format(absMag_mean) # probability of recognition propto star density prob_map = prob_map",
"or self.lastCtype != type: print \"\\t calculating contours for type = \",type if",
"con_levels=10 if self.zi == \"\" or self.lastCtype != type: print \"\\t calculating contours",
"add guassians to get a gaussian. absMag_mean = self.absMagMean absMag_var = self.absMagSigma**2 test_sum",
"\"\\t calculating contours for type = \",type if hourangle == False : xmin",
"import mags import hp2np import warnings license=\"\"\" Copyright (C) 2014 <NAME> This program",
"np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, = np.where(apparent_mag < limitingMag) prob_map[ix] = 1.0 ix,",
"contours, keep the intermediate data around self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype =",
"star density prob_map = prob_map * self.precog # finally, eliminate every where the",
"distance modulus dm_var = ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding gaussians to get",
"hope that it will be useful, but WITHOUT ANY WARRANTY; without even the",
"elif type == \"dark\" : if tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude =",
"< limitingMag) prob_map[ix] = 1.0 ix, = np.where((apparent_mag >= limitingMag) & (apparent_mag <",
"then, assume error is gaussian in DM and in absolute magnitude # so",
"projected into mcbryde coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib",
"mags import hp2np import warnings license=\"\"\" Copyright (C) 2014 <NAME> This program is",
"self.absMagSigma # whereas we're setting the absolute scale here with # self.modelAbsoluteMagnitude, self.modelAbsoluteMagnitudeSigma",
"pixels # down from 196,608 to 10^4 ix = (ligo_spatial > 1e-8) &",
"\"apparent\" self.modelAbsoluteMagnitude = 21.5 self.modelAbsoluteMagnitudeSigma = 0 else : # fixed luminosity self.lumModel",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License",
"we are going # to renormalize by integrating from 0 to infinity #",
"0 to infinity # normalize norm_min, norm_max = 7.0, 25.0 # magnitudes ans",
"calculate prob mag_min, mag_max = 7.0, limitingMag[pix] ans = scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag,",
"verbose = True) : import scipy.integrate warnings.filterwarnings(\"ignore\") # bookkeeping for plotting self.zi= \"\"",
"HA instead of RA projected into mcbryde coords def plotLigoContours(self, obs, type=\"ligo\", whiteLine=\"False\",",
"2014 <NAME> This program is free software; you can redistribute it and/or modify",
"= \",type if hourangle == False : xmin = obs.x.min(); xmax = obs.x.max()",
"around self.xi, self.yi, self.zi = [\"\",\"\",\"\"] self.lastCtype = \"\" def calculateProb(self, ligo, ligo_distance,",
"tryApparent : self.lumModel = \"apparent\" self.modelAbsoluteMagnitude = apparent_mag_source self.modelAbsoluteMagnitudeSigma = 0 else :",
"for plotting self.zi= \"\" # telescopeLimits = self.limits limitingMag = self.limitingMag # check",
"from the source model # this can be done as the source abs",
"magnitudes ans = scipy.integrate.quad(self.probability_density, norm_min, norm_max, args=(mag, var ) ) norm = ans[0];",
"published by the Free Software Foundation. More to the points- this code is",
"obs.hx.max() ymin = obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500)",
"ligo_d_var[ix]*(5./np.log(10)/ligo_d_mean[ix]) # assume gaussians, so adding gaussians to get a gaussian ap_mag_mean =",
"import numpy as np import os import scipy.stats import mags import hp2np import",
"= ligo_distance ligo_d_var = ligo_distance_sigma**2 # we are going to change variables to",
"the GNU General Public License as published by the Free Software Foundation. More",
"ymax = obs.y.max() else : xmin = obs.hx.min(); xmax = obs.hx.max() ymin =",
"going # to renormalize by integrating from 0 to infinity # normalize norm_min,",
"License along with this program; if not, write to the Free Software Foundation,",
"ix, = np.where((apparent_mag >= limitingMag) & (apparent_mag < limitingMag+0.5)) prob_map[ix] = 0.5 else",
"pd= np.exp( -(m-mag_mean)/2/mag_var) * \\ np.exp(0.6*np.log(10.)*(m -mag_mean)) return pd # one can choose",
"useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or",
"the number of pixels # down from 196,608 to 10^4 ix = (ligo_spatial",
"= scipy.integrate.quad(self.probability_density, mag_min, mag_max, args=(mag, var ) ) prob = ans[0]; prob_error =",
"(Note the rate at which people who stand on the summit of K2",
"prob_map * self.precog # finally, eliminate every where the telescope cannot point prob_map",
"= 21.5 self.modelAbsoluteMagnitudeSigma = 0 else : # fixed luminosity self.lumModel = \"bh-gaussian\"",
"trigger types known are bright and dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma",
"it under the terms of version 3 of the GNU General Public License",
"-11.1 # LIGO O3 self.modelAbsoluteMagnitude = -15.5 self.modelAbsoluteMagnitudeSigma = 1.0 elif type ==",
"limitingMag+0.5)) prob_map[ix] = 0.5 else : # we can't afford to do every",
"bright and dark, not {}\".format(type)) self.absMagMean = self.modelAbsoluteMagnitude self.absMagSigma = self.modelAbsoluteMagnitudeSigma # get",
"this can be used to scale the magnitudes from the source model #",
"= obs.hy.min(); ymax = obs.y.max() xi=np.linspace(xmin, xmax, 500) yi=np.linspace(ymin, ymax, 500) if type",
": raise Exception ( \"only trigger types known are bright and dark, not",
"modify it under the terms of version 3 of the GNU General Public",
"is distributed in the hope that it will be useful, but WITHOUT ANY",
"in Feb 2020 prob_map = np.zeros(ligo_spatial.size) apparent_mag = absMag_mean ix, = np.where(apparent_mag <",
"type=\"ligo\", whiteLine=\"False\", hourangle=False) : import matplotlib import matplotlib.pyplot as plt con_levels=10 if self.zi",
"# probability of recognition propto star density prob_map = prob_map * self.precog #",
"= prob_map * telescopeLimits self.probMap = prob_map return 1 # # This is",
"observation.maglim self.limits = observation.limits tryApparent = True if type == \"bright\" : if",
"unit volume # probability_density = np.exp( (m - ap_mag_mean)/2/ap_mag_var) * \\ # np.exp(0.6*np.log(10.)*(m",
"with this program; if not, write to the Free Software Foundation, Inc., 51",
"be done as the source abs magnitude for calculations # is taken from",
"ligo_spatial = ligo ligo_d_mean = ligo_distance ligo_d_var = ligo_distance_sigma**2 # we are going",
"constants, equivalent to assuming we are going # to renormalize by integrating from",
"absMag_mean ap_mag_var = absMag_var + dm_var ic = 0 prob_map = np.copy(ligo_spatial)*0.0 for",
"type = \",type if hourangle == False : xmin = obs.x.min(); xmax =",
"= observation.pdec self.precog = observation.precog # keep the answer self.probMap = \"\" #",
"the GNU General Public License for more details. You should have received a",
"import hp2np import warnings license=\"\"\" Copyright (C) 2014 <NAME> This program is free",
"of recognition propto star density prob_map = prob_map * self.precog # finally, eliminate",
"# bookkeeping for plotting self.zi= \"\" # telescopeLimits = self.limits limitingMag = self.limitingMag",
"calculations # is taken from self.absMagMean, self.absMagSigma # whereas we're setting the absolute",
"This is a gaussian in apparent magnitude, weighted by r^2 (itself # trasformed",
"if hourangle == False : xmin = obs.x.min(); xmax = obs.x.max() ymin =",
"pd # one can choose to plot the ligo contours # or the",
"yi=np.linspace(ymin, ymax, 500) if type == \"ligo\" : probMap = obs.map if type",
"this program; if not, write to the Free Software Foundation, Inc., 51 Franklin",
"!= type: print \"\\t calculating contours for type = \",type if hourangle ==",
"as np import os import scipy.stats import mags import hp2np import warnings license=\"\"\"",
"the ligo contours # or the ligo*obs_prob contours # type=\"ligo\" type=\"ls\" # houranlge",
"the ligo*obs_prob contours # type=\"ligo\" type=\"ls\" # houranlge chooses HA instead of RA",
"sun is up if limitingMag.mean() < -9 : self.probMap = np.zeros(ligo.size) return 0"
] |
[
"des matrices. Auteur: <NAME> Version: 1.0 \"\"\" def matrice_identite(n: int) -> list: \"\"\"",
"vérifier. n: {int} -- Taille de la matrice. Retourne: {bool} -- True si",
"<NAME> Version: 1.0 \"\"\" def matrice_identite(n: int) -> list: \"\"\" Description: Crée une",
"0], [0, 0, 1]] \"\"\" matrice = [] for i in range(n): matrice.append([])",
"matrice est de taille n. Paramètres: matrice: {list} -- Matrice à vérifier. n:",
"n: {int} -- Taille de la matrice. Retourne: {bool} -- True si la",
"i == j: matrice[i].append(1) else: matrice[i].append(0) return matrice def dimension_matrice(matrice: list, n: int)",
"if i == j: matrice[i].append(1) else: matrice[i].append(0) return matrice def dimension_matrice(matrice: list, n:",
"n: {int} -- Taille de la matrice. Retourne: {list} -- Matrice identité de",
"-> bool: \"\"\" Description: Vérifie si la matrice est de taille n. Paramètres:",
"taille n, False sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0, 0], [0,",
"[0, 0, 0]], 3) True \"\"\" if len(matrice) == n and len(matrice[0]) ==",
"taille n. Exemple: >>> matrice_identite(3) [[1, 0, 0], [0, 1, 0], [0, 0,",
"Exemple: >>> matrice_identite(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] \"\"\"",
"Crée une matrice identité de taille n. Paramètres: n: {int} -- Taille de",
"-- Taille de la matrice. Retourne: {list} -- Matrice identité de taille n.",
"0]], 3) True \"\"\" if len(matrice) == n and len(matrice[0]) == n: return",
"1, 0], [0, 0, 1]] \"\"\" matrice = [] for i in range(n):",
"n and len(matrice[0]) == n: return True else: return False # TESTS print(",
"{int} -- Taille de la matrice. Retourne: {list} -- Matrice identité de taille",
"taille n. Paramètres: matrice: {list} -- Matrice à vérifier. n: {int} -- Taille",
"de taille n, False sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0, 0],",
"manipuler des matrices. Auteur: <NAME> Version: 1.0 \"\"\" def matrice_identite(n: int) -> list:",
"\"\"\" Description: Différentes fonctions pour manipuler des matrices. Auteur: <NAME> Version: 1.0 \"\"\"",
"n. Paramètres: matrice: {list} -- Matrice à vérifier. n: {int} -- Taille de",
"Paramètres: n: {int} -- Taille de la matrice. Retourne: {list} -- Matrice identité",
"n: return True else: return False # TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3),",
"1.0 \"\"\" def matrice_identite(n: int) -> list: \"\"\" Description: Crée une matrice identité",
"Matrice identité de taille n. Exemple: >>> matrice_identite(3) [[1, 0, 0], [0, 1,",
"else: matrice[i].append(0) return matrice def dimension_matrice(matrice: list, n: int) -> bool: \"\"\" Description:",
"matrice est de taille n, False sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0,",
"len(matrice[0]) == n: return True else: return False # TESTS print( 'matrice_identite(3)'+' ---------------------------->",
"-- True si la matrice est de taille n, False sinon. Exemple: >>>",
"\"\"\" Description: Vérifie si la matrice est de taille n. Paramètres: matrice: {list}",
"Description: Différentes fonctions pour manipuler des matrices. Auteur: <NAME> Version: 1.0 \"\"\" def",
"range(n): matrice.append([]) for j in range(n): if i == j: matrice[i].append(1) else: matrice[i].append(0)",
"{list} -- Matrice à vérifier. n: {int} -- Taille de la matrice. Retourne:",
"taille n. Paramètres: n: {int} -- Taille de la matrice. Retourne: {list} --",
"de la matrice. Retourne: {list} -- Matrice identité de taille n. Exemple: >>>",
"matrice. Retourne: {list} -- Matrice identité de taille n. Exemple: >>> matrice_identite(3) [[1,",
"est de taille n. Paramètres: matrice: {list} -- Matrice à vérifier. n: {int}",
"la matrice est de taille n. Paramètres: matrice: {list} -- Matrice à vérifier.",
"-- Matrice à vérifier. n: {int} -- Taille de la matrice. Retourne: {bool}",
"Vérifie si la matrice est de taille n. Paramètres: matrice: {list} -- Matrice",
"de taille n. Paramètres: matrice: {list} -- Matrice à vérifier. n: {int} --",
"Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 3) True",
"False sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0, 0], [0, 0, 0]],",
"for j in range(n): if i == j: matrice[i].append(1) else: matrice[i].append(0) return matrice",
"list, n: int) -> bool: \"\"\" Description: Vérifie si la matrice est de",
"matrice identité de taille n. Paramètres: n: {int} -- Taille de la matrice.",
"matrice[i].append(0) return matrice def dimension_matrice(matrice: list, n: int) -> bool: \"\"\" Description: Vérifie",
"for i in range(n): matrice.append([]) for j in range(n): if i == j:",
"dimension_matrice(matrice: list, n: int) -> bool: \"\"\" Description: Vérifie si la matrice est",
"\"\"\" def matrice_identite(n: int) -> list: \"\"\" Description: Crée une matrice identité de",
"-- Taille de la matrice. Retourne: {bool} -- True si la matrice est",
"in range(n): if i == j: matrice[i].append(1) else: matrice[i].append(0) return matrice def dimension_matrice(matrice:",
">>> dimension_matrice([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 3) True \"\"\"",
"in range(n): matrice.append([]) for j in range(n): if i == j: matrice[i].append(1) else:",
"return matrice def dimension_matrice(matrice: list, n: int) -> bool: \"\"\" Description: Vérifie si",
"la matrice est de taille n, False sinon. Exemple: >>> dimension_matrice([[0, 0, 0],",
"-> list: \"\"\" Description: Crée une matrice identité de taille n. Paramètres: n:",
"Matrice à vérifier. n: {int} -- Taille de la matrice. Retourne: {bool} --",
"matrice def dimension_matrice(matrice: list, n: int) -> bool: \"\"\" Description: Vérifie si la",
"[] for i in range(n): matrice.append([]) for j in range(n): if i ==",
"matrice[i].append(1) else: matrice[i].append(0) return matrice def dimension_matrice(matrice: list, n: int) -> bool: \"\"\"",
"matrices. Auteur: <NAME> Version: 1.0 \"\"\" def matrice_identite(n: int) -> list: \"\"\" Description:",
"fonctions pour manipuler des matrices. Auteur: <NAME> Version: 1.0 \"\"\" def matrice_identite(n: int)",
"-- Matrice identité de taille n. Exemple: >>> matrice_identite(3) [[1, 0, 0], [0,",
"if len(matrice) == n and len(matrice[0]) == n: return True else: return False",
"len(matrice) == n and len(matrice[0]) == n: return True else: return False #",
"Description: Crée une matrice identité de taille n. Paramètres: n: {int} -- Taille",
"matrice.append([]) for j in range(n): if i == j: matrice[i].append(1) else: matrice[i].append(0) return",
"0], [0, 1, 0], [0, 0, 1]] \"\"\" matrice = [] for i",
"{list} -- Matrice identité de taille n. Exemple: >>> matrice_identite(3) [[1, 0, 0],",
"return True else: return False # TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3), '\\ndimension_matrice(matrice_identite(3),",
"list: \"\"\" Description: Crée une matrice identité de taille n. Paramètres: n: {int}",
"\"\"\" matrice = [] for i in range(n): matrice.append([]) for j in range(n):",
"Auteur: <NAME> Version: 1.0 \"\"\" def matrice_identite(n: int) -> list: \"\"\" Description: Crée",
"de taille n. Paramètres: n: {int} -- Taille de la matrice. Retourne: {list}",
"matrice_identite(n: int) -> list: \"\"\" Description: Crée une matrice identité de taille n.",
"= [] for i in range(n): matrice.append([]) for j in range(n): if i",
"matrice: {list} -- Matrice à vérifier. n: {int} -- Taille de la matrice.",
"Retourne: {bool} -- True si la matrice est de taille n, False sinon.",
"3) True \"\"\" if len(matrice) == n and len(matrice[0]) == n: return True",
"[0, 0, 0], [0, 0, 0]], 3) True \"\"\" if len(matrice) == n",
"j in range(n): if i == j: matrice[i].append(1) else: matrice[i].append(0) return matrice def",
"0, 1]] \"\"\" matrice = [] for i in range(n): matrice.append([]) for j",
"[0, 0, 1]] \"\"\" matrice = [] for i in range(n): matrice.append([]) for",
"False # TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3), '\\ndimension_matrice(matrice_identite(3), 3)'+' ------> ', dimension_matrice(matrice_identite(3),",
"TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3), '\\ndimension_matrice(matrice_identite(3), 3)'+' ------> ', dimension_matrice(matrice_identite(3), 3) )",
"range(n): if i == j: matrice[i].append(1) else: matrice[i].append(0) return matrice def dimension_matrice(matrice: list,",
"[0, 1, 0], [0, 0, 1]] \"\"\" matrice = [] for i in",
"[[1, 0, 0], [0, 1, 0], [0, 0, 1]] \"\"\" matrice = []",
"else: return False # TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3), '\\ndimension_matrice(matrice_identite(3), 3)'+' ------>",
"Taille de la matrice. Retourne: {bool} -- True si la matrice est de",
"Version: 1.0 \"\"\" def matrice_identite(n: int) -> list: \"\"\" Description: Crée une matrice",
"i in range(n): matrice.append([]) for j in range(n): if i == j: matrice[i].append(1)",
"def dimension_matrice(matrice: list, n: int) -> bool: \"\"\" Description: Vérifie si la matrice",
"\"\"\" Description: Crée une matrice identité de taille n. Paramètres: n: {int} --",
"n, False sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0, 0], [0, 0,",
"def matrice_identite(n: int) -> list: \"\"\" Description: Crée une matrice identité de taille",
"n. Exemple: >>> matrice_identite(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]]",
"matrice = [] for i in range(n): matrice.append([]) for j in range(n): if",
"si la matrice est de taille n. Paramètres: matrice: {list} -- Matrice à",
"\"\"\" if len(matrice) == n and len(matrice[0]) == n: return True else: return",
"{int} -- Taille de la matrice. Retourne: {bool} -- True si la matrice",
"pour manipuler des matrices. Auteur: <NAME> Version: 1.0 \"\"\" def matrice_identite(n: int) ->",
"0], [0, 0, 0]], 3) True \"\"\" if len(matrice) == n and len(matrice[0])",
"dimension_matrice([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 3) True \"\"\" if",
"1]] \"\"\" matrice = [] for i in range(n): matrice.append([]) for j in",
"int) -> bool: \"\"\" Description: Vérifie si la matrice est de taille n.",
"0, 0], [0, 0, 0], [0, 0, 0]], 3) True \"\"\" if len(matrice)",
"0, 0]], 3) True \"\"\" if len(matrice) == n and len(matrice[0]) == n:",
"Taille de la matrice. Retourne: {list} -- Matrice identité de taille n. Exemple:",
"Retourne: {list} -- Matrice identité de taille n. Exemple: >>> matrice_identite(3) [[1, 0,",
"la matrice. Retourne: {bool} -- True si la matrice est de taille n,",
"0, 0], [0, 1, 0], [0, 0, 1]] \"\"\" matrice = [] for",
"est de taille n, False sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0,",
"return False # TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3), '\\ndimension_matrice(matrice_identite(3), 3)'+' ------> ',",
"bool: \"\"\" Description: Vérifie si la matrice est de taille n. Paramètres: matrice:",
"si la matrice est de taille n, False sinon. Exemple: >>> dimension_matrice([[0, 0,",
"identité de taille n. Exemple: >>> matrice_identite(3) [[1, 0, 0], [0, 1, 0],",
">>> matrice_identite(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] \"\"\" matrice",
"{bool} -- True si la matrice est de taille n, False sinon. Exemple:",
"== n and len(matrice[0]) == n: return True else: return False # TESTS",
"une matrice identité de taille n. Paramètres: n: {int} -- Taille de la",
"identité de taille n. Paramètres: n: {int} -- Taille de la matrice. Retourne:",
"j: matrice[i].append(1) else: matrice[i].append(0) return matrice def dimension_matrice(matrice: list, n: int) -> bool:",
"Différentes fonctions pour manipuler des matrices. Auteur: <NAME> Version: 1.0 \"\"\" def matrice_identite(n:",
"la matrice. Retourne: {list} -- Matrice identité de taille n. Exemple: >>> matrice_identite(3)",
"matrice. Retourne: {bool} -- True si la matrice est de taille n, False",
"sinon. Exemple: >>> dimension_matrice([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 3)",
"<filename>Python/Maths/matrices.py<gh_stars>1-10 \"\"\" Description: Différentes fonctions pour manipuler des matrices. Auteur: <NAME> Version: 1.0",
"de la matrice. Retourne: {bool} -- True si la matrice est de taille",
"n: int) -> bool: \"\"\" Description: Vérifie si la matrice est de taille",
"True si la matrice est de taille n, False sinon. Exemple: >>> dimension_matrice([[0,",
"de taille n. Exemple: >>> matrice_identite(3) [[1, 0, 0], [0, 1, 0], [0,",
"Paramètres: matrice: {list} -- Matrice à vérifier. n: {int} -- Taille de la",
"n. Paramètres: n: {int} -- Taille de la matrice. Retourne: {list} -- Matrice",
"== j: matrice[i].append(1) else: matrice[i].append(0) return matrice def dimension_matrice(matrice: list, n: int) ->",
"True else: return False # TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3), '\\ndimension_matrice(matrice_identite(3), 3)'+'",
"# TESTS print( 'matrice_identite(3)'+' ----------------------------> ', matrice_identite(3), '\\ndimension_matrice(matrice_identite(3), 3)'+' ------> ', dimension_matrice(matrice_identite(3), 3)",
"int) -> list: \"\"\" Description: Crée une matrice identité de taille n. Paramètres:",
"matrice_identite(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] \"\"\" matrice =",
"True \"\"\" if len(matrice) == n and len(matrice[0]) == n: return True else:",
"== n: return True else: return False # TESTS print( 'matrice_identite(3)'+' ----------------------------> ',",
"Description: Vérifie si la matrice est de taille n. Paramètres: matrice: {list} --",
"and len(matrice[0]) == n: return True else: return False # TESTS print( 'matrice_identite(3)'+'",
"à vérifier. n: {int} -- Taille de la matrice. Retourne: {bool} -- True",
"0, 0], [0, 0, 0]], 3) True \"\"\" if len(matrice) == n and",
"0], [0, 0, 0], [0, 0, 0]], 3) True \"\"\" if len(matrice) =="
] |
[
"from flask import Flask, current_app, render_template, request from flask_babel import Babel from flask_babel",
"dotenv import load_dotenv from flask import Flask, current_app, render_template, request from flask_babel import",
"import LoginManager from flask_mail import Mail from flask_migrate import Migrate from flask_sqlalchemy import",
"as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from",
"cookie by remember-me option mail = Mail() flask_bcrypt = Bcrypt() babel = Babel()",
"from app.main import bp as main_bp app.register_blueprint(main_bp) return app @babel.localeselector def get_locale(): return",
"session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db,",
"import Bcrypt from flask_login import LoginManager from flask_mail import Mail from flask_migrate import",
"app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import",
"migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from app.errors import bp as errors_bp app.register_blueprint(errors_bp)",
"Flask, current_app, render_template, request from flask_babel import Babel from flask_babel import lazy_gettext as",
"deleting session cookie after recovered # cookie by remember-me option mail = Mail()",
"# Above strong mode causes deleting session cookie after recovered # cookie by",
"recovered # cookie by remember-me option mail = Mail() flask_bcrypt = Bcrypt() babel",
"Babel() csrf = CSRFProtect() talisman = Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404 def",
"app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main",
"from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from",
"as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp)",
"bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp as main_bp app.register_blueprint(main_bp)",
"url_prefix=\"/auth\") from app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp",
"url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) return app @babel.localeselector def",
"Bcrypt() babel = Babel() csrf = CSRFProtect() talisman = Talisman() def page_not_found(e): return",
"= Babel() csrf = CSRFProtect() talisman = Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404",
"import lazy_gettext as _l from flask_bcrypt import Bcrypt from flask_login import LoginManager from",
"page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app",
"= \"info\" # login.session_protection = \"strong\" # Above strong mode causes deleting session",
"from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_talisman import Talisman from",
"from flask_mail import Mail from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from",
"flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_talisman import Talisman from flask_wtf.csrf",
"= \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect your account, please reauthenticate to access",
"remember-me option mail = Mail() flask_bcrypt = Bcrypt() babel = Babel() csrf =",
"twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from",
"login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https,",
"this page.\" ) login.needs_refresh_message_category = \"info\" # login.session_protection = \"strong\" # Above strong",
"render_as_batch=True) else: migrate.init_app(app, db) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found)",
"SQLAlchemy() migrate = Migrate() login = LoginManager() login.login_view = \"auth.login\" login.login_message = _l(\"Please",
"CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with",
"500 def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app)",
"bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\")",
"account, please reauthenticate to access this page.\" ) login.needs_refresh_message_category = \"info\" # login.session_protection",
"app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings()",
"from flask_babel import lazy_gettext as _l from flask_bcrypt import Bcrypt from flask_login import",
"flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect db = SQLAlchemy() migrate = Migrate()",
"babel = Babel() csrf = CSRFProtect() talisman = Talisman() def page_not_found(e): return render_template(\"errors/404.html\"),",
"LoginManager() login.login_view = \"auth.login\" login.login_message = _l(\"Please log in to access this page.\")",
"LoginManager from flask_mail import Mail from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy",
"Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def",
"flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from flask_migrate",
"mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options,",
"reauthenticate to access this page.\" ) login.needs_refresh_message_category = \"info\" # login.session_protection = \"strong\"",
"def page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config):",
"content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername",
"os from dataclasses import dataclass from config import Config, CSPSettings from dotenv import",
"flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security,",
"= Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app(",
"= Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500",
"= _l( u\"To protect your account, please reauthenticate to access this page.\" )",
"db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in,",
"page.\" ) login.needs_refresh_message_category = \"info\" # login.session_protection = \"strong\" # Above strong mode",
"import dataclass from config import Config, CSPSettings from dotenv import load_dotenv from flask",
"if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from app.errors import",
"bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth import bp as",
"import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth import bp",
"log in to access this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To",
"import CSRFProtect db = SQLAlchemy() migrate = Migrate() login = LoginManager() login.login_view =",
"protect your account, please reauthenticate to access this page.\" ) login.needs_refresh_message_category = \"info\"",
"app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth import",
"# cookie by remember-me option mail = Mail() flask_bcrypt = Bcrypt() babel =",
"with app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from",
"your account, please reauthenticate to access this page.\" ) login.needs_refresh_message_category = \"info\" #",
"\"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect your account, please reauthenticate to access this",
"\"strong\" # Above strong mode causes deleting session cookie after recovered # cookie",
"return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app)",
"app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if",
"flask import Flask, current_app, render_template, request from flask_babel import Babel from flask_babel import",
"_l(\"Please log in to access this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l(",
"import bp as main_bp app.register_blueprint(main_bp) return app @babel.localeselector def get_locale(): return request.accept_languages.best_match(current_app.config[\"LANGUAGES\"]) from",
"from dotenv import load_dotenv from flask import Flask, current_app, render_template, request from flask_babel",
") with app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db)",
"access this page.\" ) login.needs_refresh_message_category = \"info\" # login.session_protection = \"strong\" # Above",
"causes deleting session cookie after recovered # cookie by remember-me option mail =",
"import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp,",
"strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else:",
"dataclasses import dataclass from config import Config, CSPSettings from dotenv import load_dotenv from",
"from app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp as",
"main_bp app.register_blueprint(main_bp) return app @babel.localeselector def get_locale(): return request.accept_languages.best_match(current_app.config[\"LANGUAGES\"]) from app import models",
"flask_sqlalchemy import SQLAlchemy from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect db =",
"strong mode causes deleting session cookie after recovered # cookie by remember-me option",
"csrf.exempt(webauthn_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) return app @babel.localeselector def get_locale():",
"Bcrypt from flask_login import LoginManager from flask_mail import Mail from flask_migrate import Migrate",
"login = LoginManager() login.login_view = \"auth.login\" login.login_message = _l(\"Please log in to access",
"babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only,",
"CSRFProtect() talisman = Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return",
"db, render_as_batch=True) else: migrate.init_app(app, db) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404,",
"from app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp",
"app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp as",
"app.main import bp as main_bp app.register_blueprint(main_bp) return app @babel.localeselector def get_locale(): return request.accept_languages.best_match(current_app.config[\"LANGUAGES\"])",
"from flask_wtf.csrf import CSRFProtect db = SQLAlchemy() migrate = Migrate() login = LoginManager()",
"render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app)",
"page_not_found) app.register_error_handler(500, internal_error) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa",
"db = SQLAlchemy() migrate = Migrate() login = LoginManager() login.login_view = \"auth.login\" login.login_message",
"to access this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect your",
"load_dotenv from flask import Flask, current_app, render_template, request from flask_babel import Babel from",
"to access this page.\" ) login.needs_refresh_message_category = \"info\" # login.session_protection = \"strong\" #",
"from flask_sqlalchemy import SQLAlchemy from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect db",
"Above strong mode causes deleting session cookie after recovered # cookie by remember-me",
"= \"auth.login\" login.login_message = _l(\"Please log in to access this page.\") login.refresh_view =",
"_l from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail",
"as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth import bp as auth_bp",
"login.needs_refresh_message = _l( u\"To protect your account, please reauthenticate to access this page.\"",
"csrf = CSRFProtect() talisman = Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e):",
"Migrate from flask_sqlalchemy import SQLAlchemy from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect",
"else: migrate.init_app(app, db) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500,",
"app.register_error_handler(500, internal_error) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import",
"import Babel from flask_babel import lazy_gettext as _l from flask_bcrypt import Bcrypt from",
"talisman = Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"),",
"== \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from app.errors import bp as",
"flask_mail import Mail from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_talisman",
"please reauthenticate to access this page.\" ) login.needs_refresh_message_category = \"info\" # login.session_protection =",
"cookie after recovered # cookie by remember-me option mail = Mail() flask_bcrypt =",
"\"info\" # login.session_protection = \"strong\" # Above strong mode causes deleting session cookie",
"from flask_login import LoginManager from flask_mail import Mail from flask_migrate import Migrate from",
"in to access this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect",
"content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername ==",
"\"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from app.errors import bp as errors_bp",
") login.needs_refresh_message_category = \"info\" # login.session_protection = \"strong\" # Above strong mode causes",
"force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername == \"sqlite\":",
"mail = Mail() flask_bcrypt = Bcrypt() babel = Babel() csrf = CSRFProtect() talisman",
"Mail() flask_bcrypt = Bcrypt() babel = Babel() csrf = CSRFProtect() talisman = Talisman()",
"create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp =",
"CSPSettings from dotenv import load_dotenv from flask import Flask, current_app, render_template, request from",
"\"auth.login\" login.login_message = _l(\"Please log in to access this page.\") login.refresh_view = \"auth.refresh_login\"",
"internal_error) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp",
"<reponame>onyxcherry/OnyxcherryOTP<gh_stars>1-10 import os from dataclasses import dataclass from config import Config, CSPSettings from",
"from app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth",
"= LoginManager() login.login_view = \"auth.login\" login.login_message = _l(\"Please log in to access this",
"= SQLAlchemy() migrate = Migrate() login = LoginManager() login.login_view = \"auth.login\" login.login_message =",
"app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from",
"Babel from flask_babel import lazy_gettext as _l from flask_bcrypt import Bcrypt from flask_login",
"app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp as twofa_bp",
"= _l(\"Please log in to access this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message =",
"this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect your account, please",
"bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\")",
"webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) return app",
"as main_bp app.register_blueprint(main_bp) return app @babel.localeselector def get_locale(): return request.accept_languages.best_match(current_app.config[\"LANGUAGES\"]) from app import",
"flask_bcrypt = Bcrypt() babel = Babel() csrf = CSRFProtect() talisman = Talisman() def",
"import Migrate from flask_sqlalchemy import SQLAlchemy from flask_talisman import Talisman from flask_wtf.csrf import",
"= CSRFProtect() talisman = Talisman() def page_not_found(e): return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback()",
"import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp,",
"flask_babel import lazy_gettext as _l from flask_bcrypt import Bcrypt from flask_login import LoginManager",
"SQLAlchemy from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect db = SQLAlchemy() migrate",
"import Mail from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_talisman import",
"render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app = Flask(__name__)",
"mode causes deleting session cookie after recovered # cookie by remember-me option mail",
"db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from app.errors import bp",
"errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth import bp as auth_bp app.register_blueprint(auth_bp,",
"import Config, CSPSettings from dotenv import load_dotenv from flask import Flask, current_app, render_template,",
"from flask_babel import Babel from flask_babel import lazy_gettext as _l from flask_bcrypt import",
"= Bcrypt() babel = Babel() csrf = CSRFProtect() talisman = Talisman() def page_not_found(e):",
"Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app,",
"import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp as main_bp",
"migrate = Migrate() login = LoginManager() login.login_view = \"auth.login\" login.login_message = _l(\"Please log",
"after recovered # cookie by remember-me option mail = Mail() flask_bcrypt = Bcrypt()",
"Talisman from flask_wtf.csrf import CSRFProtect db = SQLAlchemy() migrate = Migrate() login =",
"from dataclasses import dataclass from config import Config, CSPSettings from dotenv import load_dotenv",
"flask_login import LoginManager from flask_mail import Mail from flask_migrate import Migrate from flask_sqlalchemy",
"Config, CSPSettings from dotenv import load_dotenv from flask import Flask, current_app, render_template, request",
"by remember-me option mail = Mail() flask_bcrypt = Bcrypt() babel = Babel() csrf",
"import Talisman from flask_wtf.csrf import CSRFProtect db = SQLAlchemy() migrate = Migrate() login",
"db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app)",
"csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy,",
"app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from app.errors",
"import load_dotenv from flask import Flask, current_app, render_template, request from flask_babel import Babel",
"flask_babel import Babel from flask_babel import lazy_gettext as _l from flask_bcrypt import Bcrypt",
"404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class)",
"render_template, request from flask_babel import Babel from flask_babel import lazy_gettext as _l from",
"talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context():",
"url_prefix=\"/twofa\") from app.webauthn import bp as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import",
"app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn import bp as webauthn_bp",
"app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\")",
"config import Config, CSPSettings from dotenv import load_dotenv from flask import Flask, current_app,",
"import Flask, current_app, render_template, request from flask_babel import Babel from flask_babel import lazy_gettext",
"migrate.init_app(app, db) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error)",
"page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect your account, please reauthenticate",
"from config import Config, CSPSettings from dotenv import load_dotenv from flask import Flask,",
"bp as main_bp app.register_blueprint(main_bp) return app @babel.localeselector def get_locale(): return request.accept_languages.best_match(current_app.config[\"LANGUAGES\"]) from app",
"csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure,",
"_l( u\"To protect your account, please reauthenticate to access this page.\" ) login.needs_refresh_message_category",
"= Mail() flask_bcrypt = Bcrypt() babel = Babel() csrf = CSRFProtect() talisman =",
"lazy_gettext as _l from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail",
"option mail = Mail() flask_bcrypt = Bcrypt() babel = Babel() csrf = CSRFProtect()",
"import os from dataclasses import dataclass from config import Config, CSPSettings from dotenv",
"= Migrate() login = LoginManager() login.login_view = \"auth.login\" login.login_message = _l(\"Please log in",
"from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp as",
"login.needs_refresh_message_category = \"info\" # login.session_protection = \"strong\" # Above strong mode causes deleting",
"session cookie after recovered # cookie by remember-me option mail = Mail() flask_bcrypt",
"internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app)",
"app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp = CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy,",
"as webauthn_bp app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) return",
"= \"strong\" # Above strong mode causes deleting session cookie after recovered #",
"referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app,",
"Mail from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_talisman import Talisman",
"return render_template(\"errors/404.html\"), 404 def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app =",
"request from flask_babel import Babel from flask_babel import lazy_gettext as _l from flask_bcrypt",
"db) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) from",
"auth_bp app.register_blueprint(auth_bp, url_prefix=\"/auth\") from app.twofa import bp as twofa_bp app.register_blueprint(twofa_bp, url_prefix=\"/twofa\") from app.webauthn",
"# login.session_protection = \"strong\" # Above strong mode causes deleting session cookie after",
"login.session_protection = \"strong\" # Above strong mode causes deleting session cookie after recovered",
"app.register_blueprint(webauthn_bp, url_prefix=\"/webauthn\") csrf.exempt(webauthn_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) return app @babel.localeselector",
"dataclass from config import Config, CSPSettings from dotenv import load_dotenv from flask import",
"access this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect your account,",
"session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app, db, render_as_batch=True)",
"as _l from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import",
"u\"To protect your account, please reauthenticate to access this page.\" ) login.needs_refresh_message_category =",
"def internal_error(e): db.session.rollback() return render_template(\"errors/500.html\"), 500 def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app)",
"flask_wtf.csrf import CSRFProtect db = SQLAlchemy() migrate = Migrate() login = LoginManager() login.login_view",
"current_app, render_template, request from flask_babel import Babel from flask_babel import lazy_gettext as _l",
"login.login_view = \"auth.login\" login.login_message = _l(\"Please log in to access this page.\") login.refresh_view",
"login.login_message = _l(\"Please log in to access this page.\") login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message",
"Migrate() login = LoginManager() login.login_view = \"auth.login\" login.login_message = _l(\"Please log in to",
"frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, ) with app.app_context(): if db.engine.url.drivername == \"sqlite\": migrate.init_app(app,",
"def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) login.init_app(app) mail.init_app(app) csrf.init_app(app) babel.init_app(app) flask_bcrypt.init_app(app) csp",
"login.refresh_view = \"auth.refresh_login\" login.needs_refresh_message = _l( u\"To protect your account, please reauthenticate to",
"from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect db = SQLAlchemy() migrate =",
"import SQLAlchemy from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect db = SQLAlchemy()",
"CSRFProtect db = SQLAlchemy() migrate = Migrate() login = LoginManager() login.login_view = \"auth.login\"",
"= CSPSettings() talisman.init_app( app, content_security_policy=csp.content_security_policy, content_security_policy_nonce_in=csp.content_security_policy_nonce_in, force_https=csp.force_https, frame_options=csp.frame_options, session_cookie_secure=csp.session_cookie_secure, session_cookie_http_only=csp.session_cookie_http_only, strict_transport_security=csp.strict_transport_security, referrer_policy=csp.referrer_policy, )"
] |
[] |
[
"% 4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter % 4 == 3:",
"mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write =",
"err.code == 404: pass else: for gene in best: for address in best[gene]:",
"organism = best # for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError",
"\"\"\" try: mol_weights = {} for ec_number in bigg_ids: # WARNING: joblib may",
"' + ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError",
"for ec number: '+ec_number) continue else: raise if genes: loop = 'best' searching",
"CS from multiprocessing import Pool from urllib.error import HTTPError from DataTreatment import openJson,",
"'TMU', 'MDO', 'SHR', 'OAA'] animals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC',",
"'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN',",
"done for this project. Hopefully going sequentially increases both readability and efficiency. Parameters",
"searching = False except TypeError as err: if loop == 'best': loop =",
"genes: return genes['SCE'] elif 'ECO' in genes: return genes['ECO'] def loopHandler(mol_weights, ec_number, genes,",
"+ ':' + address) sequence = CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot",
"address loop : string Indicates the highest potential group of matching organisms to",
"in mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] = {} mol_weights_to_write[bigg_id]['ec_number'] = ec_number",
"== 'vertebrates': loop = 'csm' if loop == 'csm': searching = False finally:",
"fillData(mol_weights, ec_number, organism, address) except HTTPError as err: if err.code == 404: pass",
"BiGG id: ' + ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number)",
"'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF',",
"genes: return genes['DME'] elif 'SCE' in genes: return genes['SCE'] elif 'ECO' in genes:",
"collected data in program by this process. \"\"\" try: mol_weights = {} for",
"and organism \"\"\" if loop == 'best': if 'CGE' in genes: return genes['CGE']",
"empty list. will contain estimated molecular weights of enzymes. ec_number : string genes",
"here containing depicrated ec numbers Returns ------- dict key: ec number. value: all",
"'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH',",
"[]) optimized_bigg[v].append(k) counter = 0 for ec_number in optimized_bigg: if counter % 4",
"err: if err.code == 404: pass else: for gene in best: for address",
"write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for ec_number in mol_weights:",
"'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals = ['HSA', 'PTR', 'PPS', 'GGO',",
"function called by each multiprocessing.process. Parameters ---------- bigg_ids : dict key: ec_number. value:",
"searching: best = returnBestAddress(genes, loop) if not best: if loop == 'best': loop",
"Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for ec_number in mol_weights: for bigg_id in mol_weights[ec_number]['bigg",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Jan 24 16:03:28 2018",
"for available genes matching kegg enzyme entry. This function searches 'sequentially'. It returns",
"try: fillData(mol_weights, ec_number, organism, address) except HTTPError as err: if err.code == 404:",
"available model organism genes. Organisms phylogenetically closer to Cricetulus griseus are preferred, but",
"'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU',",
"= 'csm' break if loop == 'csm': searching = False return None searching",
"enzyme uniprot id and AA sequence. Parameters ---------- mol_weights : dict object containing",
"'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM',",
"not been done for this project. Hopefully going sequentially increases both readability and",
"counter = counter + 1 try: with Pool(processes=4) as pool: del_ec1 = []",
"coding: utf-8 -*- \"\"\" Created on Wed Jan 24 16:03:28 2018 @author: dimitricoukos",
"study of the phylogenetic tree has not been done for this project. Hopefully",
"searching = True while searching: try: loopHandler(mol_weights, ec_number, genes, loop) searching = False",
"'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG',",
"'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA']",
"loop = 'vertebrates' if loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return",
"if err.code == 404: pass def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg for",
"False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = [] if loop == 'best' or loop",
"'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC',",
"data in program by this process. \"\"\" try: mol_weights = {} for ec_number",
"elif 'HSA' in genes: return genes['HSA'] else: loop = 'mammals' if loop ==",
"'best' or loop == 'csm': for address in best: organism = best #",
"'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO',",
"loop == 'csm': searching = False finally: return mol_weights if __name__ == '__main__':",
"pass else: for gene in best: for address in best[gene]: organism = best[gene]",
"containing all information collected by program. ec_number : string enzyme classification number used",
"'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT',",
"[] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 =",
"= {} for ec_number in bigg_ids: # WARNING: joblib may require list mol_weights[ec_number]",
"mol_weights = {} if len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters =",
"pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for ec in",
"import Pool from urllib.error import HTTPError from DataTreatment import openJson, write mammals =",
"pool.join() for ec in del_ec1: mw_1.pop(ec, None) for ec in del_ec2: mw_2.pop(ec, None)",
"del_ec3: mw_3.pop(ec, None) for ec in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get())",
"del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for ec in del_ec1: mw_1.pop(ec,",
"> 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for ec_number",
"'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ',",
"Cricetulus griseus are preferred, but they are chosen by approximation. A detailed study",
"dict key: kegg organism code. value: gene addresses for enzyme and organism \"\"\"",
"and efficiency. Parameters ---------- genes : dict key: value pair is organism: address",
"= pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4,",
"'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals = ['HSA', 'PTR', 'PPS',",
"for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError as err: if err.code",
"= set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else: loop = 'csm' # Stands for",
"k, v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0 for",
"404 and loop == 'csm': searching = False except TypeError as err: if",
"genes : dict key: value pair is organism: address loop : string Indicates",
"genes matches. Parameters ---------- mol_weights : list empty list. will contain estimated molecular",
"best = returnBestAddress(genes, loop) if not best: if loop == 'best': loop =",
"kegg organism code. value: gene addresses for enzyme and organism \"\"\" if loop",
"if loop == 'mammals': loop = 'vertebrates' break if loop == 'vertebrates': loop",
"string \"\"\" searching = True while searching: best = returnBestAddress(genes, loop) if not",
"pair is organism: address loop : string Indicates the highest potential group of",
"return genes['DME'] elif 'SCE' in genes: return genes['SCE'] elif 'ECO' in genes: return",
"'mammals': loop = 'vertebrates' break if loop == 'vertebrates': loop = 'csm' break",
"ec in del_ec3: mw_3.pop(ec, None) for ec in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get())",
"multiprocessing import Pool from urllib.error import HTTPError from DataTreatment import openJson, write mammals",
"returnBestAddress based on best potential genes matches. Parameters ---------- mol_weights : list empty",
"collected by program. ec_number : string enzyme classification number used to organize data.",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Wed Jan 24",
"multiprocessing.process. Parameters ---------- bigg_ids : dict key: ec_number. value: corresponding bigg ids. del_ec",
"python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services as CS from multiprocessing",
"'csm' break if loop == 'csm': searching = False return None searching =",
"------- dict key: ec number. value: all collected data in program by this",
"404: pass else: for gene in best: for address in best[gene]: organism =",
"of matching organisms to search in. Returns ------- dict key: kegg organism code.",
"for address in best[gene]: organism = best[gene] # for readability try: fillData(mol_weights, ec_number,",
"return mol_weights if __name__ == '__main__': sub_dict_1 = {} sub_dict_2 = {} sub_dict_3",
"uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called",
"len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {}",
"err: if loop == 'best': loop = 'mammals' if loop == 'mammals': loop",
"except HTTPError as err: if err.code == 404: pass def fillData(mol_weights, ec_number, organism,",
"sys import cobra_services as CS from multiprocessing import Pool from urllib.error import HTTPError",
"Organisms phylogenetically closer to Cricetulus griseus are preferred, but they are chosen by",
"'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else: loop = 'vertebrates' if",
"= best # for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError as",
"(sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for ec in del_ec1:",
"genes, loop) searching = False except HTTPError as err: if err.code == 404",
"= set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else: loop = 'vertebrates' if loop ==",
"= 0 for ec_number in optimized_bigg: if counter % 4 == 0: sub_dict_1[ec_number]",
"'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI',",
"'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB',",
"== 'csm': for address in best: organism = best # for readability try:",
"models\" if loop == 'csm': if 'DME' in genes: return genes['DME'] elif 'SCE'",
"best: organism = best # for readability try: fillData(mol_weights, ec_number, organism, address) except",
"estimated molecular weights of enzymes. ec_number : string genes : list Addresses of",
"brenda_parameters[bigg_id][0] optimized_bigg = {} for k, v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, [])",
"'vertebrates' if loop == 'vertebrates': loop = 'csm' if loop == 'csm': searching",
"del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit",
"finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit",
"require list mol_weights[ec_number] = {} print('Currently processing BiGG id: ' + ec_number) mol_weights[ec_number]['bigg",
"{} if len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda",
"set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else: loop = 'vertebrates' if loop == 'vertebrates':",
"ec_number, genes, loop) searching = False except HTTPError as err: if err.code ==",
"Pool from urllib.error import HTTPError from DataTreatment import openJson, write mammals = ['HSA',",
"brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {} for k, v in simplified_brenda.items(): optimized_bigg[v]",
"mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get())",
"model organism genes. Organisms phylogenetically closer to Cricetulus griseus are preferred, but they",
"searches 'sequentially'. It returns the best available model organism genes. Organisms phylogenetically closer",
"mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else: loop = 'vertebrates' if loop",
"= {} for k, v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter",
"'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS',",
"'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO',",
"key: value pair is organism: address loop : string Indicates the highest potential",
"if loop == 'vertebrates': loop = 'csm' break if loop == 'csm': searching",
"HTTPError as err: if err.code == 404: pass else: for gene in best:",
"loop == 'csm': if 'DME' in genes: return genes['DME'] elif 'SCE' in genes:",
"== 404: print('Excepted: No entry for ec number: '+ec_number) continue else: raise if",
"'+ec_number) continue else: raise if genes: loop = 'best' searching = True while",
"'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX',",
"counter % 4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter % 4 ==",
"loop == 'best': if 'CGE' in genes: return genes['CGE'] elif 'MMU' in genes:",
"mw_3.get()) mol_weights_to_write = {} for ec_number in mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']:",
"the correct loop of returnBestAddress based on best potential genes matches. Parameters ----------",
"enzyme entry. This function searches 'sequentially'. It returns the best available model organism",
"best: if loop == 'best': loop = 'mammals' break if loop == 'mammals':",
"simple models\" if loop == 'csm': if 'DME' in genes: return genes['DME'] elif",
"pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,))",
"address) except HTTPError as err: if err.code == 404: pass else: for gene",
"Returns ------- dict key: ec number. value: all collected data in program by",
"each multiprocessing.process. Parameters ---------- bigg_ids : dict key: ec_number. value: corresponding bigg ids.",
"contain estimated molecular weights of enzymes. ec_number : string genes : list Addresses",
"'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU',",
"genes: return genes['MMU'] elif 'RNO' in genes: return genes['RNO'] elif 'HSA' in genes:",
"HTTPError as err: if err.code == 404: print('Excepted: No entry for ec number:",
"genes. Organisms phylogenetically closer to Cricetulus griseus are preferred, but they are chosen",
"genes corresponding to ec number. loop : string \"\"\" searching = True while",
"'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE',",
"ec_number. value: corresponding bigg ids. del_ec : list empty list which is appended",
"== 'csm': searching = False return None searching = False mol_weights[ec_number]['weights'] = []",
"mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for",
"== 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter % 4 == 1: sub_dict_2[ec_number] =",
"mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] = {} mol_weights_to_write[bigg_id]['ec_number'] = ec_number mol_weights_to_write[bigg_id].update(mol_weights[ec_number])",
": string Indicates the highest potential group of matching organisms to search in.",
"in del_ec1: mw_1.pop(ec, None) for ec in del_ec2: mw_2.pop(ec, None) for ec in",
"'vertebrates' break if loop == 'vertebrates': loop = 'csm' break if loop ==",
"{} print('Currently processing BiGG id: ' + ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try:",
"list which is appended to here containing depicrated ec numbers Returns ------- dict",
"in genes: return genes['CGE'] elif 'MMU' in genes: return genes['MMU'] elif 'RNO' in",
"'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO',",
"program. ec_number : string enzyme classification number used to organize data. address :",
"+ address) sequence = CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism,",
"if loop == 'best': if 'CGE' in genes: return genes['CGE'] elif 'MMU' in",
"'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for available genes matching",
"openJson, write mammals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO',",
"404: print('Excepted: No entry for ec number: '+ec_number) continue else: raise if genes:",
": string \"\"\" searching = True while searching: best = returnBestAddress(genes, loop) if",
"return genes['MMU'] elif 'RNO' in genes: return genes['RNO'] elif 'HSA' in genes: return",
"all collected data in program by this process. \"\"\" try: mol_weights = {}",
"'best': loop = 'mammals' if loop == 'mammals': loop = 'vertebrates' if loop",
"It returns the best available model organism genes. Organisms phylogenetically closer to Cricetulus",
"as pool: del_ec1 = [] del_ec2 = [] del_ec3 = [] del_ec4 =",
"ids'] = bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError as err: if err.code",
"Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for ec_number in mol_weights: for",
"except TypeError as err: if loop == 'best': loop = 'mammals' if loop",
"= [] if loop == 'best' or loop == 'csm': for address in",
"if bool(mammal_match): return mammal_match else: loop = 'vertebrates' if loop == 'vertebrates': animal_match",
"= 'mammals' if loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match",
"'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO',",
"'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ',",
"'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals = ['HSA',",
"del_ec2 = [] del_ec3 = [] del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1,",
"loopHandler(mol_weights, ec_number, genes, loop) searching = False except HTTPError as err: if err.code",
"in best[gene]: organism = best[gene] # for readability try: fillData(mol_weights, ec_number, organism, address)",
"list. will contain estimated molecular weights of enzymes. ec_number : string genes :",
"dict object containing all information collected by program. ec_number : string enzyme classification",
"in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {} for k, v in simplified_brenda.items():",
"'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA',",
"for bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {} for k, v",
"0 for ec_number in optimized_bigg: if counter % 4 == 0: sub_dict_1[ec_number] =",
"corresponding bigg ids. del_ec : list empty list which is appended to here",
"'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS',",
"for \"common simple models\" if loop == 'csm': if 'DME' in genes: return",
"loop == 'csm': searching = False return None searching = False mol_weights[ec_number]['weights'] =",
"organism code. value: gene addresses for enzyme and organism \"\"\" if loop ==",
"as CS from multiprocessing import Pool from urllib.error import HTTPError from DataTreatment import",
"while searching: try: loopHandler(mol_weights, ec_number, genes, loop) searching = False except HTTPError as",
"organisms to search in. Returns ------- dict key: kegg organism code. value: gene",
"Pool(processes=4) as pool: del_ec1 = [] del_ec2 = [] del_ec3 = [] del_ec4",
"loop == 'mammals': loop = 'vertebrates' break if loop == 'vertebrates': loop =",
"weights of enzymes. ec_number : string genes : list Addresses of genes corresponding",
"best potential genes matches. Parameters ---------- mol_weights : list empty list. will contain",
"= [] del_ec2 = [] del_ec3 = [] del_ec4 = [] mw_1 =",
"id and AA sequence. Parameters ---------- mol_weights : dict object containing all information",
"def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by each multiprocessing.process. Parameters ---------- bigg_ids :",
"'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC',",
"utf-8 -*- \"\"\" Created on Wed Jan 24 16:03:28 2018 @author: dimitricoukos Test:",
"ec_number in optimized_bigg: if counter % 4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if",
"uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by each multiprocessing.process. Parameters ----------",
"in genes: return genes['SCE'] elif 'ECO' in genes: return genes['ECO'] def loopHandler(mol_weights, ec_number,",
"= pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for ec in del_ec1: mw_1.pop(ec, None) for",
"loop == 'best': loop = 'mammals' if loop == 'mammals': loop = 'vertebrates'",
"mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for ec_number in mol_weights: for bigg_id",
"approximation. A detailed study of the phylogenetic tree has not been done for",
"going sequentially increases both readability and efficiency. Parameters ---------- genes : dict key:",
"ec numbers Returns ------- dict key: ec number. value: all collected data in",
"Returns ------- dict key: kegg organism code. value: gene addresses for enzyme and",
"python3 # -*- coding: utf-8 -*- \"\"\" Created on Wed Jan 24 16:03:28",
"loop == 'csm': for address in best: organism = best # for readability",
"= optimized_bigg[ec_number] if counter % 4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter =",
"for ec in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv)",
"None searching = False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = [] if loop ==",
"process. \"\"\" try: mol_weights = {} for ec_number in bigg_ids: # WARNING: joblib",
"'csm': searching = False except TypeError as err: if loop == 'best': loop",
"searching = False return None searching = False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] =",
"= optimized_bigg[ec_number] if counter % 4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter",
"bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] = {} mol_weights_to_write[bigg_id]['ec_number'] = ec_number mol_weights_to_write[bigg_id].update(mol_weights[ec_number]) write('JSONs/molecular_weights.json', mol_weights_to_write)",
"4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter % 4 == 1: sub_dict_2[ec_number]",
"'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR',",
"loop == 'mammals': loop = 'vertebrates' if loop == 'vertebrates': loop = 'csm'",
"in del_ec3: mw_3.pop(ec, None) for ec in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get())",
"2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter % 4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number]",
"optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0 for ec_number in optimized_bigg: if counter %",
"% 4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter % 4 == 2:",
"'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for",
"= pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for ec",
"sub_dict_4 = {} mol_weights = {} if len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json')",
"= bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError as err: if err.code ==",
"'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD',",
"1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for ec_number in",
"ec in del_ec2: mw_2.pop(ec, None) for ec in del_ec3: mw_3.pop(ec, None) for ec",
"return mammal_match else: loop = 'vertebrates' if loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals)",
"correct loop of returnBestAddress based on best potential genes matches. Parameters ---------- mol_weights",
"sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence = CS.kegggene_to_sequence(organism, address) weight",
"as err: if err.code == 404: print('Excepted: No entry for ec number: '+ec_number)",
"'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU',",
"'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def",
"they are chosen by approximation. A detailed study of the phylogenetic tree has",
"simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0 for ec_number in optimized_bigg:",
"import HTTPError from DataTreatment import openJson, write mammals = ['HSA', 'PTR', 'PPS', 'GGO',",
"= 'csm' # Stands for \"common simple models\" if loop == 'csm': if",
"try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError as err: if err.code == 404: print('Excepted:",
"[] mol_weights[ec_number]['uniprot_ids'] = [] if loop == 'best' or loop == 'csm': for",
"loop of returnBestAddress based on best potential genes matches. Parameters ---------- mol_weights :",
"openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {} for bigg_id in brenda_parameters: simplified_brenda[bigg_id]",
"'best': loop = 'mammals' break if loop == 'mammals': loop = 'vertebrates' break",
"string gene address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence",
"genes, loop): \"\"\"Calls the correct loop of returnBestAddress based on best potential genes",
"optimized_bigg[ec_number] counter = counter + 1 try: with Pool(processes=4) as pool: del_ec1 =",
"Indicates the highest potential group of matching organisms to search in. Returns -------",
"(sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close()",
"for this project. Hopefully going sequentially increases both readability and efficiency. Parameters ----------",
"group of matching organisms to search in. Returns ------- dict key: kegg organism",
"if loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else: loop",
"mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess,",
"mammal_match else: loop = 'vertebrates' if loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if",
": dict object containing all information collected by program. ec_number : string enzyme",
"write mammals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB',",
"'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for available genes matching kegg enzyme entry. This",
"return genes['CGE'] elif 'MMU' in genes: return genes['MMU'] elif 'RNO' in genes: return",
"list Addresses of genes corresponding to ec number. loop : string \"\"\" searching",
"= openJson(sys.argv[1]) simplified_brenda = {} for bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg",
"genes: return genes['CGE'] elif 'MMU' in genes: return genes['MMU'] elif 'RNO' in genes:",
"used to organize data. address : string gene address for sequence lookup. \"\"\"",
"= False finally: return mol_weights if __name__ == '__main__': sub_dict_1 = {} sub_dict_2",
"'__main__': sub_dict_1 = {} sub_dict_2 = {} sub_dict_3 = {} sub_dict_4 = {}",
"del_ec1: mw_1.pop(ec, None) for ec in del_ec2: mw_2.pop(ec, None) for ec in del_ec3:",
"CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main",
"\"\"\"Calls the correct loop of returnBestAddress based on best potential genes matches. Parameters",
"if genes: loop = 'best' searching = True while searching: try: loopHandler(mol_weights, ec_number,",
"of enzymes. ec_number : string genes : list Addresses of genes corresponding to",
"if loop == 'csm': searching = False return None searching = False mol_weights[ec_number]['weights']",
"organism, address) except HTTPError as err: if err.code == 404: pass else: for",
"= False return None searching = False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = []",
"'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop):",
"molecular weights of enzymes. ec_number : string genes : list Addresses of genes",
"else: loop = 'csm' # Stands for \"common simple models\" if loop ==",
"RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services as CS from multiprocessing import",
"cobra_services as CS from multiprocessing import Pool from urllib.error import HTTPError from DataTreatment",
"in optimized_bigg: if counter % 4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter",
"for ec in del_ec1: mw_1.pop(ec, None) for ec in del_ec2: mw_2.pop(ec, None) for",
"by this process. \"\"\" try: mol_weights = {} for ec_number in bigg_ids: #",
"= optimized_bigg[ec_number] if counter % 4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter",
"loop == 'vertebrates': loop = 'csm' break if loop == 'csm': searching =",
"'vertebrates': loop = 'csm' if loop == 'csm': searching = False finally: return",
"'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR',",
"genes['HSA'] else: loop = 'mammals' if loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if",
"'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV',",
"list empty list. will contain estimated molecular weights of enzymes. ec_number : string",
"err: if err.code == 404 and loop == 'csm': searching = False except",
"'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for available",
"= {} for bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {} for",
"1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter % 4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number]",
"(sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4",
"in del_ec2: mw_2.pop(ec, None) for ec in del_ec3: mw_3.pop(ec, None) for ec in",
"'mammals': loop = 'vertebrates' if loop == 'vertebrates': loop = 'csm' if loop",
"False except TypeError as err: if loop == 'best': loop = 'mammals' if",
"empty list which is appended to here containing depicrated ec numbers Returns -------",
"bigg_ids: # WARNING: joblib may require list mol_weights[ec_number] = {} print('Currently processing BiGG",
"address in best[gene]: organism = best[gene] # for readability try: fillData(mol_weights, ec_number, organism,",
"'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON',",
"mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by each multiprocessing.process. Parameters ---------- bigg_ids : dict",
"in genes: return genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the correct loop",
"line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services as CS from",
"\"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence = CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence)",
"'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM',",
"with Pool(processes=4) as pool: del_ec1 = [] del_ec2 = [] del_ec3 = []",
"= 'mammals' break if loop == 'mammals': loop = 'vertebrates' break if loop",
"= {} if len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1])",
"available genes matching kegg enzyme entry. This function searches 'sequentially'. It returns the",
"'csm': if 'DME' in genes: return genes['DME'] elif 'SCE' in genes: return genes['SCE']",
"pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for ec in del_ec1: mw_1.pop(ec, None) for ec",
"{} sub_dict_3 = {} sub_dict_4 = {} mol_weights = {} if len(sys.argv) ==",
"in command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services as",
"del_ec : list empty list which is appended to here containing depicrated ec",
"pool.close() pool.join() for ec in del_ec1: mw_1.pop(ec, None) for ec in del_ec2: mw_2.pop(ec,",
"---------- genes : dict key: value pair is organism: address loop : string",
"break if loop == 'vertebrates': loop = 'csm' break if loop == 'csm':",
"== 'csm': searching = False finally: return mol_weights if __name__ == '__main__': sub_dict_1",
": list empty list. will contain estimated molecular weights of enzymes. ec_number :",
"key: kegg organism code. value: gene addresses for enzyme and organism \"\"\" if",
"openJson(sys.argv[1]) simplified_brenda = {} for bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg =",
"'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ',",
"@author: dimitricoukos Test: in command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys",
"organism, address) except HTTPError as err: if err.code == 404: pass def fillData(mol_weights,",
": string gene address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address)",
"WARNING: joblib may require list mol_weights[ec_number] = {} print('Currently processing BiGG id: '",
"mol_weights : list empty list. will contain estimated molecular weights of enzymes. ec_number",
"# for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError as err: if",
"continue else: raise if genes: loop = 'best' searching = True while searching:",
"+ ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError as",
"animals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC',",
"in best: organism = best # for readability try: fillData(mol_weights, ec_number, organism, address)",
"counter % 4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter + 1",
"== 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter % 4 == 2: sub_dict_3[ec_number] =",
"# Stands for \"common simple models\" if loop == 'csm': if 'DME' in",
"'ECO' in genes: return genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the correct",
"loop) if not best: if loop == 'best': loop = 'mammals' break if",
"\"\"\"Main function called by each multiprocessing.process. Parameters ---------- bigg_ids : dict key: ec_number.",
"closer to Cricetulus griseus are preferred, but they are chosen by approximation. A",
"genes: loop = 'best' searching = True while searching: try: loopHandler(mol_weights, ec_number, genes,",
"for enzyme and organism \"\"\" if loop == 'best': if 'CGE' in genes:",
"enzyme and organism \"\"\" if loop == 'best': if 'CGE' in genes: return",
"gene in best: for address in best[gene]: organism = best[gene] # for readability",
"genes['DME'] elif 'SCE' in genes: return genes['SCE'] elif 'ECO' in genes: return genes['ECO']",
"ec in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) >",
"genes: return genes['RNO'] elif 'HSA' in genes: return genes['HSA'] else: loop = 'mammals'",
"'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI',",
"'RNO' in genes: return genes['RNO'] elif 'HSA' in genes: return genes['HSA'] else: loop",
"has not been done for this project. Hopefully going sequentially increases both readability",
"= CS.ecnumber_to_genes(ec_number) except HTTPError as err: if err.code == 404: print('Excepted: No entry",
"increases both readability and efficiency. Parameters ---------- genes : dict key: value pair",
"return genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the correct loop of returnBestAddress",
"string genes : list Addresses of genes corresponding to ec number. loop :",
"genes['MMU'] elif 'RNO' in genes: return genes['RNO'] elif 'HSA' in genes: return genes['HSA']",
"information collected by program. ec_number : string enzyme classification number used to organize",
"griseus are preferred, but they are chosen by approximation. A detailed study of",
"by approximation. A detailed study of the phylogenetic tree has not been done",
"counter + 1 try: with Pool(processes=4) as pool: del_ec1 = [] del_ec2 =",
"CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot",
"'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals = ['HSA', 'PTR',",
"highest potential group of matching organisms to search in. Returns ------- dict key:",
"number used to organize data. address : string gene address for sequence lookup.",
"bigg_ids : dict key: ec_number. value: corresponding bigg ids. del_ec : list empty",
"= {} print('Currently processing BiGG id: ' + ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number]",
"No entry for ec number: '+ec_number) continue else: raise if genes: loop =",
"numbers Returns ------- dict key: ec number. value: all collected data in program",
"loop): \"\"\"Calls the correct loop of returnBestAddress based on best potential genes matches.",
"which is appended to here containing depicrated ec numbers Returns ------- dict key:",
"'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ',",
"key: ec_number. value: corresponding bigg ids. del_ec : list empty list which is",
"4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter + 1 try: with",
"= 'vertebrates' if loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match",
"'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY',",
"sub_dict_2 = {} sub_dict_3 = {} sub_dict_4 = {} mol_weights = {} if",
"entry. This function searches 'sequentially'. It returns the best available model organism genes.",
"if bool(animal_match): return animal_match else: loop = 'csm' # Stands for \"common simple",
"'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA',",
"loop == 'csm': searching = False except TypeError as err: if loop ==",
"is organism: address loop : string Indicates the highest potential group of matching",
"string enzyme classification number used to organize data. address : string gene address",
"'CGE' in genes: return genes['CGE'] elif 'MMU' in genes: return genes['MMU'] elif 'RNO'",
"'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for available genes matching kegg enzyme entry.",
"best # for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError as err:",
"to ec number. loop : string \"\"\" searching = True while searching: best",
"addresses for enzyme and organism \"\"\" if loop == 'best': if 'CGE' in",
"= [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3",
"== 404: pass else: for gene in best: for address in best[gene]: organism",
"'mammals' if loop == 'mammals': loop = 'vertebrates' if loop == 'vertebrates': loop",
"pool: del_ec1 = [] del_ec2 = [] del_ec3 = [] del_ec4 = []",
"function searches 'sequentially'. It returns the best available model organism genes. Organisms phylogenetically",
"sub_dict_3 = {} sub_dict_4 = {} mol_weights = {} if len(sys.argv) == 1:",
"'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG',",
"counter % 4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter % 4 ==",
"(sub_dict_4, del_ec4,)) pool.close() pool.join() for ec in del_ec1: mw_1.pop(ec, None) for ec in",
"'MMU' in genes: return genes['MMU'] elif 'RNO' in genes: return genes['RNO'] elif 'HSA'",
"'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU',",
"dimitricoukos Test: in command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import",
"mammals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC',",
"'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR',",
"sequentially increases both readability and efficiency. Parameters ---------- genes : dict key: value",
"for address in best: organism = best # for readability try: fillData(mol_weights, ec_number,",
"sequence = CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if",
"write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for ec_number in mol_weights: for bigg_id in",
"ec_number, genes, loop): \"\"\"Calls the correct loop of returnBestAddress based on best potential",
"from urllib.error import HTTPError from DataTreatment import openJson, write mammals = ['HSA', 'PTR',",
"'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA',",
"= CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec):",
"mol_weights[ec_number] = {} print('Currently processing BiGG id: ' + ec_number) mol_weights[ec_number]['bigg ids'] =",
"== 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else: loop = 'csm'",
"== 'best': loop = 'mammals' break if loop == 'mammals': loop = 'vertebrates'",
"for ec in del_ec3: mw_3.pop(ec, None) for ec in del_ec4: mw_4.pop(ec, None) finally:",
"gene addresses for enzyme and organism \"\"\" if loop == 'best': if 'CGE'",
"'csm': searching = False finally: return mol_weights if __name__ == '__main__': sub_dict_1 =",
"mw_1.pop(ec, None) for ec in del_ec2: mw_2.pop(ec, None) for ec in del_ec3: mw_3.pop(ec,",
"'SCE' in genes: return genes['SCE'] elif 'ECO' in genes: return genes['ECO'] def loopHandler(mol_weights,",
"if err.code == 404: pass else: for gene in best: for address in",
"for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence = CS.kegggene_to_sequence(organism, address)",
"matching organisms to search in. Returns ------- dict key: kegg organism code. value:",
"\"\"\" searching = True while searching: best = returnBestAddress(genes, loop) if not best:",
"organism: address loop : string Indicates the highest potential group of matching organisms",
"ids. del_ec : list empty list which is appended to here containing depicrated",
"'mammals' if loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else:",
"{} for bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {} for k,",
"---------- mol_weights : list empty list. will contain estimated molecular weights of enzymes.",
"print('Currently processing BiGG id: ' + ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes",
"0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter % 4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number]",
"'MDO', 'SHR', 'OAA'] animals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF',",
"if loop == 'best': loop = 'mammals' if loop == 'mammals': loop =",
"[] del_ec3 = [] del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2",
"loop = 'best' searching = True while searching: try: loopHandler(mol_weights, ec_number, genes, loop)",
"if not best: if loop == 'best': loop = 'mammals' break if loop",
"else: for gene in best: for address in best[gene]: organism = best[gene] #",
"'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM',",
"sub_dict_1 = {} sub_dict_2 = {} sub_dict_3 = {} sub_dict_4 = {} mol_weights",
"except HTTPError as err: if err.code == 404: print('Excepted: No entry for ec",
": list Addresses of genes corresponding to ec number. loop : string \"\"\"",
"'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI',",
"'csm' if loop == 'csm': searching = False finally: return mol_weights if __name__",
"for gene in best: for address in best[gene]: organism = best[gene] # for",
"ec number. value: all collected data in program by this process. \"\"\" try:",
"del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join()",
"to here containing depicrated ec numbers Returns ------- dict key: ec number. value:",
"'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD',",
"'csm' # Stands for \"common simple models\" if loop == 'csm': if 'DME'",
"None) for ec in del_ec2: mw_2.pop(ec, None) for ec in del_ec3: mw_3.pop(ec, None)",
"= 'vertebrates' if loop == 'vertebrates': loop = 'csm' if loop == 'csm':",
"This function searches 'sequentially'. It returns the best available model organism genes. Organisms",
"searching = False finally: return mol_weights if __name__ == '__main__': sub_dict_1 = {}",
"24 16:03:28 2018 @author: dimitricoukos Test: in command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json'",
"Parameters ---------- bigg_ids : dict key: ec_number. value: corresponding bigg ids. del_ec :",
"return None searching = False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = [] if loop",
"True while searching: try: loopHandler(mol_weights, ec_number, genes, loop) searching = False except HTTPError",
"del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 =",
"ec_number, organism, address) except HTTPError as err: if err.code == 404: pass def",
"'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA',",
"try: with Pool(processes=4) as pool: del_ec1 = [] del_ec2 = [] del_ec3 =",
"= True while searching: best = returnBestAddress(genes, loop) if not best: if loop",
"if counter % 4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter % 4",
"'SHR', 'OAA'] animals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO',",
"'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB',",
"sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter % 4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter",
"if loop == 'mammals': loop = 'vertebrates' if loop == 'vertebrates': loop =",
"'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE',",
"are preferred, but they are chosen by approximation. A detailed study of the",
"value: corresponding bigg ids. del_ec : list empty list which is appended to",
"from multiprocessing import Pool from urllib.error import HTTPError from DataTreatment import openJson, write",
"this process. \"\"\" try: mol_weights = {} for ec_number in bigg_ids: # WARNING:",
"optimized_bigg[ec_number] if counter % 4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter",
"== '__main__': sub_dict_1 = {} sub_dict_2 = {} sub_dict_3 = {} sub_dict_4 =",
"uniprot id and AA sequence. Parameters ---------- mol_weights : dict object containing all",
"searching: try: loopHandler(mol_weights, ec_number, genes, loop) searching = False except HTTPError as err:",
"else: raise if genes: loop = 'best' searching = True while searching: try:",
"== 'mammals': loop = 'vertebrates' if loop == 'vertebrates': loop = 'csm' if",
"AA sequence. Parameters ---------- mol_weights : dict object containing all information collected by",
"---------- bigg_ids : dict key: ec_number. value: corresponding bigg ids. del_ec : list",
"A detailed study of the phylogenetic tree has not been done for this",
"mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,)) mw_4 = pool.apply_async(mainSubprocess,",
"loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the correct loop of returnBestAddress based on best",
"mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json',",
"entry for ec number: '+ec_number) continue else: raise if genes: loop = 'best'",
"ec_number in bigg_ids: # WARNING: joblib may require list mol_weights[ec_number] = {} print('Currently",
"2018 @author: dimitricoukos Test: in command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import",
"dict key: value pair is organism: address loop : string Indicates the highest",
"loop : string Indicates the highest potential group of matching organisms to search",
"loop == 'best' or loop == 'csm': for address in best: organism =",
"potential group of matching organisms to search in. Returns ------- dict key: kegg",
"1 try: with Pool(processes=4) as pool: del_ec1 = [] del_ec2 = [] del_ec3",
"---------- mol_weights : dict object containing all information collected by program. ec_number :",
"'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE',",
"while searching: best = returnBestAddress(genes, loop) if not best: if loop == 'best':",
"None) for ec in del_ec3: mw_3.pop(ec, None) for ec in del_ec4: mw_4.pop(ec, None)",
"{} sub_dict_4 = {} mol_weights = {} if len(sys.argv) == 1: brenda_parameters =",
"'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR',",
"if err.code == 404 and loop == 'csm': searching = False except TypeError",
"matching kegg enzyme entry. This function searches 'sequentially'. It returns the best available",
"\"\"\" if loop == 'best': if 'CGE' in genes: return genes['CGE'] elif 'MMU'",
"= 'csm' if loop == 'csm': searching = False finally: return mol_weights if",
"else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {} for bigg_id in brenda_parameters: simplified_brenda[bigg_id] =",
"to Cricetulus griseus are preferred, but they are chosen by approximation. A detailed",
"dict key: ec number. value: all collected data in program by this process.",
"if loop == 'best': loop = 'mammals' break if loop == 'mammals': loop",
"'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH', 'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS',",
"TypeError as err: if loop == 'best': loop = 'mammals' if loop ==",
"pass def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg for enzyme uniprot id and",
"mol_weights : dict object containing all information collected by program. ec_number : string",
"[] del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2,",
"enzymes. ec_number : string genes : list Addresses of genes corresponding to ec",
"del_ec1 = [] del_ec2 = [] del_ec3 = [] del_ec4 = [] mw_1",
"'best' searching = True while searching: try: loopHandler(mol_weights, ec_number, genes, loop) searching =",
"'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals",
"loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else: loop =",
"returnBestAddress(genes, loop) if not best: if loop == 'best': loop = 'mammals' break",
"'mammals' break if loop == 'mammals': loop = 'vertebrates' break if loop ==",
"ec_number in mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] = {} mol_weights_to_write[bigg_id]['ec_number'] =",
"as err: if loop == 'best': loop = 'mammals' if loop == 'mammals':",
"for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] = {} mol_weights_to_write[bigg_id]['ec_number'] = ec_number mol_weights_to_write[bigg_id].update(mol_weights[ec_number]) write('JSONs/molecular_weights.json',",
"import sys import cobra_services as CS from multiprocessing import Pool from urllib.error import",
"kegg for enzyme uniprot id and AA sequence. Parameters ---------- mol_weights : dict",
"all information collected by program. ec_number : string enzyme classification number used to",
"ec_number : string genes : list Addresses of genes corresponding to ec number.",
"Parameters ---------- mol_weights : list empty list. will contain estimated molecular weights of",
"'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches",
"optimized_bigg[ec_number] if counter % 4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter %",
": string genes : list Addresses of genes corresponding to ec number. loop",
"'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO',",
"genes matching kegg enzyme entry. This function searches 'sequentially'. It returns the best",
"'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA',",
"if 'CGE' in genes: return genes['CGE'] elif 'MMU' in genes: return genes['MMU'] elif",
"value: all collected data in program by this process. \"\"\" try: mol_weights =",
"genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the correct loop of returnBestAddress based",
"in program by this process. \"\"\" try: mol_weights = {} for ec_number in",
"HTTPError as err: if err.code == 404: pass def fillData(mol_weights, ec_number, organism, address):",
"True while searching: best = returnBestAddress(genes, loop) if not best: if loop ==",
"loop = 'mammals' break if loop == 'mammals': loop = 'vertebrates' break if",
"'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU',",
"tree has not been done for this project. Hopefully going sequentially increases both",
"containing depicrated ec numbers Returns ------- dict key: ec number. value: all collected",
"for ec_number in mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] = {} mol_weights_to_write[bigg_id]['ec_number']",
"= False except TypeError as err: if loop == 'best': loop = 'mammals'",
"bool(animal_match): return animal_match else: loop = 'csm' # Stands for \"common simple models\"",
"for ec in del_ec2: mw_2.pop(ec, None) for ec in del_ec3: mw_3.pop(ec, None) for",
"'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else: loop = 'csm' #",
"optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0 for ec_number in optimized_bigg: if",
"address : string gene address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' +",
"value: gene addresses for enzyme and organism \"\"\" if loop == 'best': if",
"number. value: all collected data in program by this process. \"\"\" try: mol_weights",
"{} for ec_number in bigg_ids: # WARNING: joblib may require list mol_weights[ec_number] =",
"mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = [] if loop == 'best' or loop ==",
"if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {}",
"brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {} for bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0]",
"== 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else: loop = 'vertebrates'",
"best[gene] # for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError as err:",
"Jan 24 16:03:28 2018 @author: dimitricoukos Test: in command line: python RetrieveUniProt.py 'Unit",
"Hopefully going sequentially increases both readability and efficiency. Parameters ---------- genes : dict",
"value pair is organism: address loop : string Indicates the highest potential group",
"Addresses of genes corresponding to ec number. loop : string \"\"\" searching =",
"as err: if err.code == 404: pass else: for gene in best: for",
"by program. ec_number : string enzyme classification number used to organize data. address",
"from DataTreatment import openJson, write mammals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE',",
"brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {} for bigg_id in",
"mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence = CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight)",
"if loop == 'csm': searching = False finally: return mol_weights if __name__ ==",
"raise if genes: loop = 'best' searching = True while searching: try: loopHandler(mol_weights,",
"DataTreatment import openJson, write mammals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC',",
"'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA',",
"'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA'] animals =",
"'DME' in genes: return genes['DME'] elif 'SCE' in genes: return genes['SCE'] elif 'ECO'",
"break if loop == 'csm': searching = False return None searching = False",
"'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA',",
"mol_weights = {} for ec_number in bigg_ids: # WARNING: joblib may require list",
"ec number. loop : string \"\"\" searching = True while searching: best =",
"import cobra_services as CS from multiprocessing import Pool from urllib.error import HTTPError from",
"loop): \"\"\"Searches for available genes matching kegg enzyme entry. This function searches 'sequentially'.",
": dict key: value pair is organism: address loop : string Indicates the",
"% 4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter + 1 try:",
"Wed Jan 24 16:03:28 2018 @author: dimitricoukos Test: in command line: python RetrieveUniProt.py",
"'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU',",
"False return None searching = False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = [] if",
"= ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ',",
"list empty list which is appended to here containing depicrated ec numbers Returns",
"'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI',",
"# WARNING: joblib may require list mol_weights[ec_number] = {} print('Currently processing BiGG id:",
"list mol_weights[ec_number] = {} print('Currently processing BiGG id: ' + ec_number) mol_weights[ec_number]['bigg ids']",
"loop) searching = False except HTTPError as err: if err.code == 404 and",
"the best available model organism genes. Organisms phylogenetically closer to Cricetulus griseus are",
"def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the correct loop of returnBestAddress based on",
"based on best potential genes matches. Parameters ---------- mol_weights : list empty list.",
"optimized_bigg[v].append(k) counter = 0 for ec_number in optimized_bigg: if counter % 4 ==",
"'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR',",
"object containing all information collected by program. ec_number : string enzyme classification number",
"ec_number : string enzyme classification number used to organize data. address : string",
"in genes: return genes['DME'] elif 'SCE' in genes: return genes['SCE'] elif 'ECO' in",
"{} sub_dict_2 = {} sub_dict_3 = {} sub_dict_4 = {} mol_weights = {}",
"phylogenetically closer to Cricetulus griseus are preferred, but they are chosen by approximation.",
"ec in del_ec1: mw_1.pop(ec, None) for ec in del_ec2: mw_2.pop(ec, None) for ec",
"== 'csm': if 'DME' in genes: return genes['DME'] elif 'SCE' in genes: return",
"'sequentially'. It returns the best available model organism genes. Organisms phylogenetically closer to",
"loop = 'csm' if loop == 'csm': searching = False finally: return mol_weights",
"'HSA' in genes: return genes['HSA'] else: loop = 'mammals' if loop == 'mammals':",
"urllib.error import HTTPError from DataTreatment import openJson, write mammals = ['HSA', 'PTR', 'PPS',",
"number. loop : string \"\"\" searching = True while searching: best = returnBestAddress(genes,",
"Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services as CS from multiprocessing import Pool from",
"== 'best' or loop == 'csm': for address in best: organism = best",
"id: ' + ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except",
"= 'best' searching = True while searching: try: loopHandler(mol_weights, ec_number, genes, loop) searching",
"loop = 'mammals' if loop == 'mammals': loop = 'vertebrates' if loop ==",
"if len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda =",
"'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services as CS from multiprocessing import Pool",
"if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by each multiprocessing.process. Parameters",
"'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK']",
"16:03:28 2018 @author: dimitricoukos Test: in command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\"",
"['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU',",
"this project. Hopefully going sequentially increases both readability and efficiency. Parameters ---------- genes",
"simplified_brenda = {} for bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {}",
"'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA',",
"mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError as err: if",
"optimized_bigg[ec_number] if counter % 4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter %",
"pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3, del_ec3,))",
"'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA',",
"except HTTPError as err: if err.code == 404 and loop == 'csm': searching",
"searching = True while searching: best = returnBestAddress(genes, loop) if not best: if",
"'csm': searching = False return None searching = False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids']",
"data. address : string gene address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':'",
"to search in. Returns ------- dict key: kegg organism code. value: gene addresses",
"False finally: return mol_weights if __name__ == '__main__': sub_dict_1 = {} sub_dict_2 =",
"'SGH', 'IPU', 'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS',",
"is appended to here containing depicrated ec numbers Returns ------- dict key: ec",
"in genes: return genes['HSA'] else: loop = 'mammals' if loop == 'mammals': mammal_match",
"try: mol_weights = {} for ec_number in bigg_ids: # WARNING: joblib may require",
"organism = best[gene] # for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError",
"== 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {} for",
"'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV',",
"if loop == 'best' or loop == 'csm': for address in best: organism",
"project. Hopefully going sequentially increases both readability and efficiency. Parameters ---------- genes :",
"both readability and efficiency. Parameters ---------- genes : dict key: value pair is",
"1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {} for bigg_id",
"mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json',",
"err: if err.code == 404: pass def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg",
"del_ec4,)) pool.close() pool.join() for ec in del_ec1: mw_1.pop(ec, None) for ec in del_ec2:",
"= False except HTTPError as err: if err.code == 404 and loop ==",
"sequence. Parameters ---------- mol_weights : dict object containing all information collected by program.",
"animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else: loop = 'csm' # Stands",
"del_ec): \"\"\"Main function called by each multiprocessing.process. Parameters ---------- bigg_ids : dict key:",
"Stands for \"common simple models\" if loop == 'csm': if 'DME' in genes:",
"ec_number, organism, address) except HTTPError as err: if err.code == 404: pass else:",
"= optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0 for ec_number in optimized_bigg: if counter",
"== 'csm': searching = False except TypeError as err: if loop == 'best':",
"counter % 4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter % 4 ==",
"mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write",
"\"\"\"Searches for available genes matching kegg enzyme entry. This function searches 'sequentially'. It",
"on best potential genes matches. Parameters ---------- mol_weights : list empty list. will",
"the highest potential group of matching organisms to search in. Returns ------- dict",
"return genes['SCE'] elif 'ECO' in genes: return genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop):",
"of returnBestAddress based on best potential genes matches. Parameters ---------- mol_weights : list",
"[] if loop == 'best' or loop == 'csm': for address in best:",
"appended to here containing depicrated ec numbers Returns ------- dict key: ec number.",
"will contain estimated molecular weights of enzymes. ec_number : string genes : list",
"dict key: ec_number. value: corresponding bigg ids. del_ec : list empty list which",
"potential genes matches. Parameters ---------- mol_weights : list empty list. will contain estimated",
"bigg_id in brenda_parameters: simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {} for k, v in",
"loop = 'mammals' if loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return",
"\"\"\" Created on Wed Jan 24 16:03:28 2018 @author: dimitricoukos Test: in command",
"sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter + 1 try: with Pool(processes=4) as pool:",
": dict key: ec_number. value: corresponding bigg ids. del_ec : list empty list",
"loop == 'vertebrates': loop = 'csm' if loop == 'csm': searching = False",
"for ec_number in optimized_bigg: if counter % 4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number]",
"set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else: loop = 'csm' # Stands for \"common",
"may require list mol_weights[ec_number] = {} print('Currently processing BiGG id: ' + ec_number)",
"been done for this project. Hopefully going sequentially increases both readability and efficiency.",
"'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK', 'LVE',",
"'best': if 'CGE' in genes: return genes['CGE'] elif 'MMU' in genes: return genes['MMU']",
"loop = 'csm' # Stands for \"common simple models\" if loop == 'csm':",
"key: ec number. value: all collected data in program by this process. \"\"\"",
"genes : list Addresses of genes corresponding to ec number. loop : string",
"return animal_match else: loop = 'csm' # Stands for \"common simple models\" if",
"not best: if loop == 'best': loop = 'mammals' break if loop ==",
"= openJson('JSONs/brenda_parameters.json') else: brenda_parameters = openJson(sys.argv[1]) simplified_brenda = {} for bigg_id in brenda_parameters:",
"genes = CS.ecnumber_to_genes(ec_number) except HTTPError as err: if err.code == 404: print('Excepted: No",
"= {} mol_weights = {} if len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else:",
"preferred, but they are chosen by approximation. A detailed study of the phylogenetic",
"== 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter + 1 try: with Pool(processes=4)",
"del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,))",
"detailed study of the phylogenetic tree has not been done for this project.",
"if loop == 'csm': if 'DME' in genes: return genes['DME'] elif 'SCE' in",
"lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence = CS.kegggene_to_sequence(organism, address) weight =",
"corresponding to ec number. loop : string \"\"\" searching = True while searching:",
"= 'mammals' if loop == 'mammals': loop = 'vertebrates' if loop == 'vertebrates':",
"mw_3.pop(ec, None) for ec in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get())",
"__name__ == '__main__': sub_dict_1 = {} sub_dict_2 = {} sub_dict_3 = {} sub_dict_4",
"= {} sub_dict_4 = {} mol_weights = {} if len(sys.argv) == 1: brenda_parameters",
"elif 'ECO' in genes: return genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the",
"3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter + 1 try: with Pool(processes=4) as",
"'TRU', 'TNG', 'LCO', 'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM',",
"== 'best': if 'CGE' in genes: return genes['CGE'] elif 'MMU' in genes: return",
"return genes['RNO'] elif 'HSA' in genes: return genes['HSA'] else: loop = 'mammals' if",
"search in. Returns ------- dict key: kegg organism code. value: gene addresses for",
"Test: in command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services",
"if counter % 4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter % 4",
"organism, address): \"\"\"Searches kegg for enzyme uniprot id and AA sequence. Parameters ----------",
"searching = False except HTTPError as err: if err.code == 404 and loop",
"optimized_bigg = {} for k, v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k)",
"\"common simple models\" if loop == 'csm': if 'DME' in genes: return genes['DME']",
"'NCC', 'MZE', 'OLA', 'XMA', 'NFU', 'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes,",
"searching = False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = [] if loop == 'best'",
"4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter % 4 == 3: sub_dict_4[ec_number]",
"== 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if counter % 4 == 3: sub_dict_4[ec_number] =",
"ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError as err:",
"== 'vertebrates': loop = 'csm' break if loop == 'csm': searching = False",
"best[gene]: organism = best[gene] # for readability try: fillData(mol_weights, ec_number, organism, address) except",
"fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg for enzyme uniprot id and AA sequence.",
"Parameters ---------- genes : dict key: value pair is organism: address loop :",
"except HTTPError as err: if err.code == 404: pass else: for gene in",
"are chosen by approximation. A detailed study of the phylogenetic tree has not",
"address) except HTTPError as err: if err.code == 404: pass def fillData(mol_weights, ec_number,",
"return genes['HSA'] else: loop = 'mammals' if loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals)",
"= returnBestAddress(genes, loop) if not best: if loop == 'best': loop = 'mammals'",
"program by this process. \"\"\" try: mol_weights = {} for ec_number in bigg_ids:",
"\"\"\"Searches kegg for enzyme uniprot id and AA sequence. Parameters ---------- mol_weights :",
"elif 'SCE' in genes: return genes['SCE'] elif 'ECO' in genes: return genes['ECO'] def",
"'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW',",
"finally: return mol_weights if __name__ == '__main__': sub_dict_1 = {} sub_dict_2 = {}",
"HTTPError from DataTreatment import openJson, write mammals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON',",
"'CLV', 'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA',",
"{} for ec_number in mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] = {}",
"------- dict key: kegg organism code. value: gene addresses for enzyme and organism",
"if 'DME' in genes: return genes['DME'] elif 'SCE' in genes: return genes['SCE'] elif",
"404: pass def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg for enzyme uniprot id",
"genes['SCE'] elif 'ECO' in genes: return genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls",
"address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence = CS.kegggene_to_sequence(organism,",
"optimized_bigg: if counter % 4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter %",
"'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE',",
"efficiency. Parameters ---------- genes : dict key: value pair is organism: address loop",
"called by each multiprocessing.process. Parameters ---------- bigg_ids : dict key: ec_number. value: corresponding",
"mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by each multiprocessing.process. Parameters ---------- bigg_ids",
"+ 1 try: with Pool(processes=4) as pool: del_ec1 = [] del_ec2 = []",
"'vertebrates' if loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else:",
"= CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by",
": string enzyme classification number used to organize data. address : string gene",
"as err: if err.code == 404 and loop == 'csm': searching = False",
"for enzyme uniprot id and AA sequence. Parameters ---------- mol_weights : dict object",
"== 'mammals': loop = 'vertebrates' break if loop == 'vertebrates': loop = 'csm'",
"import openJson, write mammals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF',",
"def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg for enzyme uniprot id and AA",
"and loop == 'csm': searching = False except TypeError as err: if loop",
"= counter + 1 try: with Pool(processes=4) as pool: del_ec1 = [] del_ec2",
"= [] del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess,",
"'LCF', 'HCQ', 'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for available genes",
"or loop == 'csm': for address in best: organism = best # for",
"{} mol_weights = {} if len(sys.argv) == 1: brenda_parameters = openJson('JSONs/brenda_parameters.json') else: brenda_parameters",
"bigg ids. del_ec : list empty list which is appended to here containing",
"best: for address in best[gene]: organism = best[gene] # for readability try: fillData(mol_weights,",
"address) sequence = CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address)",
"chosen by approximation. A detailed study of the phylogenetic tree has not been",
"depicrated ec numbers Returns ------- dict key: ec number. value: all collected data",
"mol_weights if __name__ == '__main__': sub_dict_1 = {} sub_dict_2 = {} sub_dict_3 =",
"counter = 0 for ec_number in optimized_bigg: if counter % 4 == 0:",
"'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB', 'PHI', 'CCW', 'FPG', 'FCH',",
"-*- \"\"\" Created on Wed Jan 24 16:03:28 2018 @author: dimitricoukos Test: in",
"try: loopHandler(mol_weights, ec_number, genes, loop) searching = False except HTTPError as err: if",
"on Wed Jan 24 16:03:28 2018 @author: dimitricoukos Test: in command line: python",
"= {} for ec_number in mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id] =",
"= {} sub_dict_3 = {} sub_dict_4 = {} mol_weights = {} if len(sys.argv)",
"organism genes. Organisms phylogenetically closer to Cricetulus griseus are preferred, but they are",
"processing BiGG id: ' + ec_number) mol_weights[ec_number]['bigg ids'] = bigg_ids[ec_number] try: genes =",
"by each multiprocessing.process. Parameters ---------- bigg_ids : dict key: ec_number. value: corresponding bigg",
"ec number: '+ec_number) continue else: raise if genes: loop = 'best' searching =",
"del_ec3 = [] del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 =",
"None) for ec in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if",
"genes: return genes['HSA'] else: loop = 'mammals' if loop == 'mammals': mammal_match =",
"bool(mammal_match): return mammal_match else: loop = 'vertebrates' if loop == 'vertebrates': animal_match =",
"'ELS', 'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for available genes matching kegg",
"mol_weights[ec_number]['uniprot_ids'] = [] if loop == 'best' or loop == 'csm': for address",
"if loop == 'vertebrates': loop = 'csm' if loop == 'csm': searching =",
"returnBestAddress(genes, loop): \"\"\"Searches for available genes matching kegg enzyme entry. This function searches",
"in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0 for ec_number in",
"[] del_ec2 = [] del_ec3 = [] del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess,",
"ec_number, organism, address): \"\"\"Searches kegg for enzyme uniprot id and AA sequence. Parameters",
"but they are chosen by approximation. A detailed study of the phylogenetic tree",
"= best[gene] # for readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError as",
"of genes corresponding to ec number. loop : string \"\"\" searching = True",
"address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by each multiprocessing.process.",
"readability try: fillData(mol_weights, ec_number, organism, address) except HTTPError as err: if err.code ==",
"animal_match else: loop = 'csm' # Stands for \"common simple models\" if loop",
"mw_4 = pool.apply_async(mainSubprocess, (sub_dict_4, del_ec4,)) pool.close() pool.join() for ec in del_ec1: mw_1.pop(ec, None)",
"weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids,",
"kegg enzyme entry. This function searches 'sequentially'. It returns the best available model",
"Created on Wed Jan 24 16:03:28 2018 @author: dimitricoukos Test: in command line:",
"= optimized_bigg[ec_number] counter = counter + 1 try: with Pool(processes=4) as pool: del_ec1",
"= True while searching: try: loopHandler(mol_weights, ec_number, genes, loop) searching = False except",
"elif 'MMU' in genes: return genes['MMU'] elif 'RNO' in genes: return genes['RNO'] elif",
"phylogenetic tree has not been done for this project. Hopefully going sequentially increases",
"== 404 and loop == 'csm': searching = False except TypeError as err:",
"'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI',",
"loop : string \"\"\" searching = True while searching: best = returnBestAddress(genes, loop)",
"address in best: organism = best # for readability try: fillData(mol_weights, ec_number, organism,",
"elif 'RNO' in genes: return genes['RNO'] elif 'HSA' in genes: return genes['HSA'] else:",
"4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter % 4 == 2: sub_dict_3[ec_number]",
"CS.ecnumber_to_genes(ec_number) except HTTPError as err: if err.code == 404: print('Excepted: No entry for",
"'SFM', 'LCM', 'CMK'] def returnBestAddress(genes, loop): \"\"\"Searches for available genes matching kegg enzyme",
"'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP', 'CFA', 'AML',",
"sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter % 4 == 1: sub_dict_2[ec_number] = optimized_bigg[ec_number] if",
"gene address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() + ':' + address) sequence =",
"'vertebrates': loop = 'csm' break if loop == 'csm': searching = False return",
"enzyme classification number used to organize data. address : string gene address for",
"loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match): return mammal_match else: loop =",
"'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU',",
"in genes: return genes['MMU'] elif 'RNO' in genes: return genes['RNO'] elif 'HSA' in",
"\"\"\" import sys import cobra_services as CS from multiprocessing import Pool from urllib.error",
": list empty list which is appended to here containing depicrated ec numbers",
"'OAA'] animals = ['HSA', 'PTR', 'PPS', 'GGO', 'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB',",
"= 'vertebrates' break if loop == 'vertebrates': loop = 'csm' break if loop",
"in best: for address in best[gene]: organism = best[gene] # for readability try:",
"for ec_number in bigg_ids: # WARNING: joblib may require list mol_weights[ec_number] = {}",
"len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get()) write('Unit Tests/multiprocessing_sub_output3.json', mw_3.get()) mol_weights_to_write = {} for",
"genes['CGE'] elif 'MMU' in genes: return genes['MMU'] elif 'RNO' in genes: return genes['RNO']",
"loop == 'best': loop = 'mammals' break if loop == 'mammals': loop =",
"of the phylogenetic tree has not been done for this project. Hopefully going",
"loop = 'vertebrates' if loop == 'vertebrates': loop = 'csm' if loop ==",
"sub_dict_2[ec_number] = optimized_bigg[ec_number] if counter % 4 == 2: sub_dict_3[ec_number] = optimized_bigg[ec_number] if",
"matches. Parameters ---------- mol_weights : list empty list. will contain estimated molecular weights",
"v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0 for ec_number",
"'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX',",
"= pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,)) mw_2 = pool.apply_async(mainSubprocess, (sub_dict_2, del_ec2,)) mw_3 = pool.apply_async(mainSubprocess, (sub_dict_3,",
"code. value: gene addresses for enzyme and organism \"\"\" if loop == 'best':",
"if loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match): return animal_match else: loop",
"if err.code == 404: print('Excepted: No entry for ec number: '+ec_number) continue else:",
"else: loop = 'mammals' if loop == 'mammals': mammal_match = set(genes.keys()).intersection(mammals) if bool(mammal_match):",
"= [] mol_weights[ec_number]['uniprot_ids'] = [] if loop == 'best' or loop == 'csm':",
"% 4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter % 4 == 1:",
"HTTPError as err: if err.code == 404 and loop == 'csm': searching =",
"simplified_brenda[bigg_id] = brenda_parameters[bigg_id][0] optimized_bigg = {} for k, v in simplified_brenda.items(): optimized_bigg[v] =",
"loop = 'csm' break if loop == 'csm': searching = False return None",
"Parameters ---------- mol_weights : dict object containing all information collected by program. ec_number",
"genes['RNO'] elif 'HSA' in genes: return genes['HSA'] else: loop = 'mammals' if loop",
"'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL', 'OCU', 'TUP',",
"in. Returns ------- dict key: kegg organism code. value: gene addresses for enzyme",
"classification number used to organize data. address : string gene address for sequence",
"== 'best': loop = 'mammals' if loop == 'mammals': loop = 'vertebrates' if",
"err.code == 404: pass def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg for enzyme",
"def returnBestAddress(genes, loop): \"\"\"Searches for available genes matching kegg enzyme entry. This function",
"joblib may require list mol_weights[ec_number] = {} print('Currently processing BiGG id: ' +",
"if counter % 4 == 0: sub_dict_1[ec_number] = optimized_bigg[ec_number] if counter % 4",
"mw_2.pop(ec, None) for ec in del_ec3: mw_3.pop(ec, None) for ec in del_ec4: mw_4.pop(ec,",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Jan 24 16:03:28 2018 @author:",
"address): \"\"\"Searches kegg for enzyme uniprot id and AA sequence. Parameters ---------- mol_weights",
"':' + address) sequence = CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot =",
"= [] del_ec3 = [] del_ec4 = [] mw_1 = pool.apply_async(mainSubprocess, (sub_dict_1, del_ec1,))",
"if __name__ == '__main__': sub_dict_1 = {} sub_dict_2 = {} sub_dict_3 = {}",
"organize data. address : string gene address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower() +",
"print('Excepted: No entry for ec number: '+ec_number) continue else: raise if genes: loop",
"break if loop == 'mammals': loop = 'vertebrates' break if loop == 'vertebrates':",
"= brenda_parameters[bigg_id][0] optimized_bigg = {} for k, v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v,",
"{} for k, v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter =",
"= {} sub_dict_2 = {} sub_dict_3 = {} sub_dict_4 = {} mol_weights =",
"= False mol_weights[ec_number]['weights'] = [] mol_weights[ec_number]['uniprot_ids'] = [] if loop == 'best' or",
"in genes: return genes['RNO'] elif 'HSA' in genes: return genes['HSA'] else: loop =",
"del_ec2: mw_2.pop(ec, None) for ec in del_ec3: mw_3.pop(ec, None) for ec in del_ec4:",
"'PON', 'NLE', 'MCC', 'MCF', 'RRO', 'RBB', 'CJC', 'SBQ', 'MMU', 'RNO', 'CGE', 'NGI', 'HGL',",
"'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU', 'PHD', 'CHX', 'OAS', 'SSC', 'CFR', 'CDK',",
"best available model organism genes. Organisms phylogenetically closer to Cricetulus griseus are preferred,",
"address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def",
"else: loop = 'vertebrates' if loop == 'vertebrates': animal_match = set(genes.keys()).intersection(animals) if bool(animal_match):",
"'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR',",
"as err: if err.code == 404: pass def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches",
"err.code == 404: print('Excepted: No entry for ec number: '+ec_number) continue else: raise",
"command line: python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json' \"\"\" import sys import cobra_services as CS",
"= CS.kegggene_to_sequence(organism, address) weight = CS.sequence_weight(sequence) mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot:",
"number: '+ec_number) continue else: raise if genes: loop = 'best' searching = True",
"readability and efficiency. Parameters ---------- genes : dict key: value pair is organism:",
"'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP',",
"mol_weights[ec_number]['weights'].append(weight) uniprot = CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function",
"returns the best available model organism genes. Organisms phylogenetically closer to Cricetulus griseus",
"err.code == 404 and loop == 'csm': searching = False except TypeError as",
"False except HTTPError as err: if err.code == 404 and loop == 'csm':",
"'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR', 'NPR', 'DRE', 'SRX', 'SGH', 'IPU', 'TRU', 'TNG',",
"'EGZ', 'AAM', 'ASN', 'AMJ', 'PSS', 'CMY', 'SEA', 'ACS', 'PVT', 'PBI', 'GJA', 'XLA', 'XTR',",
"== 404: pass def fillData(mol_weights, ec_number, organism, address): \"\"\"Searches kegg for enzyme uniprot",
"err: if err.code == 404: print('Excepted: No entry for ec number: '+ec_number) continue",
"CS.kegggene_to_uniprotid(organism, address) if uniprot: mol_weights[ec_number]['uniprot_ids'].uniprot def mainSubprocess(bigg_ids, del_ec): \"\"\"Main function called by each",
"organism \"\"\" if loop == 'best': if 'CGE' in genes: return genes['CGE'] elif",
"in del_ec4: mw_4.pop(ec, None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1:",
"and AA sequence. Parameters ---------- mol_weights : dict object containing all information collected",
"mol_weights_to_write = {} for ec_number in mol_weights: for bigg_id in mol_weights[ec_number]['bigg ids']: mol_weights_to_write[bigg_id]",
"the phylogenetic tree has not been done for this project. Hopefully going sequentially",
"bigg_ids[ec_number] try: genes = CS.ecnumber_to_genes(ec_number) except HTTPError as err: if err.code == 404:",
"'HGL', 'OCU', 'TUP', 'CFA', 'AML', 'UMR', 'ORO', 'FCA', 'PTG', 'AJU', 'BTA', 'BOM', 'BIU',",
"loop = 'vertebrates' break if loop == 'vertebrates': loop = 'csm' break if",
"'OAS', 'SSC', 'CFR', 'CDK', 'LVE', 'OOR', 'ECB', 'EPZ', 'EAI', 'MYB', 'MYD', 'HAI', 'RSS',",
"to organize data. address : string gene address for sequence lookup. \"\"\" mol_weights[ec_number]['genes'].append(organism.lower()",
"None) finally: mol_weights.update(mw_1.get()) mol_weights.update(mw_2.get()) mol_weights.update(mw_3.get()) mol_weights.update(mw_4.get()) if len(sys.argv) > 1: write('Unit Tests/multiprocessing_sub_output1.json', mw_1.get())",
"if counter % 4 == 3: sub_dict_4[ec_number] = optimized_bigg[ec_number] counter = counter +",
"genes: return genes['ECO'] def loopHandler(mol_weights, ec_number, genes, loop): \"\"\"Calls the correct loop of",
"'csm': for address in best: organism = best # for readability try: fillData(mol_weights,",
"'HAI', 'RSS', 'LAV', 'TMU', 'MDO', 'SHR', 'OAA', 'GGA', 'MGP', 'CJO', 'TGU', 'GFR', 'FAB',",
"for k, v in simplified_brenda.items(): optimized_bigg[v] = optimized_bigg.get(v, []) optimized_bigg[v].append(k) counter = 0",
"in bigg_ids: # WARNING: joblib may require list mol_weights[ec_number] = {} print('Currently processing",
"string Indicates the highest potential group of matching organisms to search in. Returns"
] |
[
"if file: finish_file() file_samples = 0 ts = int(time.time() * 1000) filename =",
"None file = None file_samples = 0 start = None n_names = 0",
"args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None filename =",
"import time import shutil from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import RequestInit from",
"type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info,",
"file_samples = 0 start = None n_names = 0 n_production = 0 def",
"type=float) args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req =",
"i in range(args.samples): if not file or file_samples >= args.samples_per_file: if file: finish_file()",
"type=int, default=1000, help='number of samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file',",
"1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename,",
"n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def",
"n_names, n_production, end - start )) for i in range(args.samples): if not file",
"Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request as ExprRequest from",
"kite.infer_call.request import Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request as",
"int) -> str: n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample,",
"parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed,",
"= 0 def finish_file(): file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info( \"sample {}:",
"kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config from",
"type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config",
"file_samples >= args.samples_per_file: if file: finish_file() file_samples = 0 ts = int(time.time() *",
"= \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename, 'wb') start",
"finish_file() file_samples = 0 ts = int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i,",
"argparse import datetime import json import logging import pickle import time import shutil",
"batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist,",
"start )) for i in range(args.samples): if not file or file_samples >= args.samples_per_file:",
"from kite.infer_call.request import Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request",
"EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None filename = None file = None file_samples",
"= 0 start = None n_names = 0 n_production = 0 def finish_file():",
"filename) end = datetime.datetime.now() logging.info( \"sample {}: saved {} with {} samples ({}",
"batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist,",
"parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion',",
"args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing",
"{} samples ({} name, {} production), took {}\".format( i, filename, args.samples_per_file, n_names, n_production,",
"pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples",
"file_samples += 1 if file_samples > 0: finish_file() finally: feeder.stop() if __name__ ==",
"Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int, total: int, timestamp:",
"tmp_filename = None filename = None file = None file_samples = 0 start",
"samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int)",
"type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number of samples",
"kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config",
"type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number of samples to generate') parser.add_argument('--meta_info',",
"return format_str.format(cur_sample, total, timestamp) def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed',",
"\"sample {}: saved {} with {} samples ({} name, {} production), took {}\".format(",
"len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples > 0: finish_file() finally:",
"= argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000,",
">= args.samples_per_file: if file: finish_file() file_samples = 0 ts = int(time.time() * 1000)",
"parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number of",
"range(args.samples): if not file or file_samples >= args.samples_per_file: if file: finish_file() file_samples =",
"in range(args.samples): if not file or file_samples >= args.samples_per_file: if file: finish_file() file_samples",
"kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request import Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest",
"num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist,",
"max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion,",
"\"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename, 'wb') start =",
"parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float)",
"from kite.infer_expr.attr_base import Request as AttrBaseRequest from kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG,",
"req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest(",
"= \"{}.part\".format(filename) file = open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample",
"None filename = None file = None file_samples = 0 start = None",
"import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request",
"default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float)",
"0 start = None n_names = 0 n_production = 0 def finish_file(): file.close()",
"import pickle import time import shutil from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import",
"args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None filename = None file",
"start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file) n_names +=",
"+= len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples > 0: finish_file()",
"total: int, timestamp: int) -> str: n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) +",
"max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion,",
"end = datetime.datetime.now() logging.info( \"sample {}: saved {} with {} samples ({} name,",
"parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords,",
"argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number",
"samples to {}, random seed = {}\".format( args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint,",
"or file_samples >= args.samples_per_file: if file: finish_file() file_samples = 0 ts = int(time.time()",
"type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args =",
"to {}, random seed = {}\".format( args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req)",
"symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write {} samples to {}, random seed",
"args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req = RequestInit(",
"symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest(",
"({} name, {} production), took {}\".format( i, filename, args.samples_per_file, n_names, n_production, end -",
"default=1000, help='number of samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int,",
"= MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops,",
"as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request as ExprRequest from kite.infer_expr.attr_base",
"generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float)",
"file = open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next()",
"= RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist,",
"type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info",
"AttrBaseRequest from kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample:",
"file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info( \"sample {}: saved {} with {}",
"format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int, total: int, timestamp: int) -> str: n_digits",
"datetime.datetime.now() logging.info( \"sample {}: saved {} with {} samples ({} name, {} production),",
"open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file)",
"logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production +=",
"int, total: int, timestamp: int) -> str: n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits)",
"= None file_samples = 0 start = None n_names = 0 n_production =",
"= 0 ts = int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts))",
"{}\".format( i, filename, args.samples_per_file, n_names, n_production, end - start )) for i in",
"{} production), took {}\".format( i, filename, args.samples_per_file, n_names, n_production, end - start ))",
"%(message)s') def get_filename(cur_sample: int, total: int, timestamp: int) -> str: n_digits = len(str(total))",
"expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist,",
"\"{}.part\".format(filename) file = open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample =",
"total, timestamp) def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch',",
"n_names = 0 n_production = 0 def finish_file(): file.close() shutil.move(tmp_filename, filename) end =",
"timestamp: int) -> str: n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return",
"timestamp) def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int,",
"i, filename, args.samples_per_file, n_names, n_production, end - start )) for i in range(args.samples):",
"for i in range(args.samples): if not file or file_samples >= args.samples_per_file: if file:",
"import EndpointDataFeeder from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import",
"'wb') start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file) n_names",
"= feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1",
"not file or file_samples >= args.samples_per_file: if file: finish_file() file_samples = 0 ts",
"feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if",
"GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request import Request as CallRequest, KwargRequest,",
"attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ),",
"= datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes)",
"file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples >",
"def finish_file(): file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info( \"sample {}: saved {}",
"from kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request import Request as CallRequest, KwargRequest, ArgTypeRequest,",
"parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int,",
"type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float)",
"call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ),",
"sample = feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples +=",
"), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will",
"name, {} production), took {}\".format( i, filename, args.samples_per_file, n_names, n_production, end - start",
"= \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def main(): parser = argparse.ArgumentParser()",
"kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write",
"parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args()",
"import datetime import json import logging import pickle import time import shutil from",
"parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number of samples to generate')",
"feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None filename = None file =",
"parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req",
"pickle import time import shutil from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import RequestInit",
"finish_file(): file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info( \"sample {}: saved {} with",
"file or file_samples >= args.samples_per_file: if file: finish_file() file_samples = 0 ts =",
"from kite.infer_expr.request import Request as ExprRequest from kite.infer_expr.attr_base import Request as AttrBaseRequest from",
"ts = int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename =",
"to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion',",
"parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r')))",
"as ExprRequest from kite.infer_expr.attr_base import Request as AttrBaseRequest from kite.infer_attr.request import Request as",
"= datetime.datetime.now() logging.info( \"sample {}: saved {} with {} samples ({} name, {}",
"CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request as ExprRequest from kite.infer_expr.attr_base import",
"-> str: n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total,",
"+ \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str,",
"len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def main(): parser",
"= {}\".format( args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None",
"Request as AttrBaseRequest from kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s')",
"config = Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production,",
"format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def main(): parser =",
"kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request import Request as",
"keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write {} samples",
"), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion,",
"shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info( \"sample {}: saved {} with {} samples",
"saved {} with {} samples ({} name, {} production), took {}\".format( i, filename,",
"{} with {} samples ({} name, {} production), took {}\".format( i, filename, args.samples_per_file,",
"parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info =",
"main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples',",
"MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index,",
"Config from kite.infer_call.request import Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import",
"from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config",
"as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int, total: int, timestamp: int)",
"{}: saved {} with {} samples ({} name, {} production), took {}\".format( i,",
"production), took {}\".format( i, filename, args.samples_per_file, n_names, n_production, end - start )) for",
"RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request import",
"n_production = 0 def finish_file(): file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info( \"sample",
"logging import pickle import time import shutil from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session",
"n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples > 0:",
"MetaInfo, Config from kite.infer_call.request import Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request",
"as AttrBaseRequest from kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def",
") ), ) logging.info(\"will write {} samples to {}, random seed = {}\".format(",
"parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion',",
"{}\".format( args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None filename",
"parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number of samples to generate') parser.add_argument('--meta_info', type=str)",
"str: n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp)",
"import GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request import Request as CallRequest,",
"EndpointDataFeeder from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import MetaInfo,",
"of samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples',",
"datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production",
"ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request as ExprRequest from kite.infer_expr.attr_base import Request as",
"len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples > 0: finish_file() finally: feeder.stop() if __name__",
"batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), )",
"1 if file_samples > 0: finish_file() finally: feeder.stop() if __name__ == \"__main__\": main()",
"= open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample,",
"import argparse import datetime import json import logging import pickle import time import",
"import Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request as ExprRequest",
"{}, random seed = {}\".format( args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try:",
"n_production, end - start )) for i in range(args.samples): if not file or",
")) for i in range(args.samples): if not file or file_samples >= args.samples_per_file: if",
"0 ts = int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename",
"import json import logging import pickle import time import shutil from kite.graph_data.data_feeder import",
"= Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest(",
"name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents,",
"- start )) for i in range(args.samples): if not file or file_samples >=",
"time import shutil from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed",
"production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest(",
"symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ),",
"filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename, 'wb')",
"config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ),",
"arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, )",
"default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number of samples to",
"import Request as ExprRequest from kite.infer_expr.attr_base import Request as AttrBaseRequest from kite.infer_attr.request import",
"None n_names = 0 n_production = 0 def finish_file(): file.close() shutil.move(tmp_filename, filename) end",
"symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest(",
"if not file or file_samples >= args.samples_per_file: if file: finish_file() file_samples = 0",
"), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion,",
"took {}\".format( i, filename, args.samples_per_file, n_names, n_production, end - start )) for i",
"None file_samples = 0 start = None n_names = 0 n_production = 0",
"seed = {}\".format( args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename =",
"\"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039')",
"from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig from",
"get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename, 'wb') start = datetime.datetime.now()",
"ts)) tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing to",
"args.samples_per_file: if file: finish_file() file_samples = 0 ts = int(time.time() * 1000) filename",
"ArgPlaceholderRequest from kite.infer_expr.request import Request as ExprRequest from kite.infer_expr.attr_base import Request as AttrBaseRequest",
"logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int, total: int, timestamp: int) -> str:",
"kite.infer_expr.attr_base import Request as AttrBaseRequest from kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s",
"), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write {} samples to {},",
"file_samples = 0 ts = int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples,",
"arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write {} samples to {}, random",
"tmp_filename = \"{}.part\".format(filename) file = open(tmp_filename, 'wb') start = datetime.datetime.now() logging.info(\"writing to {}\".format(tmp_filename))",
") logging.info(\"will write {} samples to {}, random seed = {}\".format( args.samples, args.out_dir,",
"def get_filename(cur_sample: int, total: int, timestamp: int) -> str: n_digits = len(str(total)) format_str",
"file = None file_samples = 0 start = None n_names = 0 n_production",
"help='number of samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500)",
"= None n_names = 0 n_production = 0 def finish_file(): file.close() shutil.move(tmp_filename, filename)",
"kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int, total:",
"batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write {} samples to {}, random seed =",
"parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config =",
"type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args = parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config()",
"try: tmp_filename = None filename = None file = None file_samples = 0",
"from kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int,",
"parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion',",
"datetime import json import logging import pickle import time import shutil from kite.graph_data.data_feeder",
"0 def finish_file(): file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info( \"sample {}: saved",
"int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file",
"n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples > 0: finish_file() finally: feeder.stop()",
"attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ),",
"= len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def main():",
"int, timestamp: int) -> str: n_digits = len(str(total)) format_str = \"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\"",
"type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float)",
"end - start )) for i in range(args.samples): if not file or file_samples",
"samples ({} name, {} production), took {}\".format( i, filename, args.samples_per_file, n_names, n_production, end",
"import Request as AttrBaseRequest from kite.infer_attr.request import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s",
"symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write {}",
"type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest( symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ),",
"default=10) parser.add_argument('--samples', type=int, default=1000, help='number of samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str,",
"KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from kite.infer_expr.request import Request as ExprRequest from kite.infer_expr.attr_base import Request",
"random seed = {}\".format( args.samples, args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename",
"filename, args.samples_per_file, n_names, n_production, end - start )) for i in range(args.samples): if",
"shutil from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import GraphFeedConfig",
"= parser.parse_args() meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set),",
"type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion',",
"file: finish_file() file_samples = 0 ts = int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir,",
"format_str.format(cur_sample, total, timestamp) def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int)",
"symbols=meta_info.attr.dist, batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest(",
"\"{{:0{}d}}\".format(n_digits) + \"-of-{}-{}.pickle\" return format_str.format(cur_sample, total, timestamp) def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint',",
"* 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename) file =",
"type=str) parser.add_argument('--out_dir', type=str, default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float)",
"import Request as AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int, total: int,",
"= None filename = None file = None file_samples = 0 start =",
"req) try: tmp_filename = None filename = None file = None file_samples =",
"import MetaInfo, Config from kite.infer_call.request import Request as CallRequest, KwargRequest, ArgTypeRequest, ArgPlaceholderRequest from",
"meta_info = MetaInfo.from_json(json.load(open(args.meta_info, 'r'))) config = Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch,",
"with {} samples ({} name, {} production), took {}\".format( i, filename, args.samples_per_file, n_names,",
"= EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None filename = None file = None",
"default='data') parser.add_argument('--samples_per_file', type=int, default=500) parser.add_argument('--max_samples', type=int) parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion',",
"to {}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes)",
"start = None n_names = 0 n_production = 0 def finish_file(): file.close() shutil.move(tmp_filename,",
"+= 1 if file_samples > 0: finish_file() finally: feeder.stop() if __name__ == \"__main__\":",
"AttrRequest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s') def get_filename(cur_sample: int, total: int, timestamp: int) ->",
"logging.info(\"will write {} samples to {}, random seed = {}\".format( args.samples, args.out_dir, args.random_seed))",
"import logging import pickle import time import shutil from kite.graph_data.data_feeder import EndpointDataFeeder from",
"batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion, ) ), ) logging.info(\"will write {} samples to",
"get_filename(cur_sample: int, total: int, timestamp: int) -> str: n_digits = len(str(total)) format_str =",
"args.samples_per_file, n_names, n_production, end - start )) for i in range(args.samples): if not",
"{} samples to {}, random seed = {}\".format( args.samples, args.out_dir, args.random_seed)) feeder =",
"logging.info( \"sample {}: saved {} with {} samples ({} name, {} production), took",
"= int(time.time() * 1000) filename = \"{}/{}\".format(args.out_dir, get_filename(i, args.samples, ts)) tmp_filename = \"{}.part\".format(filename)",
"), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist, keywords=meta_info.call.keywords, batch_proportion=args.kwarg_name_proportion, ), arg_placeholder=ArgPlaceholderRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_placeholder_proportion,",
"filename = None file = None file_samples = 0 start = None n_names",
"parser.add_argument('--attr_base_proportion', type=float) parser.add_argument('--attr_proportion', type=float) parser.add_argument('--call_proportion', type=float) parser.add_argument('--arg_type_proportion', type=float) parser.add_argument('--kwarg_name_proportion', type=float) parser.add_argument('--arg_placeholder_proportion', type=float) args",
"ExprRequest from kite.infer_expr.attr_base import Request as AttrBaseRequest from kite.infer_attr.request import Request as AttrRequest",
"args.out_dir, args.random_seed)) feeder = EndpointDataFeeder(args.endpoint, req) try: tmp_filename = None filename = None",
"), ) logging.info(\"will write {} samples to {}, random seed = {}\".format( args.samples,",
"RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion,",
"Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples,",
"json import logging import pickle import time import shutil from kite.graph_data.data_feeder import EndpointDataFeeder",
"%(levelname)-8s %(message)s') def get_filename(cur_sample: int, total: int, timestamp: int) -> str: n_digits =",
"batch_proportion=args.attr_proportion, parents=meta_info.attr.parents, ), attr_base=AttrBaseRequest( symbols=meta_info.attr_base.dist, batch_proportion=args.attr_base_proportion, ), arg_type=ArgTypeRequest( symbols=meta_info.call.dist, batch_proportion=args.arg_type_proportion, ), kwarg_name=KwargRequest( symbols=meta_info.call.dist,",
"0 n_production = 0 def finish_file(): file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now() logging.info(",
"= 0 n_production = 0 def finish_file(): file.close() shutil.move(tmp_filename, filename) end = datetime.datetime.now()",
"random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index, production_index=meta_info.production, expr=ExprRequest( max_samples=args.max_samples, call=CallRequest( symbols=meta_info.call.dist, batch_proportion=args.call_proportion, ), attr=AttrRequest(",
"+= len(sample.data.expr.infer_production.prediction_nodes) file_samples += 1 if file_samples > 0: finish_file() finally: feeder.stop() if",
"Request as ExprRequest from kite.infer_expr.attr_base import Request as AttrBaseRequest from kite.infer_attr.request import Request",
"type=int, default=10) parser.add_argument('--samples', type=int, default=1000, help='number of samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir',",
"'r'))) config = Config() req = RequestInit( config=GraphFeedConfig(edge_set=config.ggnn.edge_set), random_seed=args.random_seed, num_batches=args.batch, max_hops=config.max_hops, name_subtoken_index=meta_info.name_subtoken_index, type_subtoken_index=meta_info.type_subtoken_index,",
"def main(): parser = argparse.ArgumentParser() parser.add_argument('--endpoint', type=str, default='http://localhost:3039') parser.add_argument('--random_seed', type=int) parser.add_argument('--batch', type=int, default=10)",
"write {} samples to {}, random seed = {}\".format( args.samples, args.out_dir, args.random_seed)) feeder",
"= None file = None file_samples = 0 start = None n_names =",
"parser.add_argument('--samples', type=int, default=1000, help='number of samples to generate') parser.add_argument('--meta_info', type=str) parser.add_argument('--out_dir', type=str, default='data')",
"import shutil from kite.graph_data.data_feeder import EndpointDataFeeder from kite.graph_data.session import RequestInit from kite.graph_data.graph_feed import",
"{}\".format(tmp_filename)) sample = feeder.next() pickle.dump(sample, file) n_names += len(sample.data.expr.infer_name.prediction_nodes) n_production += len(sample.data.expr.infer_production.prediction_nodes) file_samples",
"from kite.graph_data.graph_feed import GraphFeedConfig from kite.infer_expr.config import MetaInfo, Config from kite.infer_call.request import Request",
"kite.infer_expr.request import Request as ExprRequest from kite.infer_expr.attr_base import Request as AttrBaseRequest from kite.infer_attr.request"
] |
[
"indicating if we should learn all the layers from scratch :param layers: str.",
"L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if",
"L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input =",
"n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None,",
"Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy =",
"group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if not",
"= L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss =",
"layers='5', is_imagenet=False): \"\"\" Creates a protoxt for the AlexNet architecture :param lmdb_path: str.",
"else: fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc,",
"layers from scratch :returns: Caffe NetSpec, tuple with names of loss blobs, tuple",
"testing or training :param num_classes: int. number of classes for the top classifier",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz",
"bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet,",
"# Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) #",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p,",
"relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNN n.concat = L.Concat(relu5,",
"n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5,",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x",
"n, learn_all, False) # TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat,",
"stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego",
"int. Batch size :param scale: float. How to scale the images :param contrastive_margin:",
"learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if layers == '4': n.fc_prev =",
"L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True),",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p =",
"learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout =",
"n, learn_all, True) # TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat,",
"MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt similar",
"= n.relu3 # Learn all true because we always want to train the",
"= L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2",
"is_train: bool. Flag indicating if this is for testing or training :param learn_all:",
"in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7",
"n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b',",
"for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz =",
"caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data,",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7,",
"n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\"",
"the net we can track to test the 'health' # of the training",
"= L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 =",
"False) # TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"to test the 'health' # of the training process return n, ('loss',), ('acc',)",
"n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1,",
"should learn all the layers from scratch :param layers: str. from which layer",
"bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop = fcxinput",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 = fc8input =",
"Batch size :param scale: float. How to scale the images :param contrastive_margin: int.",
"scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx,",
"param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if layers ==",
"bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"= L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384,",
"n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x",
"layers: str. from which layer we will extract features to train a classifier",
"L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5 =",
"num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label)",
"bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc,",
"is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the",
"are training from scratch or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b',",
"bcnn(n.data0, n.data1, n, learn_all, False) # TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True),",
"= L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers",
"is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',),",
"n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0)",
"n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc = L.Accuracy(n.fc8_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',)",
"siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a protoxt for",
"relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNN n.concat = L.Concat(relu5, relu5_p,",
"slice_point=1), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2,",
"fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"lmdb_path: str. Path to train LMDB :param batch_size: int. Batch size :param scale:",
"n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout = fcxinput =",
"is for testing or training :returns: Caffe NetSpec, tuple with names of loss",
"the images :param is_train: bool. Flag indicating if this is for testing or",
"a contrastive loss layer on top :param lmdb_path: str. Path to train LMDB",
"outputs of the net we can track to test the 'health' # of",
"L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w',",
"# Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5,",
"return n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc,",
"num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 =",
"n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels for MNIST",
"fczinput = n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)],",
"L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def",
"= L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x =",
"learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 = fc7input =",
"return n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc,",
"MNIST experiment :param lmdb_path: str. Path to train LMDB :param batch_size: int. Batch",
"can # know which outputs of the net we can track to test",
"L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if",
"L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop = fcxinput = fcyinput = fczinput = L.Dropout(n.relu8,",
"n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1,",
"= input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1 =",
"L.ReLU(n.conv4, in_place=True) if layers == '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b',",
"param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7",
"L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'),",
"caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels",
"learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop =",
"protoxt for the AlexNet architecture :param lmdb_path: str. Path to train LMDB :param",
"scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet architecture for",
"weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if layers == '4': n.fc_prev = L.InnerProduct(n.relu4,",
"L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive",
"Path to test LMDB labels :param batch_size: int. Batch size :param scale: float.",
"n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely,",
"import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True):",
"n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1,",
"L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if",
"= L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"in_place=True) if is_train: n.drop = fcxinput = fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5),",
"= L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7,",
"bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class KITTINetFactory:",
"n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 =",
"= L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input",
"Contrastive loss :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path",
"else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 =",
"scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) #",
"('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler,",
"L.ReLU(n.conv5, in_place=True) if not is_imagenet: if layers == '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000,",
"num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train:",
"L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3,",
"we should learn all the layers from scratch :returns: Caffe NetSpec, tuple with",
"= fczinput = n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b',",
"TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 =",
"include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w',",
"is_imagenet: if layers == '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)],",
"bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod def",
"caffe from caffe import (layers as L, params as P) from layers_wrappers import",
"def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for",
"if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc = L.Accuracy(n.fc8_imgnet, n.label, include=dict(phase=caffe.TEST)) return n,",
"is useful because then we can # know which outputs of the net",
"('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler,",
"L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet,",
"is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7_imgnet =",
"= L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5",
"= L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w',",
"for the contrastive loss layer :param is_train: bool. Flag indicating if this is",
"in_place=True) else: fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)],",
"L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2,",
"n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if",
"n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4,",
"n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500",
"L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input =",
"n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5,",
"float. How to scale the images :param is_train: bool. Flag indicating if this",
"= L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20,",
":returns: Caffe NetSpec, tuple with names of loss blobs, tuple with name of",
"num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train:",
"bcnn(n.data0, n.data1, n, learn_all, False) # TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6",
"('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6",
"str. Path to train LMDB labels :param test_lmdb: str. Path to train LMDB",
"def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a protoxt",
"= fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes,",
"stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2,",
"'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates",
"in_place=True) else: fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)],",
"for the MNIST experiment :param lmdb_path: str. Path to train LMDB :param batch_size:",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train: n.dropout = fc10input =",
"blobs, tuple with name of accuracy blobs \"\"\" n = caffe.NetSpec() phase =",
"param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc",
"in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)],",
"is for testing or training :param num_classes: int. number of classes for the",
"= L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x =",
"if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz,",
"= L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n,",
"n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True),",
"is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',),",
"learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc =",
"learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if layers == '3': n.fc_prev =",
"L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b',",
"caffe.TRAIN if is_train else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale),",
"learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500,",
"learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if not is_imagenet: if layers ==",
"n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1",
"'3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev =",
"Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely,",
"Uses Contrastive loss :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str.",
"= L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz,",
"bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3,",
"False) # TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2,",
"\"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) #",
"None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False):",
"layers of AlexNet architecture for the MNIST experiment :param lmdb_path: str. Path to",
"in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)],",
"labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1,",
"= L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True),",
"L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout = fcxinput = fcyinput = fczinput = L.Dropout(n.relu3,",
"= L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n,",
"= L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST))",
"learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX,",
":param batch_size: int. Batch size :param scale: float. How to scale the images",
"return n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all),",
"= L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n,",
"= caffe.TRAIN if is_train else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path,",
"ntop=3) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNN",
"L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4 =",
"param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6,",
":param layers: str. from which layer we will extract features to train a",
"indicating if this is for testing or training :param learn_all: bool. Flag indicating",
"\"\"\" Creates a protoxt similar to the first layers of AlexNet architecture for",
"include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y',",
"n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p = bcnn(n.data0,",
"= L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True),",
"kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True)",
"for the MNIST experiment Uses Contrastive loss :param lmdb_path: str. Path to train",
"L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate,",
"n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz,",
"= L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss =",
"labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet",
"training process return n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True,",
"local_size=5, alpha=1e-4, beta=0.75) if layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True),",
"bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout = fcxinput",
"if layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc,",
"n.label, include=dict(phase=caffe.TEST)) # Returning the name of the loss/acc layers is useful because",
"bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if not is_imagenet: if layers == '5': n.fc_prev",
"How to scale the images :param contrastive_margin: int. Margin for the contrastive loss",
"top classifier :param classifier_name: str. name of the top classifier :param learn_all: bool.",
"learn_all: bool. Flag indicating if we should learn all the layers from scratch",
"L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)],",
"n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x',",
"= L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the name of",
"params as P) from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def",
"= L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout = fcxinput = fcyinput = fczinput =",
"bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100,",
"classifier :param learn_all: bool. Flag indicating if we should learn all the layers",
"= L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3",
"L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6 =",
"n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3",
"# Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx,",
"= fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3 # Learn all true",
"Path to train LMDB :param test_labels_lmdb: str. Path to test LMDB labels :param",
"param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b',",
":param learn_all: bool. Flag indicating if we should learn all the layers from",
"bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if layers == '4': n.fc_prev",
"or training :returns: Caffe NetSpec, tuple with names of loss blobs, tuple with",
"n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all),",
"n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss",
"fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput = fczinput = n.relu8",
"name of accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path,",
"n.dropout = fcxinput = fcyinput = fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput =",
"n.relu5 = L.ReLU(n.conv5, in_place=True) if not is_imagenet: if layers == '5': n.fc_prev =",
":param is_train: bool. Flag indicating if this is for testing or training :param",
"local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b',",
"n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2,",
"fcxinput = fcyinput = fczinput = n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7,",
"pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5,",
"top classifier :param learn_all: bool. Flag indicating if we should learn all the",
"batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a protoxt for siamese AlexNet architecture",
"LMDB :param test_labels_lmdb: str. Path to test LMDB labels :param batch_size: int. Batch",
"number of classes for the top classifier :param classifier_name: str. name of the",
"'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\"",
"learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if layers == '3':",
"<filename>experiments/utils/nets/cnn_factory.py #!/usr/bin/env python2.7 import caffe from caffe import (layers as L, params as",
"# TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3",
"L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2 =",
"learn_all, False) # TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3,",
"in_place=True) else: fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)],",
"n.relu3 # Learn all true because we always want to train the top",
"L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6,",
"if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7_imgnet",
"loss :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path to",
"process return n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False,",
"param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if layers ==",
"L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet =",
"= L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20,",
"param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop",
"n.relu3 = L.ReLU(n.conv3, in_place=True) if layers == '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w',",
"return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125,",
"n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1,",
"str. Path to train LMDB :param batch_size: int. Batch size :param scale: float.",
"if layers == '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc,",
"data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label,",
"learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2)",
"no matter if we are training from scratch or finetuning n.fc10 = L.InnerProduct(fc10input,",
":param test_lmdb: str. Path to train LMDB :param test_labels_lmdb: str. Path to test",
"n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w',",
"should learn all the layers from scratch :returns: Caffe NetSpec, tuple with names",
"Creates a protoxt for the AlexNet architecture :param lmdb_path: str. Path to train",
"stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1",
"bool. Flag indicating if this is for testing or training :param learn_all: bool.",
"labels :param test_lmdb: str. Path to train LMDB :param test_labels_lmdb: str. Path to",
"== '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"# of the training process return n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None,",
"in_place=True) else: fcxinput = fcyinput = fczinput = n.relu8 # Classifiers n.fcx =",
"scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a protoxt for siamese AlexNet architecture with",
"bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x =",
"= L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)],",
"to train LMDB labels :param test_lmdb: str. Path to train LMDB :param test_labels_lmdb:",
"bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 = fc8input",
"L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all,",
"num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train:",
"concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0)",
"bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True)",
"from scratch :param layers: str. from which layer we will extract features to",
"num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train:",
"bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if not is_imagenet: if layers",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout = fcxinput = fcyinput",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely)",
"= L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True)",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"contrastive_margin: int. Margin for the contrastive loss layer :param is_train: bool. Flag indicating",
"n.data1, n, learn_all, True) # TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b',",
"for testing or training :param num_classes: int. number of classes for the top",
"param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc",
"bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100,",
"is_train=True, learn_all=True): \"\"\" Creates a protoxt for the AlexNet architecture :param lmdb_path: str.",
"Flag indicating if we should learn all the layers from scratch :param layers:",
"layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"= input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96,",
"first layers of AlexNet architecture for the MNIST experiment :param lmdb_path: str. Path",
"on top :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path",
"L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7,",
"n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b',",
"bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz =",
"AlexNet architecture for the MNIST experiment :param lmdb_path: str. Path to train LMDB",
"bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz)",
"= L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True)",
"pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers == '2':",
"layers is useful because then we can # know which outputs of the",
"n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5,",
"n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet,",
"is_train: n.dropout = fcxinput = fcyinput = fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput",
"# Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy",
"all the layers from scratch :param layers: str. from which layer we will",
"size :param scale: float. How to scale the images :param contrastive_margin: int. Margin",
"n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b',",
"= L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss =",
"n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels n.data0,",
"('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0,",
"is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN",
"include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)],",
"bcnn(n.data0, n.data1, n, learn_all, True) # TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000",
"BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNNs n.fc1 =",
"@staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a",
"in_place=True) if is_train: n.dropout = fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3",
"= fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096,",
"learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True)",
"None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\"",
"= L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384,",
"= L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2",
"= L.ReLU(n.conv3, in_place=True) if layers == '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True),",
"n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss",
"scale the images :param contrastive_margin: int. Margin for the contrastive loss layer :param",
"contrastive loss layer on top :param lmdb_path: str. Path to train LMDB :param",
"n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNNs n.fc1 = L.InnerProduct(n.norm2,",
"L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p",
"num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label)",
"L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1",
"param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p,",
"to train LMDB :param labels_lmdb_path: str. Path to train LMDB labels :param test_lmdb:",
"n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout = fcxinput = fcyinput = fczinput",
"L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b',",
"n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)],",
"= L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n,",
"n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x',",
"num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego =",
"the AlexNet architecture :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str.",
"@staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a",
"L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if",
"fcyinput = fczinput = n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True),",
"param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1,",
"if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8",
"bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)],",
"L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx,",
"scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler,",
"n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx,",
"architecture :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path to",
"input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels for MNIST n.data0, n.data1 =",
"n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p =",
"a protoxt for siamese AlexNet architecture with a contrastive loss layer on top",
"ntop=2) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNNs",
"in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75)",
"= L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet",
"= fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput = fczinput =",
"learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)],",
"from which layer we will extract features to train a classifier :returns: Caffe",
"L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput = fczinput = n.relu3 # Classifiers n.fcx",
"paper :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path to",
"layers from scratch :param layers: str. from which layer we will extract features",
"test_lmdb: str. Path to train LMDB :param test_labels_lmdb: str. Path to test LMDB",
"'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10,",
"test the 'health' # of the training process return n, ('loss',), ('acc',) @staticmethod",
"images :param contrastive_margin: int. Margin for the contrastive loss layer :param is_train: bool.",
"bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all),",
"n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input,",
"n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput,",
"alpha=1e-4, beta=0.75) if layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b',",
"caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates",
"= L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True)",
"= L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx)",
"classifier_name: str. name of the top classifier :param learn_all: bool. Flag indicating if",
"weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1",
"to train a classifier :returns: Caffe NetSpec, tuple with names of loss blobs,",
"= L.ReLU(n.conv5, in_place=True) if not is_imagenet: if layers == '5': n.fc_prev = L.InnerProduct(n.relu5,",
"param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6,",
"= L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5",
":param lmdb_path: str. Path to train LMDB :param batch_size: int. Batch size :param",
"return n, ('contrastive',), None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0,",
"= L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 =",
"= L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None,",
"in_place=True) else: fcxinput = fcyinput = fczinput = n.relu3 # Classifiers n.fcx =",
"architecture with a contrastive loss layer on top :param lmdb_path: str. Path to",
"layer we will extract features to train a classifier :returns: Caffe NetSpec, tuple",
"is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8 =",
"pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if layers",
"n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop = fcxinput = fcyinput = fczinput",
"accuracy blobs \"\"\" n = caffe.NetSpec() phase = caffe.TRAIN if is_train else caffe.TEST",
"= fczinput = n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b',",
"bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True)",
"\"\"\" Creates a protoxt for the AlexNet architecture :param lmdb_path: str. Path to",
"fc10input = n.relu3 # Learn all true because we always want to train",
"with name of accuracy blobs \"\"\" n = caffe.NetSpec() phase = caffe.TRAIN if",
"learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if layers == '4':",
"n.label, include=dict(phase=caffe.TEST)) else: if layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True),",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7,",
"to train LMDB :param batch_size: int. Batch size :param scale: float. How to",
"L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) #",
"Flag indicating if we should learn all the layers from scratch :returns: Caffe",
"learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 = fc7input =",
"fcxinput = fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput",
"return n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all),",
"= L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2",
"bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p =",
"('contrastive',), None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True):",
"siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for",
"def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates",
"scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a protoxt for the AlexNet",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p =",
"architecture for the MNIST experiment Uses Contrastive loss :param lmdb_path: str. Path to",
"n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the name of the loss/acc",
"in_place=True) else: fc10input = n.relu3 # Learn all true because we always want",
"bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 = fc8input =",
"the contrastive loss layer :param is_train: bool. Flag indicating if this is for",
"('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0)",
"= L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers",
"scale: float. How to scale the images :param is_train: bool. Flag indicating if",
"n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0)",
"in the paper :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str.",
"the top classifier :param learn_all: bool. Flag indicating if we should learn all",
"n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500,",
"= L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y',",
"= L.ReLU(n.fc500, in_place=True) if is_train: n.dropout = fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input",
"labels :param batch_size: int. Batch size :param scale: float. How to scale the",
"bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 = fc7input",
"= L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True)",
"learn_all=True): \"\"\" Creates a protoxt similar to the first layers of AlexNet architecture",
"= caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice",
"= fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput =",
"n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2",
"classifier :param classifier_name: str. name of the top classifier :param learn_all: bool. Flag",
"the images :param contrastive_margin: int. Margin for the contrastive loss layer :param is_train:",
"n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss",
"('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler,",
"a protoxt for the AlexNet architecture for the MNIST experiment Uses Egomotion as",
"which layer we will extract features to train a classifier :returns: Caffe NetSpec,",
"= L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p,",
"can track to test the 'health' # of the training process return n,",
"labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the",
"n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w',",
"= L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss =",
"input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w',",
"n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2,",
"alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)],",
"('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False):",
"learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True),",
"indicating if we should learn all the layers from scratch :returns: Caffe NetSpec,",
"n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11,",
"dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput = fczinput = n.relu8 # Classifiers n.fcx",
"bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"train the top classifier no matter if we are training from scratch or",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z =",
"LMDB labels :param test_lmdb: str. Path to train LMDB :param test_labels_lmdb: str. Path",
"= L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input",
"local_size=5, alpha=1e-4, beta=0.75) if layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True),",
"= L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500,",
"learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 =",
"n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b',",
"learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely)",
"transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler,",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"a protoxt for the AlexNet architecture for the MNIST experiment Uses Contrastive loss",
":param is_train: bool. Flag indicating if this is for testing or training :returns:",
"scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt for the AlexNet architecture :param lmdb_path:",
"for the AlexNet architecture for the MNIST experiment Uses Contrastive loss :param lmdb_path:",
"loss blobs, tuple with name of accuracy blobs \"\"\" n = caffe.NetSpec() n.data,",
"similar to the first layers of AlexNet architecture for the MNIST experiment :param",
"bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc = L.Accuracy(n.fc8_imgnet,",
"MNIST experiment Uses Contrastive loss :param lmdb_path: str. Path to train LMDB :param",
"alpha=1e-4, beta=0.75) if layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b',",
"slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False)",
"for the top classifier :param classifier_name: str. name of the top classifier :param",
"n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p = bcnn(n.data0,",
"str. Path to train LMDB labels :param batch_size: int. Batch size :param scale:",
"= L.ReLU(n.conv4, in_place=True) if layers == '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True),",
"learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n,",
"fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput = fczinput",
"= L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers == '5':",
"include=dict(phase=caffe.TEST)) else: if layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b',",
"is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a protoxt for the AlexNet architecture",
"n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"loss layer on top :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path:",
"accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale,",
"Creates a protoxt for the AlexNet architecture for the MNIST experiment Uses Egomotion",
"L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126,",
"for the MNIST experiment Uses Egomotion as stated in the paper :param lmdb_path:",
"L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx,",
"stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True),",
"= L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input",
"batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet architecture",
"L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w',",
"'5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev =",
"if this is for testing or training :param num_classes: int. number of classes",
"n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096,",
"n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p,",
"in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p =",
"P) from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125,",
"Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy =",
"learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)],",
"= L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes,",
"n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z')",
"the top classifier no matter if we are training from scratch or finetuning",
"test LMDB labels :param batch_size: int. Batch size :param scale: float. How to",
"bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 =",
"n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)],",
"n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss",
"L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all,",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p",
"alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3",
"num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train:",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label,",
"relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc,",
"matter if we are training from scratch or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10,",
"fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc =",
"param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train: n.drop6",
"siamese AlexNet architecture with a contrastive loss layer on top :param lmdb_path: str.",
"num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p =",
"n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1",
"n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train: n.dropout = fc10input",
"= bcnn(n.data0, n.data1, n, learn_all, False) # TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w',",
"n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2,",
"= L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True)",
"not is_imagenet: if layers == '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b',",
"n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500,",
"Flag indicating if this is for testing or training :param num_classes: int. number",
"L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1,",
"is_imagenet=False): \"\"\" Creates a protoxt for the AlexNet architecture :param lmdb_path: str. Path",
"L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate,",
"learn_all, True) # TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000,",
"= L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True)",
"n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None,",
"L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1,",
"architecture for the MNIST experiment :param lmdb_path: str. Path to train LMDB :param",
"scratch :param layers: str. from which layer we will extract features to train",
"learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes,",
"because then we can # know which outputs of the net we can",
"bcnn(n.data0, n.data1, n, learn_all, True) # TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True),",
"bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w',",
"scale the images :param is_train: bool. Flag indicating if this is for testing",
"LMDB :param labels_lmdb_path: str. Path to train LMDB labels :param test_lmdb: str. Path",
"('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6",
"with name of accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path,",
"the 'health' # of the training process return n, ('loss',), ('acc',) @staticmethod def",
"num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label)",
"= n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc,",
"learn_all=True): \"\"\" Creates a protoxt for the AlexNet architecture :param lmdb_path: str. Path",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6,",
"How to scale the images :param is_train: bool. Flag indicating if this is",
"L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the name of the",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w',",
"scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet architecture",
"Path to train LMDB :param batch_size: int. Batch size :param scale: float. How",
"L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 =",
"fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput = fczinput = n.relu3 #",
"bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',),",
"testing or training :returns: Caffe NetSpec, tuple with names of loss blobs, tuple",
"n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7,",
"batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all),",
"is for testing or training :param learn_all: bool. Flag indicating if we should",
"learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)],",
"learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train: n.dropout =",
"layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True,",
"this is for testing or training :returns: Caffe NetSpec, tuple with names of",
"blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train)",
"experiment Uses Contrastive loss :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path:",
"# BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNNs n.fc1",
"n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) #",
"fcxinput = fcyinput = fczinput = n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20,",
"('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 =",
"L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4,",
"bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 =",
"LMDB labels :param batch_size: int. Batch size :param scale: float. How to scale",
"fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"(layers as L, params as P) from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class",
"= L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w',",
"n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the name",
"n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc,",
"blobs \"\"\" n = caffe.NetSpec() phase = caffe.TRAIN if is_train else caffe.TEST n.data,",
"= L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4",
"= L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss =",
"n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1,",
"param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if not is_imagenet:",
"n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNN n.concat = L.Concat(n.norm2, n.norm2_p,",
"is_train else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1",
"= L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True)",
"n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train: n.dropout",
"train LMDB labels :param batch_size: int. Batch size :param scale: float. How to",
"L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p",
"L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b',",
":param labels_lmdb_path: str. Path to train LMDB labels :param test_lmdb: str. Path to",
"learn_all=True): \"\"\" Creates a protoxt for siamese AlexNet architecture with a contrastive loss",
"labels_lmdb_path: str. Path to train LMDB labels :param test_lmdb: str. Path to train",
"n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else:",
"if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning",
"is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8_imgnet =",
"train LMDB :param labels_lmdb_path: str. Path to train LMDB labels :param batch_size: int.",
"L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) #",
"bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy,",
"n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx,",
"if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if",
"caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a",
"is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7 =",
"# Learn all true because we always want to train the top classifier",
"n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',)",
"stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers == '2': n.fc_intermediate =",
"= L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a protoxt for siamese AlexNet",
"= fcxinput = fcyinput = fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput",
"in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0)",
"slice_point=3), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5,",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label,",
"num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True),",
"= L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input",
"n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput,",
"or training :param num_classes: int. number of classes for the top classifier :param",
"TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w',",
"param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc",
"== '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev",
"mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3),",
"param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev,",
"backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b',",
"n.relu4 = L.ReLU(n.conv4, in_place=True) if layers == '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w',",
"'5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a protoxt for the AlexNet architecture :param",
"n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input,",
"relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500,",
"learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True)",
"learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)],",
"= L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3)",
"labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a protoxt for siamese",
"def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt for",
"will extract features to train a classifier :returns: Caffe NetSpec, tuple with names",
"n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6,",
"L.ReLU(n.fc500, in_place=True) if is_train: n.dropout = fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input =",
"num_classes: int. number of classes for the top classifier :param classifier_name: str. name",
"# Returning the name of the loss/acc layers is useful because then we",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label,",
"= caffe.NetSpec() phase = caffe.TRAIN if is_train else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase),",
"str. Path to test LMDB labels :param batch_size: int. Batch size :param scale:",
"for the AlexNet architecture :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path:",
"n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5,",
"bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100,",
"num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if",
"MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p =",
"for siamese AlexNet architecture with a contrastive loss layer on top :param lmdb_path:",
"learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)],",
"in_place=True) else: fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)],",
"in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)],",
"'4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev =",
"ntop=3) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNN",
"bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w',",
"L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 =",
"architecture for the MNIST experiment Uses Egomotion as stated in the paper :param",
"bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3,",
"('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5',",
"in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)],",
"# BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNN n.concat",
"we can # know which outputs of the net we can track to",
"n.data1, n, learn_all, False) # TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b',",
"= L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w',",
"L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all,",
"= n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc,",
"Batch size :param scale: float. How to scale the images :param is_train: bool.",
"experiment Uses Egomotion as stated in the paper :param lmdb_path: str. Path to",
"L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive",
"bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10,",
"is_train=True, learn_all=True): \"\"\" Creates a protoxt similar to the first layers of AlexNet",
"learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y =",
"num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin))",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6,",
"learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3,",
"# TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256,",
"= L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True)",
"L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers ==",
"param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2,",
":param scale: float. How to scale the images :param contrastive_margin: int. Margin for",
"num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 =",
"num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx)",
"slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN",
"n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]),",
"source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)],",
"L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p",
"L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc,",
"we always want to train the top classifier no matter if we are",
"because we always want to train the top classifier no matter if we",
"L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b',",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None",
"the top classifier :param classifier_name: str. name of the top classifier :param learn_all:",
"L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w',",
"mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt for the AlexNet architecture",
"= L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True),",
"in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p =",
"for testing or training :returns: Caffe NetSpec, tuple with names of loss blobs,",
"= L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels for",
"MNIST experiment Uses Egomotion as stated in the paper :param lmdb_path: str. Path",
"names of loss blobs, tuple with name of accuracy blobs \"\"\" n =",
"MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label,",
"caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data,",
":param num_classes: int. number of classes for the top classifier :param classifier_name: str.",
"is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc = L.Accuracy(n.fc8_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',),",
"L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler,",
"n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2,",
"n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 =",
"include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None,",
"is_train: n.drop = fcxinput = fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else:",
"KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a",
"train a classifier :returns: Caffe NetSpec, tuple with names of loss blobs, tuple",
"if is_train else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2)",
"= L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500,",
"n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev,",
"bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 = fc8input",
"param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy,",
"protoxt for the AlexNet architecture for the MNIST experiment Uses Contrastive loss :param",
"loss layer :param is_train: bool. Flag indicating if this is for testing or",
"bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100,",
"data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2,",
"AlexNet architecture with a contrastive loss layer on top :param lmdb_path: str. Path",
"== '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev",
"L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all),",
"def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt similar to the",
"in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if",
"n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1,",
"indicating if this is for testing or training :returns: Caffe NetSpec, tuple with",
"slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True)",
"tuple with names of loss blobs, tuple with name of accuracy blobs \"\"\"",
"to the first layers of AlexNet architecture for the MNIST experiment :param lmdb_path:",
"learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc =",
"n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss",
"L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label,",
"Egomotion as stated in the paper :param lmdb_path: str. Path to train LMDB",
"('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a",
"group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if layers",
"bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True) if layers == '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000,",
"contrastive loss layer :param is_train: bool. Flag indicating if this is for testing",
"@staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt",
"num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True),",
"beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler,",
"L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2,",
"protoxt similar to the first layers of AlexNet architecture for the MNIST experiment",
"float. How to scale the images :param contrastive_margin: int. Margin for the contrastive",
"n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4,",
"scale=scale, is_train=is_train) # Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1),",
"L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3 =",
"L, params as P) from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod",
"n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2,",
"n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if",
"True) # TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"int. Batch size :param scale: float. How to scale the images :param is_train:",
"batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet",
"n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev,",
"L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w',",
"= L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True),",
"if layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc,",
"L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate",
"is_train: n.dropout = fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3 # Learn",
"a protoxt similar to the first layers of AlexNet architecture for the MNIST",
"n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0)",
"bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if layers == '3': n.fc_prev",
"n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1,",
"learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2)",
"slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) #",
"learn all the layers from scratch :returns: Caffe NetSpec, tuple with names of",
"* caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\"",
"kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2,",
"BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNN n.concat =",
"if layers == '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc,",
"n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice",
"= n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"# BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNN n.concat",
"the AlexNet architecture for the MNIST experiment Uses Contrastive loss :param lmdb_path: str.",
"= fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096,",
"True) # TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w',",
"def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt",
"L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b',",
"n = caffe.NetSpec() phase = caffe.TRAIN if is_train else caffe.TEST n.data, n.label =",
"#!/usr/bin/env python2.7 import caffe from caffe import (layers as L, params as P)",
"= bcnn(n.data0, n.data1, n, learn_all, True) # TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w',",
"num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate =",
"is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet architecture for the",
"bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz =",
"Flag indicating if this is for testing or training :param learn_all: bool. Flag",
"= L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3 # Learn all true because we",
"Margin for the contrastive loss layer :param is_train: bool. Flag indicating if this",
"n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2,",
"== '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev",
":param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path to train",
"scratch or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z",
"n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3,",
"sfa=False): \"\"\" Creates a protoxt for the AlexNet architecture for the MNIST experiment",
"= L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)],",
"siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the",
"n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1,",
"kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256,",
"L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b',",
"n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the name of the loss/acc layers",
"bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2,",
"to train LMDB labels :param batch_size: int. Batch size :param scale: float. How",
"n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b',",
"= L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the name of the loss/acc layers is",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST))",
"n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p = bcnn(n.data0,",
"str. from which layer we will extract features to train a classifier :returns:",
"L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True),",
"n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"the layers from scratch :returns: Caffe NetSpec, tuple with names of loss blobs,",
"standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt similar to the first",
"all the layers from scratch :returns: Caffe NetSpec, tuple with names of loss",
"bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if layers == '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000,",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop = fcxinput =",
"Path to train LMDB :param labels_lmdb_path: str. Path to train LMDB labels :param",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc = L.Accuracy(n.fc8_imgnet, n.label, include=dict(phase=caffe.TEST))",
"input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data,",
"n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy,",
"= L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss =",
"L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8",
"bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc = L.Accuracy(n.fc8_imgnet, n.label, include=dict(phase=caffe.TEST)) return",
"ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p",
"Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz =",
"L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers ==",
"bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) #",
"('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10,",
"bool. Flag indicating if this is for testing or training :param num_classes: int.",
"Creates a protoxt for siamese AlexNet architecture with a contrastive loss layer on",
"local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"beta=0.75) if layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)],",
"testing or training :param learn_all: bool. Flag indicating if we should learn all",
"if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7",
"L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y",
"n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3,",
"if is_train: n.dropout = fcxinput = fcyinput = fczinput = L.Dropout(n.relu3, in_place=True) else:",
"fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3 # Learn all true because",
"the layers from scratch :param layers: str. from which layer we will extract",
"Path to train LMDB labels :param test_lmdb: str. Path to train LMDB :param",
"train LMDB :param labels_lmdb_path: str. Path to train LMDB labels :param test_lmdb: str.",
"from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0,",
"if we should learn all the layers from scratch :param layers: str. from",
"n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"ntop=2) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNNs",
"AlexNet architecture for the MNIST experiment Uses Contrastive loss :param lmdb_path: str. Path",
"layer on top :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str.",
"Flag indicating if this is for testing or training :returns: Caffe NetSpec, tuple",
"('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler,",
"= L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y",
"this is for testing or training :param num_classes: int. number of classes for",
"= L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 =",
"str. Path to train LMDB :param labels_lmdb_path: str. Path to train LMDB labels",
"images :param is_train: bool. Flag indicating if this is for testing or training",
"str. name of the top classifier :param learn_all: bool. Flag indicating if we",
"learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX,",
"L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w',",
"L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input =",
"else: fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc,",
"weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if not is_imagenet: if layers == '5':",
"the loss/acc layers is useful because then we can # know which outputs",
"Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5, relu5_p",
"n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w',",
"n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w',",
"labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a protoxt",
"L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1,",
"for the AlexNet architecture for the MNIST experiment Uses Egomotion as stated in",
"return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None,",
"layer :param is_train: bool. Flag indicating if this is for testing or training",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 =",
"num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True),",
"if layers == '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc,",
"learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128,",
"L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST)) # Returning the name of the loss/acc layers is useful",
"is_train: bool. Flag indicating if this is for testing or training :returns: Caffe",
"L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w',",
"= L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6",
"standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a",
"class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates",
"from scratch :returns: Caffe NetSpec, tuple with names of loss blobs, tuple with",
"learn_all, True) # TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"of accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size,",
"pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if",
"classes for the top classifier :param classifier_name: str. name of the top classifier",
"n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNN n.concat = L.Concat(n.norm2,",
"learn_all, False) # TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"we should learn all the layers from scratch :param layers: str. from which",
"= L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB, source=lmdb_path, transform_param=dict(scale=scale), ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96,",
"kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w',",
"num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4, in_place=True)",
"= L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput = fczinput = n.relu8 #",
"L.ReLU(n.conv3, in_place=True) if layers == '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b',",
"num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True)",
"n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x",
"tuple with name of accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label =",
"or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path to train LMDB",
"num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True) n.pool1 =",
"param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y",
"= L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True)",
"= fcyinput = fczinput = n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w',",
"is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers",
"bias_filler=bias_filler_1) if is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z =",
"LMDB :param batch_size: int. Batch size :param scale: float. How to scale the",
"= fcxinput = fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput =",
"learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc =",
"the paper :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path",
"in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 =",
"= L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class KITTINetFactory: @staticmethod def",
"= L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3)",
"n.dropout = fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3 # Learn all",
"a classifier :returns: Caffe NetSpec, tuple with names of loss blobs, tuple with",
"'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates",
"return n, ('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397,",
"all true because we always want to train the top classifier no matter",
"fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w',",
"num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True),",
"bool. Flag indicating if this is for testing or training :returns: Caffe NetSpec,",
"in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6",
"L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST))",
"num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 =",
"n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST))",
"bool. Flag indicating if we should learn all the layers from scratch :param",
"L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate",
"= fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput = fczinput = n.relu3",
"learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc =",
"relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNNs n.fc1 = L.InnerProduct(relu5,",
"n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else:",
"classifier no matter if we are training from scratch or finetuning n.fc10 =",
"= L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True)",
"slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) #",
"we can track to test the 'health' # of the training process return",
"'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True): \"\"\"",
"ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p",
"NetSpec, tuple with names of loss blobs, tuple with name of accuracy blobs",
"= n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"# BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNNs n.fc1",
"param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3,",
"num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train:",
"= fcyinput = fczinput = n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w',",
"n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3",
"bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2",
"slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN",
"scratch :returns: Caffe NetSpec, tuple with names of loss blobs, tuple with name",
"n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1,",
"ntop=2) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0)",
"n, ('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True,",
"= L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True)",
"L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate,",
"'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=False,",
"bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else:",
"learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 =",
"n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1,",
"param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc",
"in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive =",
"n.conv7 = L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7",
"else: fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc,",
"'2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1, in_place=True)",
"slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True)",
"L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet,",
"L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label,",
"n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput,",
"L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4,",
"n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3,",
"= L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125,",
"n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]),",
"bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p",
"kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True)",
"n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss",
"param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b',",
"in_place=True) if layers == '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)],",
"n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0,",
"stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers == '1': n.fc_intermediate =",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod",
"else: fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc,",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"extract features to train a classifier :returns: Caffe NetSpec, tuple with names of",
"n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"we are training from scratch or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True),",
"data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz",
"n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p =",
"weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b',",
"track to test the 'health' # of the training process return n, ('loss',),",
"L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p",
"know which outputs of the net we can track to test the 'health'",
"param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train: n.drop7",
"batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt for the AlexNet architecture :param",
"true because we always want to train the top classifier no matter if",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p",
"n, learn_all, False) # TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)],",
"caffe import (layers as L, params as P) from layers_wrappers import * caffe.set_device(0)",
"in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive =",
"bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p =",
"n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego,",
"then we can # know which outputs of the net we can track",
"useful because then we can # know which outputs of the net we",
"fcyinput = fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput = fczinput =",
"num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True),",
"'health' # of the training process return n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None,",
"n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11,",
"bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate,",
"Path to train LMDB labels :param batch_size: int. Batch size :param scale: float.",
"python2.7 import caffe from caffe import (layers as L, params as P) from",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b',",
"('loss',), ('acc',) n.conv4 = L.Convolution(n.relu3, kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)],",
"param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return",
"layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2,",
"BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all, True) # TCNNs n.fc1 =",
"L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w',",
"n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w',",
"param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if is_train: n.drop6",
"include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)],",
"is_train=True, learn_all=True): \"\"\" Creates a protoxt for siamese AlexNet architecture with a contrastive",
"the name of the loss/acc layers is useful because then we can #",
"beta=0.75) if layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)],",
"include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w',",
"to scale the images :param is_train: bool. Flag indicating if this is for",
"Creates a protoxt similar to the first layers of AlexNet architecture for the",
"L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6_imgnet, in_place=True) if",
"bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 = fc7input",
"stated in the paper :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path:",
"the MNIST experiment :param lmdb_path: str. Path to train LMDB :param batch_size: int.",
"of the net we can track to test the 'health' # of the",
"else: fc10input = n.relu3 # Learn all true because we always want to",
"= L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 =",
"n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0,",
"bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7, num_output=500, param=[weight_param('fc7_ego_w', learn_all=True), bias_param('fc7_ego_b', learn_all=True)],",
"import caffe from caffe import (layers as L, params as P) from layers_wrappers",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train: n.dropout = fc10input = L.Dropout(n.relu3,",
"n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc,",
"layers == '3': n.fc_prev = L.InnerProduct(n.relu3, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b',",
"else: if layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)],",
"blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale,",
"= n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7",
"= L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True),",
"accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size,",
"of AlexNet architecture for the MNIST experiment :param lmdb_path: str. Path to train",
"kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5,",
"n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input,",
"= n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7",
"beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 =",
"param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc",
"int. Margin for the contrastive loss layer :param is_train: bool. Flag indicating if",
"n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod def standar(lmdb_path=None,",
"n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None,",
"train LMDB labels :param test_lmdb: str. Path to train LMDB :param test_labels_lmdb: str.",
"n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b',",
"if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n,",
"'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True,",
"= L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True),",
"AlexNet architecture :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path",
"in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75)",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST))",
"labels_lmdb_path: str. Path to train LMDB labels :param batch_size: int. Batch size :param",
"learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu5 = L.ReLU(n.conv5, in_place=True) if not is_imagenet: if",
"n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input,",
"learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True)",
"tuple with name of accuracy blobs \"\"\" n = caffe.NetSpec() phase = caffe.TRAIN",
"n, learn_all, True) # TCNNs n.fc1 = L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)],",
"layers == '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w',",
"= input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels for MNIST n.data0, n.data1",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z",
"n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class KITTINetFactory: @staticmethod",
"name of accuracy blobs \"\"\" n = caffe.NetSpec() phase = caffe.TRAIN if is_train",
"= bcnn(n.data0, n.data1, n, learn_all, False) # TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1))",
"fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"n.data1, n, learn_all, True) # TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 =",
"contrastive_margin=10, is_train=True, learn_all=True): \"\"\" Creates a protoxt for siamese AlexNet architecture with a",
"= caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels",
"L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w',",
"scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt similar to the first layers of",
"to train LMDB :param test_labels_lmdb: str. Path to test LMDB labels :param batch_size:",
"n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else:",
"bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop = fcxinput = fcyinput =",
"labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data,",
"to test LMDB labels :param batch_size: int. Batch size :param scale: float. How",
"('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)],",
"include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z = L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n,",
"of loss blobs, tuple with name of accuracy blobs \"\"\" n = caffe.NetSpec()",
"slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) #",
"Creates a protoxt for the AlexNet architecture for the MNIST experiment Uses Contrastive",
"if we are training from scratch or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w',",
"indicating if this is for testing or training :param num_classes: int. number of",
"weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2",
"L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input =",
"pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers == '1':",
"bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True)",
"= L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True)",
"learn all the layers from scratch :param layers: str. from which layer we",
"LMDB :param labels_lmdb_path: str. Path to train LMDB labels :param batch_size: int. Batch",
"for testing or training :param learn_all: bool. Flag indicating if we should learn",
"the MNIST experiment Uses Contrastive loss :param lmdb_path: str. Path to train LMDB",
"the training process return n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0,",
"@staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt similar to",
"num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label)",
"L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3 # Learn all true because we always",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu8 = L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop = fcxinput = fcyinput",
"include=dict(phase=caffe.TEST)) # Returning the name of the loss/acc layers is useful because then",
"= L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc,",
"('acc',) n.fc6_imgnet = L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 =",
"from caffe import (layers as L, params as P) from layers_wrappers import *",
"= L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 =",
"= L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput = fczinput = n.relu3 # Classifiers",
":param scale: float. How to scale the images :param is_train: bool. Flag indicating",
"n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2,",
"learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 =",
"= fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes,",
"n.data1, n, learn_all, False) # TCNN n.concat = L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 =",
"training :param num_classes: int. number of classes for the top classifier :param classifier_name:",
"= L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv4",
"L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y =",
"bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc,",
"always want to train the top classifier no matter if we are training",
"bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True) if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True)",
"batch_size: int. Batch size :param scale: float. How to scale the images :param",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label,",
"= L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers == '2': n.fc_intermediate = L.InnerProduct(n.norm2, num_output=num_classes,",
"n.fc7_imgnet = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet,",
"n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss",
"is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely,",
"for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN n.norm2, n.norm2_p",
"n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 =",
"include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w',",
"batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)],",
"L.InnerProduct(n.norm2, num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if",
"learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet architecture for the MNIST",
"n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(relu5_p,",
"'1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"of classes for the top classifier :param classifier_name: str. name of the top",
"n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',)",
"classifier :returns: Caffe NetSpec, tuple with names of loss blobs, tuple with name",
"to train the top classifier no matter if we are training from scratch",
"stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6 = L.ReLU(n.conv6, in_place=True) n.conv7",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8_imgnet, n.label) n.acc = L.Accuracy(n.fc8_imgnet, n.label,",
"loss blobs, tuple with name of accuracy blobs \"\"\" n = caffe.NetSpec() phase",
"if is_train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8_imgnet",
"L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu1 = L.ReLU(n.conv1,",
"size :param scale: float. How to scale the images :param is_train: bool. Flag",
"if this is for testing or training :returns: Caffe NetSpec, tuple with names",
"this is for testing or training :param learn_all: bool. Flag indicating if we",
"fcxinput = fcyinput = fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput =",
"with names of loss blobs, tuple with name of accuracy blobs \"\"\" n",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 = L.InnerProduct(n.relu3,",
"int. number of classes for the top classifier :param classifier_name: str. name of",
"batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1,",
"param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout",
"learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a protoxt for the AlexNet architecture :param lmdb_path:",
"('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates",
"of the loss/acc layers is useful because then we can # know which",
"n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) n.labelx, n.labely, n.labelz = L.Slice(n.label, slice_param=dict(axis=1,",
"n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.fc6 = L.InnerProduct(n.relu5, num_output=4096,",
"str. Path to train LMDB :param test_labels_lmdb: str. Path to test LMDB labels",
"contrastive_margin=10, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt for the AlexNet architecture for",
"class MNISTNetFactory: @staticmethod def standar(lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt",
"if is_train: n.dropout = fc10input = L.Dropout(n.relu3, in_place=True) else: fc10input = n.relu3 #",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate = L.InnerProduct(n.relu_prev, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True),",
"we will extract features to train a classifier :returns: Caffe NetSpec, tuple with",
"with a contrastive loss layer on top :param lmdb_path: str. Path to train",
"L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7 = L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b',",
"fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w',",
"the AlexNet architecture for the MNIST experiment Uses Egomotion as stated in the",
"num_output=500, param=[weight_param('fc500_w', learn_all=True), bias_param('fc500_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train:",
"L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers == '5': n.fc_imgnet",
"features to train a classifier :returns: Caffe NetSpec, tuple with names of loss",
"@staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\"",
"else: fcxinput = fcyinput = fczinput = n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput,",
"= L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes,",
"\"\"\" n = caffe.NetSpec() phase = caffe.TRAIN if is_train else caffe.TEST n.data, n.label",
"BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) # TCNN n.concat =",
"n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256, pad=2, group=2,",
"= bcnn(n.data0, n.data1, n, learn_all, True) # TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1))",
"n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None,",
"n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000,",
"blobs, tuple with name of accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label",
"is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0)",
"= L.ReLU(n.fc7_ego, in_place=True) if is_train: n.drop = fcxinput = fcyinput = fczinput =",
"= L.Accuracy(n.fcz, n.labelz, include=dict(phase=caffe.TEST)) return n, ('loss_x', 'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod",
"n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3,",
"protoxt for the AlexNet architecture for the MNIST experiment Uses Egomotion as stated",
"# know which outputs of the net we can track to test the",
"slice_point=3), ntop=2) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False) #",
"train LMDB :param batch_size: int. Batch size :param scale: float. How to scale",
"n.drop = fcxinput = fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST))",
"contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125,",
"batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2)",
"num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label)",
"weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu3 = L.ReLU(n.conv3, in_place=True) if layers == '3': n.fc_prev = L.InnerProduct(n.relu3,",
"in_place=True) if is_train: n.dropout = fcxinput = fcyinput = fczinput = L.Dropout(n.relu3, in_place=True)",
"kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True)",
"n.labelz) n.acc_x = L.Accuracy(n.fcx, n.labelx, include=dict(phase=caffe.TEST)) n.acc_y = L.Accuracy(n.fcy, n.labely, include=dict(phase=caffe.TEST)) n.acc_z =",
"labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt for the AlexNet",
"layers == '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"if is_train: n.drop = fcxinput = fcyinput = fczinput = L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True)",
"TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b',",
"else: fcxinput = fcyinput = fczinput = n.relu3 # Classifiers n.fcx = L.InnerProduct(fcxinput,",
"training :param learn_all: bool. Flag indicating if we should learn all the layers",
"as L, params as P) from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory:",
"L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b',",
"contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None @staticmethod def standar(lmdb_path=None, labels_lmdb_path=None, batch_size=126, mean_file=None, scale=1.0, is_train=True,",
"n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers == '5': n.fc_imgnet =",
"mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all), bias_param('conv1_b',",
"= L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True)",
"import (layers as L, params as P) from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu()",
"n.fc2 = L.InnerProduct(n.relu3, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p,",
"= L.Concat(relu5, relu5_p, concat_param=dict(axis=1)) n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b',",
"param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b',",
"n.fc1_p = L.InnerProduct(relu5_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p,",
"train LMDB :param test_labels_lmdb: str. Path to test LMDB labels :param batch_size: int.",
"num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y =",
"param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p,",
"== '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"# TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6",
"AlexNet architecture for the MNIST experiment Uses Egomotion as stated in the paper",
"n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5, relu5_p = bcnn(n.data0,",
"return n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False):",
"@staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, is_train=True, learn_all=False, sfa=False): \"\"\" Creates a protoxt",
"= L.InnerProduct(n.relu6_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p,",
"Uses Egomotion as stated in the paper :param lmdb_path: str. Path to train",
"L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev, in_place=True) n.fc_intermediate",
"Returning the name of the loss/acc layers is useful because then we can",
"return n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all),",
"pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.fc500 = L.InnerProduct(n.norm2, num_output=500,",
"bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train: n.dropout = fc10input = L.Dropout(n.relu3, in_place=True)",
"kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers == '1': n.fc_intermediate",
"to scale the images :param contrastive_margin: int. Margin for the contrastive loss layer",
"top :param lmdb_path: str. Path to train LMDB :param labels_lmdb_path: str. Path to",
"from scratch or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc,",
"num_output=256, pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True)",
"a protoxt for the AlexNet architecture :param lmdb_path: str. Path to train LMDB",
"n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1",
"L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10,",
"batch_size=126, mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a protoxt for",
"training from scratch or finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)],",
"net we can track to test the 'health' # of the training process",
"caffe.NetSpec() phase = caffe.TRAIN if is_train else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size,",
"finetuning n.fc10 = L.InnerProduct(fc10input, num_output=10, param=[weight_param('fc10_w', learn_all=True), bias_param('fc10_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train:",
"param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 = L.ReLU(n.conv7, in_place=True) n.fc7_ego = L.InnerProduct(n.relu7,",
"bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p",
"training :returns: Caffe NetSpec, tuple with names of loss blobs, tuple with name",
"loss/acc layers is useful because then we can # know which outputs of",
"# TCNN n.concat = L.Concat(n.norm2, n.norm2_p, concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True),",
"n.relu6 = L.ReLU(n.fc6, in_place=True) if is_train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else:",
"= L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6, num_output=100, param=[weight_param('fc2_p_w', learn_all=True),",
"= L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv2 = L.Convolution(n.norm1, kernel_size=5, num_output=256,",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu3, in_place=True) n.fc2 =",
"= L.ReLU(n.conv2, in_place=True) n.pool2 = L.Pooling(n.relu2, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5,",
"mean_file=None, scale=1.0, is_train=True, num_classes=397, learn_all=True, layers='5', is_imagenet=False): \"\"\" Creates a protoxt for the",
"param=[weight_param('fc2_p_w', learn_all=True), bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b',",
"protoxt for siamese AlexNet architecture with a contrastive loss layer on top :param",
"('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256, pad=1, group=2, param=[weight_param('conv5_w', learn_all=learn_all), bias_param('conv5_b', learn_all=learn_all)],",
"L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1",
"which outputs of the net we can track to test the 'health' #",
"if layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w', learn_all=True), bias_param('fc_intermediate_b', learn_all=True)], weight_filler=weight_filler_fc,",
"kernel_size=3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) if layers == '2': n.fc_intermediate",
"\"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train)",
"= L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20,",
"name of the loss/acc layers is useful because then we can # know",
"of the training process return n, ('loss',), ('acc',) @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, batch_size=125,",
"learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"\"\"\" Creates a protoxt for siamese AlexNet architecture with a contrastive loss layer",
"bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc,",
":param contrastive_margin: int. Margin for the contrastive loss layer :param is_train: bool. Flag",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput, num_output=20, param=[weight_param('fcz_w', learn_all=True), bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"= fcyinput = fczinput = L.Dropout(n.relu3, in_place=True) else: fcxinput = fcyinput = fczinput",
"test_labels_lmdb: str. Path to test LMDB labels :param batch_size: int. Batch size :param",
"the MNIST experiment Uses Egomotion as stated in the paper :param lmdb_path: str.",
"fczinput = n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)],",
"L.InnerProduct(n.relu5, num_output=4096, param=[weight_param('fc6_w', learn_all=True), bias_param('fc6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc6, in_place=True) if",
"n.relu3 = L.ReLU(n.fc500, in_place=True) if is_train: n.dropout = fc10input = L.Dropout(n.relu3, in_place=True) else:",
"experiment :param lmdb_path: str. Path to train LMDB :param batch_size: int. Batch size",
"num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p =",
"= L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu3_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu3_p, num_output=100, param=[weight_param('fc2_p_w', learn_all=True),",
"TCNNs n.fc1 = L.InnerProduct(relu5, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 =",
"is_train: n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz, n.labelz)",
"return n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all), bias_param('conv3_b',",
"if we should learn all the layers from scratch :returns: Caffe NetSpec, tuple",
"L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w',",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.contrastive = L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class",
"if not is_imagenet: if layers == '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True),",
"L.Slice(n.label, slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN n.norm2, n.norm2_p = bcnn(n.data0, n.data1, n, learn_all,",
"Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2) # BCNN",
"n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8, n.label, include=dict(phase=caffe.TEST)) else: if layers ==",
"\"\"\" Creates a protoxt for the AlexNet architecture for the MNIST experiment Uses",
"= L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv5 = L.Convolution(n.relu4, kernel_size=3, num_output=256,",
"# Slice data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) n.labelx, n.labely, n.labelz",
"'loss_y', 'loss_z'), ('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True,",
"= L.Convolution(n.relu6, kernel_size=3, stride=2, num_output=128, param=[weight_param('conv7_w', learn_all=learn_all), bias_param('conv7_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu7 =",
"bias_param('fcz_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z",
"n.conv6 = L.Convolution(n.concat, kernel_size=3, stride=2, num_output=256, param=[weight_param('conv6_w', learn_all=learn_all), bias_param('conv6_b', learn_all=learn_all)], weight_filler=weight_filler_fc, bias_filler=bias_filler_0) n.relu6",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True) n.fc2 = L.InnerProduct(n.relu6,",
":param test_labels_lmdb: str. Path to test LMDB labels :param batch_size: int. Batch size",
"L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w', learn_all=True), bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8,",
"slice_param=dict(axis=1, slice_point=[1,2]), ntop=3) # BCNN relu5, relu5_p = bcnn(n.data0, n.data1, n, learn_all, False)",
"L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) if layers == '1': n.fc_intermediate = L.InnerProduct(n.norm1, num_output=num_classes, param=[weight_param('fc_intermediate_w',",
"to train LMDB :param labels_lmdb_path: str. Path to train LMDB labels :param batch_size:",
"as stated in the paper :param lmdb_path: str. Path to train LMDB :param",
"scale: float. How to scale the images :param contrastive_margin: int. Margin for the",
"bias_filler=bias_filler_1) n.relu3 = L.ReLU(n.fc1000, in_place=True) if is_train: n.dropout = fcxinput = fcyinput =",
"batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt similar to the first layers",
"= L.InnerProduct(fc7input, num_output=4096, param=[weight_param('fc7_w', learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7, in_place=True)",
"pad=2, group=2, param=[weight_param('conv2_w', learn_all=learn_all), bias_param('conv2_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu2 = L.ReLU(n.conv2, in_place=True) n.pool2",
"fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 n.fc8_imgnet = L.InnerProduct(fc8input, num_output=num_classes, param=[weight_param('fc8_w',",
"want to train the top classifier no matter if we are training from",
"n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu_prev = L.ReLU(n.fc_prev,",
"is_train: bool. Flag indicating if this is for testing or training :param num_classes:",
"fcyinput = fczinput = n.relu8 # Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=20, param=[weight_param('fcx_w', learn_all=True),",
"bias_param('fc2_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fc1_p = L.InnerProduct(n.norm2_p, num_output=500, param=[weight_param('fc1_p_w', learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc,",
"n, ('contrastive',), None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True,",
"n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, batch_size=batch_size, scale=scale, is_train=is_train) # Slice data/labels for MNIST n.data0,",
"of the top classifier :param learn_all: bool. Flag indicating if we should learn",
"as P) from layers_wrappers import * caffe.set_device(0) caffe.set_mode_gpu() class MNISTNetFactory: @staticmethod def standar(lmdb_path=None,",
"data/labels n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=3), ntop=2) # BCNN relu5, relu5_p =",
"of accuracy blobs \"\"\" n = caffe.NetSpec() phase = caffe.TRAIN if is_train else",
"# Classifiers n.fcx = L.InnerProduct(fcxinput, num_output=7, param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy",
"learn_all=True), bias_param('fc1_p_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6 = L.ReLU(n.fc1, in_place=True) n.dropout1 = L.Dropout(n.relu6, in_place=True)",
"param=[weight_param('fcx_w', learn_all=True), bias_param('fcx_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b',",
"labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4, num_output=96, param=[weight_param('conv1_w', learn_all=learn_all),",
":param labels_lmdb_path: str. Path to train LMDB labels :param batch_size: int. Batch size",
"of accuracy blobs \"\"\" n = caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file,",
"if this is for testing or training :param learn_all: bool. Flag indicating if",
"siamese_egomotion(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, is_train=True, learn_all=True): \"\"\" Creates a protoxt for the",
"bias_param('fc8_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc8, n.label) n.acc = L.Accuracy(n.fc8,",
"('acc_x', 'acc_y', 'acc_z') @staticmethod def siamese_contrastive(lmdb_path=None, labels_lmdb_path=None, mean_file=None, batch_size=125, scale=1.0, contrastive_margin=10, is_train=True, learn_all=True):",
"n.fcy = L.InnerProduct(fcyinput, num_output=7, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz = L.InnerProduct(fczinput,",
"bool. Flag indicating if we should learn all the layers from scratch :returns:",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcy = L.InnerProduct(fcyinput, num_output=20, param=[weight_param('fcy_w', learn_all=True), bias_param('fcy_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.fcz",
":param classifier_name: str. name of the top classifier :param learn_all: bool. Flag indicating",
"= L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2 =",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.loss_x = L.SoftmaxWithLoss(n.fcx, n.labelx) n.loss_y = L.SoftmaxWithLoss(n.fcy, n.labely) n.loss_z = L.SoftmaxWithLoss(n.fcz,",
"L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1,",
"the first layers of AlexNet architecture for the MNIST experiment :param lmdb_path: str.",
"L.ContrastiveLoss(n.fc2, n.fc2_p, n.label, contrastive_loss_param=dict(margin=contrastive_margin)) return n, ('contrastive',), None class KITTINetFactory: @staticmethod def siamese_egomotion(lmdb_path=None,",
"layers == '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1)",
"= L.ReLU(n.conv1, in_place=True) n.pool1 = L.Pooling(n.relu1, pool=P.Pooling.MAX, kernel_size=3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5,",
"or training :param learn_all: bool. Flag indicating if we should learn all the",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu6_p = L.ReLU(n.fc1_p, in_place=True) n.dropout1_p = L.Dropout(n.relu6_p, in_place=True) n.fc2_p = L.InnerProduct(n.relu6_p,",
"bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc_imgnet, n.label) n.acc = L.Accuracy(n.fc_imgnet, n.label, include=dict(phase=caffe.TEST)) return",
"name of the top classifier :param learn_all: bool. Flag indicating if we should",
"include=dict(phase=caffe.TEST)) return n, ('loss',), ('acc',) n.conv3 = L.Convolution(n.norm2, kernel_size=3, num_output=384, pad=1, param=[weight_param('conv3_w', learn_all=learn_all),",
"Caffe NetSpec, tuple with names of loss blobs, tuple with name of accuracy",
"concat_param=dict(axis=1)) n.fc1000 = L.InnerProduct(n.concat, num_output=1000, param=[weight_param('fc1000_w', learn_all=True), bias_param('fc1000_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu3 =",
"in_place=True) if not is_imagenet: if layers == '5': n.fc_prev = L.InnerProduct(n.relu5, num_output=1000, param=[weight_param('fc_prev_w',",
"n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 = L.Convolution(n.data, kernel_size=11, stride=4,",
"kernel_size=3, num_output=384, pad=1, group=2, param=[weight_param('conv4_w', learn_all=learn_all), bias_param('conv4_b', learn_all=learn_all)], weight_filler=weight_filler, bias_filler=bias_filler_0) n.relu4 = L.ReLU(n.conv4,",
"in_place=True) if layers == '4': n.fc_prev = L.InnerProduct(n.relu4, num_output=1000, param=[weight_param('fc_prev_w', learn_all=True), bias_param('fc_prev_b', learn_all=True)],",
"learn_all=True), bias_param('fc7_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) n.relu7 = L.ReLU(n.fc7_imgnet, in_place=True) if is_train: n.drop7 =",
"is_train=is_train) # Slice data/labels for MNIST n.data0, n.data1 = L.Slice(n.data, slice_param=dict(axis=1, slice_point=1), ntop=2)",
"L.Dropout(n.relu8, dropout_param=dict(dropout_ratio=0.5), in_place=True) else: fcxinput = fcyinput = fczinput = n.relu8 # Classifiers",
"top classifier no matter if we are training from scratch or finetuning n.fc10",
"== '5': n.fc_imgnet = L.InnerProduct(n.relu5, num_output=num_classes, param=[weight_param('fc_w', learn_all=True), bias_param('fc_b', learn_all=True)], weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if",
"weight_filler=weight_filler_fc, bias_filler=bias_filler_1) if is_train: n.loss = L.SoftmaxWithLoss(n.fc10, n.label) n.acc = L.Accuracy(n.fc10, n.label, include=dict(phase=caffe.TEST))",
"phase = caffe.TRAIN if is_train else caffe.TEST n.data, n.label = L.Data(include=dict(phase=phase), batch_size=batch_size, backend=P.Data.LMDB,",
"if is_train: n.loss = L.SoftmaxWithLoss(n.fc_intermediate, n.label) n.acc = L.Accuracy(n.fc_intermediate, n.label, include=dict(phase=caffe.TEST)) return n,",
"= caffe.NetSpec() n.data, n.label = input_layers(lmdb_path=lmdb_path, labels_lmdb_path=labels_lmdb_path, mean_file=mean_file, batch_size=batch_size, scale=scale, is_train=is_train) n.conv1 =",
"Learn all true because we always want to train the top classifier no"
] |
[
"np.matrix([9, -3, 1, -3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T # Example2 a =",
"-6], [4, 1, 0, -2], [1, 7, 1, 0]], dtype='float64') b = np.matrix([9,",
"import numpy as np # Example1 a = np.matrix([[0, 4, 5, 2], [1,",
"Example2 a = np.matrix([[2, 4, 6], [1, -1, 5], [4, 1, -2]], dtype='float64')",
"7, 21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T # for check sum ori_a =",
"np.matrix([[0, 4, 5, 2], [1, 0, 2, -6], [4, 1, 0, -2], [1,",
"j] / a[j, j] a[i] += p*a[j] print('extended coefficient matrix applied gauss method",
"for check sum ori_a = a # define extended coefficient matrix of eq",
"forward for i in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i, i+1:row], x[i+1:row]))/a[i, i] print('x={}'.format(x))",
"[1, 7, 1, 0]], dtype='float64') b = np.matrix([9, -3, 1, -3], dtype='float64').T x",
"1, -2]], dtype='float64') b = np.matrix([28, 7, 21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T",
"of eq ax=b a = np.concatenate([a, b], axis=1) (row, col) = a.shape for",
"/ a[j, j] a[i] += p*a[j] print('extended coefficient matrix applied gauss method \\n",
"# define extended coefficient matrix of eq ax=b a = np.concatenate([a, b], axis=1)",
"as np # Example1 a = np.matrix([[0, 4, 5, 2], [1, 0, 2,",
"coefficient matrix applied gauss method \\n a={}'.format(a)) # back forward for i in",
"x = np.matrix([None]*4, dtype='float64').T # Example2 a = np.matrix([[2, 4, 6], [1, -1,",
"a[[j, max_idx]] = a[[max_idx, j]] # push forward for i in range(j+1, row):",
"21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T # for check sum ori_a = a",
"1, 0]], dtype='float64') b = np.matrix([9, -3, 1, -3], dtype='float64').T x = np.matrix([None]*4,",
"-2]], dtype='float64') b = np.matrix([28, 7, 21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T #",
"-1, 5], [4, 1, -2]], dtype='float64') b = np.matrix([28, 7, 21], dtype='float64').T x",
"-3, 1, -3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T # Example2 a = np.matrix([[2,",
"= np.matrix([28, 7, 21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T # for check sum",
"a = np.matrix([[0, 4, 5, 2], [1, 0, 2, -6], [4, 1, 0,",
"i in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i, i+1:row], x[i+1:row]))/a[i, i] print('x={}'.format(x)) # confirm",
"= a.shape for j in range(row): # search pivot max_idx = j+np.argmax(abs(a[j:, j]))",
"# swap! a[[j, max_idx]] = a[[max_idx, j]] # push forward for i in",
"matrix of eq ax=b a = np.concatenate([a, b], axis=1) (row, col) = a.shape",
"a[[max_idx, j]] # push forward for i in range(j+1, row): p = -a[i,",
"col) = a.shape for j in range(row): # search pivot max_idx = j+np.argmax(abs(a[j:,",
"eq ax=b a = np.concatenate([a, b], axis=1) (row, col) = a.shape for j",
"ori_a = a # define extended coefficient matrix of eq ax=b a =",
"= np.matrix([None]*4, dtype='float64').T # Example2 a = np.matrix([[2, 4, 6], [1, -1, 5],",
"j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]] = a[[max_idx, j]] # push forward for",
"numpy as np # Example1 a = np.matrix([[0, 4, 5, 2], [1, 0,",
"back forward for i in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i, i+1:row], x[i+1:row]))/a[i, i]",
"applied gauss method \\n a={}'.format(a)) # back forward for i in range(row)[::-1]: x[i]",
"6], [1, -1, 5], [4, 1, -2]], dtype='float64') b = np.matrix([28, 7, 21],",
"= a[[max_idx, j]] # push forward for i in range(j+1, row): p =",
"+= p*a[j] print('extended coefficient matrix applied gauss method \\n a={}'.format(a)) # back forward",
"a = np.concatenate([a, b], axis=1) (row, col) = a.shape for j in range(row):",
"# push forward for i in range(j+1, row): p = -a[i, j] /",
"-a[i, j] / a[j, j] a[i] += p*a[j] print('extended coefficient matrix applied gauss",
"# search pivot max_idx = j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]] = a[[max_idx,",
"= np.matrix([9, -3, 1, -3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T # Example2 a",
"check sum ori_a = a # define extended coefficient matrix of eq ax=b",
"a={}'.format(a)) # back forward for i in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i, i+1:row],",
"define extended coefficient matrix of eq ax=b a = np.concatenate([a, b], axis=1) (row,",
"for i in range(j+1, row): p = -a[i, j] / a[j, j] a[i]",
"a # define extended coefficient matrix of eq ax=b a = np.concatenate([a, b],",
"5], [4, 1, -2]], dtype='float64') b = np.matrix([28, 7, 21], dtype='float64').T x =",
"row): p = -a[i, j] / a[j, j] a[i] += p*a[j] print('extended coefficient",
"max_idx]] = a[[max_idx, j]] # push forward for i in range(j+1, row): p",
"for i in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i, i+1:row], x[i+1:row]))/a[i, i] print('x={}'.format(x)) #",
"= np.matrix([[0, 4, 5, 2], [1, 0, 2, -6], [4, 1, 0, -2],",
"ax=b a = np.concatenate([a, b], axis=1) (row, col) = a.shape for j in",
"a.shape for j in range(row): # search pivot max_idx = j+np.argmax(abs(a[j:, j])) #",
"axis=1) (row, col) = a.shape for j in range(row): # search pivot max_idx",
"Example1 a = np.matrix([[0, 4, 5, 2], [1, 0, 2, -6], [4, 1,",
"np.matrix([None]*3, dtype='float64').T # for check sum ori_a = a # define extended coefficient",
"np.concatenate([a, b], axis=1) (row, col) = a.shape for j in range(row): # search",
"a[j, j] a[i] += p*a[j] print('extended coefficient matrix applied gauss method \\n a={}'.format(a))",
"for j in range(row): # search pivot max_idx = j+np.argmax(abs(a[j:, j])) # swap!",
"(row, col) = a.shape for j in range(row): # search pivot max_idx =",
"j] a[i] += p*a[j] print('extended coefficient matrix applied gauss method \\n a={}'.format(a)) #",
"# for check sum ori_a = a # define extended coefficient matrix of",
"push forward for i in range(j+1, row): p = -a[i, j] / a[j,",
"np.matrix([None]*4, dtype='float64').T # Example2 a = np.matrix([[2, 4, 6], [1, -1, 5], [4,",
"b], axis=1) (row, col) = a.shape for j in range(row): # search pivot",
"print('extended coefficient matrix applied gauss method \\n a={}'.format(a)) # back forward for i",
"x = np.matrix([None]*3, dtype='float64').T # for check sum ori_a = a # define",
"dtype='float64').T # Example2 a = np.matrix([[2, 4, 6], [1, -1, 5], [4, 1,",
"dtype='float64') b = np.matrix([28, 7, 21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T # for",
"i in range(j+1, row): p = -a[i, j] / a[j, j] a[i] +=",
"7, 1, 0]], dtype='float64') b = np.matrix([9, -3, 1, -3], dtype='float64').T x =",
"method \\n a={}'.format(a)) # back forward for i in range(row)[::-1]: x[i] = (a[i,",
"2, -6], [4, 1, 0, -2], [1, 7, 1, 0]], dtype='float64') b =",
"extended coefficient matrix of eq ax=b a = np.concatenate([a, b], axis=1) (row, col)",
"dtype='float64').T x = np.matrix([None]*4, dtype='float64').T # Example2 a = np.matrix([[2, 4, 6], [1,",
"a[i] += p*a[j] print('extended coefficient matrix applied gauss method \\n a={}'.format(a)) # back",
"4, 6], [1, -1, 5], [4, 1, -2]], dtype='float64') b = np.matrix([28, 7,",
"[4, 1, 0, -2], [1, 7, 1, 0]], dtype='float64') b = np.matrix([9, -3,",
"0]], dtype='float64') b = np.matrix([9, -3, 1, -3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T",
"dtype='float64').T # for check sum ori_a = a # define extended coefficient matrix",
"in range(row): # search pivot max_idx = j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]]",
"np.matrix([28, 7, 21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T # for check sum ori_a",
"# back forward for i in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i, i+1:row], x[i+1:row]))/a[i,",
"j]] # push forward for i in range(j+1, row): p = -a[i, j]",
"-2], [1, 7, 1, 0]], dtype='float64') b = np.matrix([9, -3, 1, -3], dtype='float64').T",
"a = np.matrix([[2, 4, 6], [1, -1, 5], [4, 1, -2]], dtype='float64') b",
"1, 0, -2], [1, 7, 1, 0]], dtype='float64') b = np.matrix([9, -3, 1,",
"in range(j+1, row): p = -a[i, j] / a[j, j] a[i] += p*a[j]",
"np # Example1 a = np.matrix([[0, 4, 5, 2], [1, 0, 2, -6],",
"5, 2], [1, 0, 2, -6], [4, 1, 0, -2], [1, 7, 1,",
"pivot max_idx = j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]] = a[[max_idx, j]] #",
"= j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]] = a[[max_idx, j]] # push forward",
"search pivot max_idx = j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]] = a[[max_idx, j]]",
"j in range(row): # search pivot max_idx = j+np.argmax(abs(a[j:, j])) # swap! a[[j,",
"= -a[i, j] / a[j, j] a[i] += p*a[j] print('extended coefficient matrix applied",
"[4, 1, -2]], dtype='float64') b = np.matrix([28, 7, 21], dtype='float64').T x = np.matrix([None]*3,",
"= np.matrix([[2, 4, 6], [1, -1, 5], [4, 1, -2]], dtype='float64') b =",
"dtype='float64') b = np.matrix([9, -3, 1, -3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T #",
"<gh_stars>0 import numpy as np # Example1 a = np.matrix([[0, 4, 5, 2],",
"2], [1, 0, 2, -6], [4, 1, 0, -2], [1, 7, 1, 0]],",
"1, -3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T # Example2 a = np.matrix([[2, 4,",
"coefficient matrix of eq ax=b a = np.concatenate([a, b], axis=1) (row, col) =",
"b = np.matrix([28, 7, 21], dtype='float64').T x = np.matrix([None]*3, dtype='float64').T # for check",
"[1, -1, 5], [4, 1, -2]], dtype='float64') b = np.matrix([28, 7, 21], dtype='float64').T",
"max_idx = j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]] = a[[max_idx, j]] # push",
"matrix applied gauss method \\n a={}'.format(a)) # back forward for i in range(row)[::-1]:",
"j])) # swap! a[[j, max_idx]] = a[[max_idx, j]] # push forward for i",
"p*a[j] print('extended coefficient matrix applied gauss method \\n a={}'.format(a)) # back forward for",
"\\n a={}'.format(a)) # back forward for i in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i,",
"[1, 0, 2, -6], [4, 1, 0, -2], [1, 7, 1, 0]], dtype='float64')",
"b = np.matrix([9, -3, 1, -3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T # Example2",
"dtype='float64').T x = np.matrix([None]*3, dtype='float64').T # for check sum ori_a = a #",
"-3], dtype='float64').T x = np.matrix([None]*4, dtype='float64').T # Example2 a = np.matrix([[2, 4, 6],",
"gauss method \\n a={}'.format(a)) # back forward for i in range(row)[::-1]: x[i] =",
"sum ori_a = a # define extended coefficient matrix of eq ax=b a",
"= a # define extended coefficient matrix of eq ax=b a = np.concatenate([a,",
"forward for i in range(j+1, row): p = -a[i, j] / a[j, j]",
"swap! a[[j, max_idx]] = a[[max_idx, j]] # push forward for i in range(j+1,",
"p = -a[i, j] / a[j, j] a[i] += p*a[j] print('extended coefficient matrix",
"np.matrix([[2, 4, 6], [1, -1, 5], [4, 1, -2]], dtype='float64') b = np.matrix([28,",
"= np.concatenate([a, b], axis=1) (row, col) = a.shape for j in range(row): #",
"= np.matrix([None]*3, dtype='float64').T # for check sum ori_a = a # define extended",
"# Example1 a = np.matrix([[0, 4, 5, 2], [1, 0, 2, -6], [4,",
"in range(row)[::-1]: x[i] = (a[i, -1]-np.dot(a[i, i+1:row], x[i+1:row]))/a[i, i] print('x={}'.format(x)) # confirm print(\"ax-b\\n={}\".format(ori_a@x-b))",
"0, 2, -6], [4, 1, 0, -2], [1, 7, 1, 0]], dtype='float64') b",
"4, 5, 2], [1, 0, 2, -6], [4, 1, 0, -2], [1, 7,",
"range(j+1, row): p = -a[i, j] / a[j, j] a[i] += p*a[j] print('extended",
"# Example2 a = np.matrix([[2, 4, 6], [1, -1, 5], [4, 1, -2]],",
"0, -2], [1, 7, 1, 0]], dtype='float64') b = np.matrix([9, -3, 1, -3],",
"range(row): # search pivot max_idx = j+np.argmax(abs(a[j:, j])) # swap! a[[j, max_idx]] ="
] |
[
"scripts=[], entry_points={}, classifiers=[ \"Intended Audience :: Developers\", \"Operating System :: OS Independent\", \"License",
"classifiers=[ \"Intended Audience :: Developers\", \"Operating System :: OS Independent\", \"License :: OSI",
"Django :: 1.11\", \"Framework :: Django :: 2.2\", \"Framework :: Django :: 3.0\",",
"as fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of",
"export and sync Django User Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License",
":: Python :: 3\", \"Framework :: Django\", \"Framework :: Django :: 1.11\", \"Framework",
":: 2.2\", \"Framework :: Django :: 3.0\", \"Intended Audience :: Developers\", ], )",
"\"Intended Audience :: Developers\", \"Operating System :: OS Independent\", \"License :: OSI Approved",
"\"Programming Language :: Python\", \"Programming Language :: Python :: 3\", \"Framework :: Django\",",
"of management commands to export and sync Django User Groups permissions between environments.\",",
"setuptools with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\",",
":: Django :: 2.2\", \"Framework :: Django :: 3.0\", \"Intended Audience :: Developers\",",
"\"Framework :: Django :: 2.2\", \"Framework :: Django :: 3.0\", \"Intended Audience ::",
":: Developers\", \"Operating System :: OS Independent\", \"License :: OSI Approved :: MIT",
"management commands to export and sync Django User Groups permissions between environments.\", long_description=long_description,",
"Python :: 3\", \"Framework :: Django\", \"Framework :: Django :: 1.11\", \"Framework ::",
"long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]),",
"long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management commands",
"= fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management commands to",
"description=\"A set of management commands to export and sync Django User Groups permissions",
"environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\",",
"Language :: Python :: 3\", \"Framework :: Django\", \"Framework :: Django :: 1.11\",",
"Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience",
"set of management commands to export and sync Django User Groups permissions between",
"Independent\", \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming",
"Language :: Python\", \"Programming Language :: Python :: 3\", \"Framework :: Django\", \"Framework",
"permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved :: MIT License\",",
"install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience :: Developers\", \"Operating System :: OS Independent\",",
":: 1.11\", \"Framework :: Django :: 2.2\", \"Framework :: Django :: 3.0\", \"Intended",
"url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[],",
"license=\"License :: OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={},",
"\"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience :: Developers\", \"Operating System ::",
"Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python ::",
"author_email=\"<EMAIL>\", description=\"A set of management commands to export and sync Django User Groups",
":: OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[",
":: MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python :: 3\",",
":: Python\", \"Programming Language :: Python :: 3\", \"Framework :: Django\", \"Framework ::",
"\"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience :: Developers\", \"Operating System :: OS",
"commands to export and sync Django User Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\",",
"entry_points={}, classifiers=[ \"Intended Audience :: Developers\", \"Operating System :: OS Independent\", \"License ::",
"to export and sync Django User Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\",",
"Django User Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved",
"Developers\", \"Operating System :: OS Independent\", \"License :: OSI Approved :: MIT License\",",
"Django :: 2.2\", \"Framework :: Django :: 3.0\", \"Intended Audience :: Developers\", ],",
":: OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language ::",
"with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\",",
"name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management commands to export and sync",
"<gh_stars>0 import setuptools with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\",",
":: Django\", \"Framework :: Django :: 1.11\", \"Framework :: Django :: 2.2\", \"Framework",
"fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management commands to export",
"Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved :: MIT",
"sync Django User Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI",
"\"r\") as fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set",
"License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience :: Developers\", \"Operating",
"\"License :: OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language",
"long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[],",
"License\", \"Programming Language :: Python\", \"Programming Language :: Python :: 3\", \"Framework ::",
"open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A",
"System :: OS Independent\", \"License :: OSI Approved :: MIT License\", \"Programming Language",
"Python\", \"Programming Language :: Python :: 3\", \"Framework :: Django\", \"Framework :: Django",
"\"Programming Language :: Python :: 3\", \"Framework :: Django\", \"Framework :: Django ::",
"packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience :: Developers\", \"Operating System",
"\"Operating System :: OS Independent\", \"License :: OSI Approved :: MIT License\", \"Programming",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management commands to export and sync Django User",
":: OS Independent\", \"License :: OSI Approved :: MIT License\", \"Programming Language ::",
"version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management commands to export and sync Django",
":: Django :: 1.11\", \"Framework :: Django :: 2.2\", \"Framework :: Django ::",
":: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience ::",
"\"Framework :: Django :: 1.11\", \"Framework :: Django :: 2.2\", \"Framework :: Django",
"MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python :: 3\", \"Framework",
"setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management commands to export and",
"Audience :: Developers\", \"Operating System :: OS Independent\", \"License :: OSI Approved ::",
"import setuptools with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\",",
"OS Independent\", \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python\",",
"OSI Approved :: MIT License\", \"Programming Language :: Python\", \"Programming Language :: Python",
":: 3\", \"Framework :: Django\", \"Framework :: Django :: 1.11\", \"Framework :: Django",
"1.11\", \"Framework :: Django :: 2.2\", \"Framework :: Django :: 3.0\", \"Intended Audience",
"and sync Django User Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License ::",
"3\", \"Framework :: Django\", \"Framework :: Django :: 1.11\", \"Framework :: Django ::",
"OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended",
"Django\", \"Framework :: Django :: 1.11\", \"Framework :: Django :: 2.2\", \"Framework ::",
"fh: long_description = fh.read() setuptools.setup( name=\"django-groups-sync\", version=\"0.0.7\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"A set of management",
"between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved :: MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\",",
"User Groups permissions between environments.\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/hansek/django-groups-sync\", license=\"License :: OSI Approved ::",
"MIT License\", packages=setuptools.find_packages(exclude=[\"contrib\", \"docs\", \"tests*\"]), install_requires=[], scripts=[], entry_points={}, classifiers=[ \"Intended Audience :: Developers\",",
"\"Framework :: Django\", \"Framework :: Django :: 1.11\", \"Framework :: Django :: 2.2\","
] |
[
"with deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2, 3]) #",
"X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2",
"n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for tranning and testing #",
"lowd_embedding2, y2, X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6)",
"import roc_curve from sklearn.preprocessing import label_binarize ##========== load low-high level features mdir1 =",
"'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc",
"Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data",
"xgboost as xgb from xgboost import XGBClassifier from xgboost import cv from sklearn.metrics",
"set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6",
"Created on Thu Dec 23 11:24:09 2021 @author: nguy0936 I used this code",
"200} # train the classifier to the training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train,",
"as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import",
"from sklearn.metrics import precision_recall_curve from sklearn.metrics import roc_curve from sklearn.preprocessing import label_binarize ##==========",
"y1, X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2) #",
"= 0.2) # note X vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate':",
"print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1]) #for i",
"data for tranning and testing # split data into train and test sets",
"cv from sklearn.metrics import roc_auc_score from hyperopt import STATUS_OK, Trials, fmin, hp, tpe",
"import StandardScaler from sklearn.model_selection import train_test_split import xgboost as xgb from xgboost import",
"set9 df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM",
"using Xhand data \"\"\" # load packages import pandas as pd import umap",
"lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 =",
"# plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df)",
"test sets (80% for training and 20% for testing) X_train, X_test, y_train, y_test",
"roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1]) #for i in",
"data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train with deep features y_test_pred",
"load low-high level features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data",
"y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2,",
"y2 = 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y",
"np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1 =",
"y = Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2)",
"= Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding",
"pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand",
"features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 =",
"from sklearn.model_selection import train_test_split import xgboost as xgb from xgboost import XGBClassifier from",
"# function to load data conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1",
"Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function to load data conv1 = pd.read_csv(mdir",
"= pd.read_csv(mdir + 'X_hand.csv') # bias features X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir",
"Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function to load data conv1 =",
"lowd_embedding6, y6, X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9)",
"pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y,",
"3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2, y6), axis=0) #",
"train_test_split(df, y, test_size = 0.2) # note X vs Xhand params_deep = {\"objective\":\"multi:softmax\",",
"X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv', header=None) # score y =",
"X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv', header=None) # score y = Y y[:]=np.where(y<3,0,1)",
"# -*- coding: utf-8 -*- \"\"\" Created on Thu Dec 23 11:24:09 2021",
"15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1]) for i in range(0,10):",
"# conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding X_hand = pd.read_csv(mdir",
"y[:]=np.where(y<3,0,1) # combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding)",
"1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,),",
"testing # split data into train and test sets (80% for training and",
"y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int)",
"on Thu Dec 23 11:24:09 2021 @author: nguy0936 I used this code to",
"#df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df)",
"conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv',",
"# train the classifier to the training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train",
"from sklearn.preprocessing import label_binarize ##========== load low-high level features mdir1 = 'R:\\\\CMPH-Windfarm Field",
"X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9) # set9",
"'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200} # train the classifier to the training",
"utf-8 -*- \"\"\" Created on Thu Dec 23 11:24:09 2021 @author: nguy0936 I",
"PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df",
"load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6,",
"Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\'",
"xgb from xgboost import XGBClassifier from xgboost import cv from sklearn.metrics import roc_auc_score",
"= reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for tranning and testing # split data",
"set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir):",
"data \"\"\" # load packages import pandas as pd import umap import matplotlib.pyplot",
"as xgb from xgboost import XGBClassifier from xgboost import cv from sklearn.metrics import",
"location using Xhand data \"\"\" # load packages import pandas as pd import",
"= load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6,",
"metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for tranning and testing",
"y6, X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9) #",
"= pd.read_csv(mdir + 'Y.csv', header=None) # score y = Y y[:]=np.where(y<3,0,1) # combine",
"# bias features X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv', header=None) #",
"'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200} #",
"Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc",
"import STATUS_OK, Trials, fmin, hp, tpe from sklearn.metrics import roc_auc_score from sklearn.metrics import",
"umap import matplotlib.pyplot as plt import numpy as np from sklearn.decomposition import PCA",
"header=None) # embedding X_hand = pd.read_csv(mdir + 'X_hand.csv') # bias features X_hand =",
"= 4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2, y6), axis=0) # plot umap reducer",
"# embedding X_hand = pd.read_csv(mdir + 'X_hand.csv') # bias features X_hand = X_hand.fillna(0)",
"clf_location(df,y): #========Split data for tranning and testing # split data into train and",
"data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1),",
"and 20% for testing) X_train, X_test, y_train, y_test = train_test_split(df, y, test_size =",
"np.concatenate((y1, y2, y6), axis=0) # plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean',",
"'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc",
"roc_curve from sklearn.preprocessing import label_binarize ##========== load low-high level features mdir1 = 'R:\\\\CMPH-Windfarm",
"in range(0,10): # AUC[i] = clf_location(data_umap,y) LALC = df[:, [13, 15]] LALC[:,1] =",
"from sklearn.metrics import roc_auc_score from hyperopt import STATUS_OK, Trials, fmin, hp, tpe from",
"level features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2",
"scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6 =",
"= label_binarize(y_test, classes=[1, 2, 3]) # print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred)",
"classifier to the training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train",
"Thu Dec 23 11:24:09 2021 @author: nguy0936 I used this code to classify",
"= load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9,",
"sets (80% for training and 20% for testing) X_train, X_test, y_train, y_test =",
"import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from",
"lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df =",
"def clf_location(df,y): #========Split data for tranning and testing # split data into train",
"umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for",
"X_test, y_train, y_test = train_test_split(df, y, test_size = 0.2) # note X vs",
"and test sets (80% for training and 20% for testing) X_train, X_test, y_train,",
"set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9) # set9 df = np.concatenate((X_hand1, X_hand2,",
"= PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames,",
"# set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9,",
"from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import",
"X vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight':",
"import label_binarize ##========== load low-high level features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc",
"header=None) # conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding X_hand =",
"pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None) #",
"Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function to load data conv1 = pd.read_csv(mdir +",
"axis=0) scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6",
"packages import pandas as pd import umap import matplotlib.pyplot as plt import numpy",
"the training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train with deep",
"train with deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2, 3])",
"np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1]) for i in range(0,10): AUC2[i] = clf_location(LALC,y)",
"pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding X_hand = pd.read_csv(mdir + 'X_hand.csv') # bias",
"train and test sets (80% for training and 20% for testing) X_train, X_test,",
"= PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)]",
"set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 =",
"Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function to load data conv1",
"Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function to load",
"+ 'result_embedding.csv', header=None) # embedding X_hand = pd.read_csv(mdir + 'X_hand.csv') # bias features",
"y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1]) #for i in range(0,10):",
"lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return",
"2, 3]) # print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10,",
"= pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None)",
"low-high level features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\'",
"import cv from sklearn.metrics import roc_auc_score from hyperopt import STATUS_OK, Trials, fmin, hp,",
"lowd_embedding9, y9, X_hand9 = load_feature(mdir9) # set9 df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0)",
"= X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv', header=None) # score y = Y",
"precision_recall_curve from sklearn.metrics import roc_curve from sklearn.preprocessing import label_binarize ##========== load low-high level",
"StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int)",
"Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding =",
"import umap import matplotlib.pyplot as plt import numpy as np from sklearn.decomposition import",
"for training and 20% for testing) X_train, X_test, y_train, y_test = train_test_split(df, y,",
"df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM =",
"from sklearn.metrics import roc_curve from sklearn.preprocessing import label_binarize ##========== load low-high level features",
"y_train ) # train with deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test,",
"xgboost import cv from sklearn.metrics import roc_auc_score from hyperopt import STATUS_OK, Trials, fmin,",
"classify noise at different location using Xhand data \"\"\" # load packages import",
"# set9 df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0)",
"sklearn.metrics import precision_recall_curve from sklearn.metrics import roc_curve from sklearn.preprocessing import label_binarize ##========== load",
"y_test = train_test_split(df, y, test_size = 0.2) # note X vs Xhand params_deep",
"y, test_size = 0.2) # note X vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth':",
"matplotlib.pyplot as plt import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing",
"combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames =",
"X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2) # set2",
"'result_conv2.csv', header=None) # conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding X_hand",
"#========Split data for tranning and testing # split data into train and test",
"X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1, y2), axis=0) scaled_df",
"'X_hand.csv') # bias features X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv', header=None)",
"= pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None)",
"conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding X_hand = pd.read_csv(mdir +",
"Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc",
"to classify noise at different location using Xhand data \"\"\" # load packages",
"label_binarize(y_test, classes=[1, 2, 3]) # print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC",
"(80% for training and 20% for testing) X_train, X_test, y_train, y_test = train_test_split(df,",
"header=None) # conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2 embedding =",
"to the training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train with",
"X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1, y2), axis=0)",
"# split data into train and test sets (80% for training and 20%",
"load_feature(mdir): # function to load data conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None) #",
"1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200}",
"lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2,",
"embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding X_hand = pd.read_csv(mdir + 'X_hand.csv')",
"AUC[i] = clf_location(data_umap,y) LALC = df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2",
"sklearn.metrics import roc_auc_score from hyperopt import STATUS_OK, Trials, fmin, hp, tpe from sklearn.metrics",
"this code to classify noise at different location using Xhand data \"\"\" #",
"min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for tranning and",
"train_test_split import xgboost as xgb from xgboost import XGBClassifier from xgboost import cv",
"as plt import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import",
"data conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1 conv2 = pd.read_csv(mdir +",
"+ 'result_conv2.csv', header=None) # conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding",
"= np.concatenate((y1, y2, y6), axis=0) # plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0,",
"= StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,),",
"xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2, 3]) # print( roc_auc_score(y_test, y_test_pred) ) return",
"and testing # split data into train and test sets (80% for training",
"note X vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11,",
"data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for tranning and testing # split",
"as pd import umap import matplotlib.pyplot as plt import numpy as np from",
"y2, X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6) #",
"mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm",
"import precision_recall_curve from sklearn.metrics import roc_curve from sklearn.preprocessing import label_binarize ##========== load low-high",
"PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import xgboost as xgb",
"dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2, y6), axis=0) # plot",
"Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data",
"X_hand9 = load_feature(mdir9) # set9 df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand =",
"the classifier to the training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) #",
"import train_test_split import xgboost as xgb from xgboost import XGBClassifier from xgboost import",
"'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200} # train the classifier to",
"= umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data",
"# note X vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma':",
"'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators':",
"tranning and testing # split data into train and test sets (80% for",
"classes=[1, 2, 3]) # print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC =",
"# set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9) # set9 df = np.concatenate((X_hand1,",
"different location using Xhand data \"\"\" # load packages import pandas as pd",
"0.2) # note X vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13,",
"'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc",
"# conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2 embedding = pd.read_csv(mdir",
"dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int)",
"0.796, 'scale_pos_weight': 1, 'n_estimators': 200} # train the classifier to the training data",
"roc_auc_score from hyperopt import STATUS_OK, Trials, fmin, hp, tpe from sklearn.metrics import roc_auc_score",
"bias features X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv', header=None) # score",
"hp, tpe from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import",
"tpe from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import roc_curve",
"@author: nguy0936 I used this code to classify noise at different location using",
"Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\'",
"Xhand data \"\"\" # load packages import pandas as pd import umap import",
"params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92,",
"y_test = label_binarize(y_test, classes=[1, 2, 3]) # print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test,",
"axis=0) #y_AM = np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int)",
"1]) #for i in range(0,10): # AUC[i] = clf_location(data_umap,y) LALC = df[:, [13,",
"sklearn.preprocessing import label_binarize ##========== load low-high level features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc",
"I used this code to classify noise at different location using Xhand data",
"5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200} # train the classifier to the",
"hyperopt import STATUS_OK, Trials, fmin, hp, tpe from sklearn.metrics import roc_auc_score from sklearn.metrics",
"from xgboost import cv from sklearn.metrics import roc_auc_score from hyperopt import STATUS_OK, Trials,",
"coding: utf-8 -*- \"\"\" Created on Thu Dec 23 11:24:09 2021 @author: nguy0936",
"load data conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1 conv2 = pd.read_csv(mdir",
"pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2 embedding = pd.read_csv(mdir + 'result_embedding.csv', header=None) #",
"= [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1,",
"reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split",
"Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def",
"axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1, y2), axis=0) scaled_df =",
"'result_embedding.csv', header=None) # embedding X_hand = pd.read_csv(mdir + 'X_hand.csv') # bias features X_hand",
"= train_test_split(df, y, test_size = 0.2) # note X vs Xhand params_deep =",
"pd import umap import matplotlib.pyplot as plt import numpy as np from sklearn.decomposition",
"y2, y6), axis=0) # plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2)",
"= pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1,",
"clf_location(data_umap,y) LALC = df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10,",
"import roc_auc_score from hyperopt import STATUS_OK, Trials, fmin, hp, tpe from sklearn.metrics import",
"Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4.",
"4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2, y6), axis=0) # plot umap reducer =",
"lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 =",
"#AUC = np.empty([10, 1]) #for i in range(0,10): # AUC[i] = clf_location(data_umap,y) LALC",
"xgb_clf.fit(X_train, y_train ) # train with deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test =",
"range(0,10): # AUC[i] = clf_location(data_umap,y) LALC = df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0],",
"= pd.read_csv(mdir + 'result_embedding.csv', header=None) # embedding X_hand = pd.read_csv(mdir + 'X_hand.csv') #",
"y6 = 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2, y6),",
"roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1]) #for i in range(0,10): # AUC[i] =",
"{\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0,",
"function to load data conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1 conv2",
"pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1,",
"'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function to",
"i in range(0,10): # AUC[i] = clf_location(data_umap,y) LALC = df[:, [13, 15]] LALC[:,1]",
"Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4.",
"header=None) # score y = Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1)",
"= 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y =",
"'Y.csv', header=None) # score y = Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1 =",
"[13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1]) for i in",
"= 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2, y6), axis=0)",
"# set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6,",
"Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4.",
"np.empty([10, 1]) #for i in range(0,10): # AUC[i] = clf_location(data_umap,y) LALC = df[:,",
"\"\"\" # load packages import pandas as pd import umap import matplotlib.pyplot as",
"= clf_location(data_umap,y) LALC = df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 =",
"sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import roc_curve from sklearn.preprocessing",
"= np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1]) for i in range(0,10): AUC2[i] =",
"noise at different location using Xhand data \"\"\" # load packages import pandas",
"load_feature(mdir9) # set9 df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2),",
"-*- coding: utf-8 -*- \"\"\" Created on Thu Dec 23 11:24:09 2021 @author:",
"from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import xgboost as xgb from",
"deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2, 3]) # print(",
"n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for tranning",
") # train with deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1,",
"at different location using Xhand data \"\"\" # load packages import pandas as",
"# combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames",
"sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import xgboost as xgb from xgboost",
"STATUS_OK, Trials, fmin, hp, tpe from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve",
"xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train with deep features y_test_pred =",
"set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9",
"training and 20% for testing) X_train, X_test, y_train, y_test = train_test_split(df, y, test_size",
"axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1",
"set\\\\set9_WL8\\\\' def load_feature(mdir): # function to load data conv1 = pd.read_csv(mdir + 'result_conv1.csv',",
"reducer.fit_transform(scaled_df) def clf_location(df,y): #========Split data for tranning and testing # split data into",
"0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1,",
"0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200} # train the classifier",
"import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import roc_curve from sklearn.preprocessing import",
"XGBClassifier from xgboost import cv from sklearn.metrics import roc_auc_score from hyperopt import STATUS_OK,",
"= np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1,",
"#y_AM = np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2",
"Trials, fmin, hp, tpe from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from",
"Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine",
"for tranning and testing # split data into train and test sets (80%",
"= df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1]) for",
"'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200} # train the",
"used this code to classify noise at different location using Xhand data \"\"\"",
"#for i in range(0,10): # AUC[i] = clf_location(data_umap,y) LALC = df[:, [13, 15]]",
"train the classifier to the training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train )",
"= XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train with deep features y_test_pred = xgb_clf.predict_proba(X_test)",
"mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm",
"PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df)",
"def load_feature(mdir): # function to load data conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None)",
"+ 'X_hand.csv') # bias features X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv',",
"= 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9 =",
"dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2,",
"label_binarize ##========== load low-high level features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4.",
"load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9) # set9 df =",
"= load_feature(mdir9) # set9 df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1,",
"split data into train and test sets (80% for training and 20% for",
"# print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1]) #for",
"return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1]) #for i in range(0,10): # AUC[i]",
"scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 =",
"import xgboost as xgb from xgboost import XGBClassifier from xgboost import cv from",
"sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import xgboost",
"conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv',",
"conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2 embedding = pd.read_csv(mdir +",
"X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6) # set6",
"pd.read_csv(mdir + 'Y.csv', header=None) # score y = Y y[:]=np.where(y<3,0,1) # combine data",
"# train with deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2,",
"lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df",
"'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda':",
"return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1) # set1",
"= np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2 =",
"3]) # print( roc_auc_score(y_test, y_test_pred) ) return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1])",
"StandardScaler from sklearn.model_selection import train_test_split import xgboost as xgb from xgboost import XGBClassifier",
"X_hand = pd.read_csv(mdir + 'X_hand.csv') # bias features X_hand = X_hand.fillna(0) Y =",
"# score y = Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2",
"roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import roc_curve from sklearn.preprocessing import label_binarize",
"1, 'n_estimators': 200} # train the classifier to the training data xgb_clf =",
"load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 = load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9,",
"xgboost import XGBClassifier from xgboost import cv from sklearn.metrics import roc_auc_score from hyperopt",
"Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function to load data",
"31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight': 1, 'n_estimators': 200} # train",
"y1 = 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9",
"= 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field",
"import pandas as pd import umap import matplotlib.pyplot as plt import numpy as",
"pandas as pd import umap import matplotlib.pyplot as plt import numpy as np",
"into train and test sets (80% for training and 20% for testing) X_train,",
"sklearn.model_selection import train_test_split import xgboost as xgb from xgboost import XGBClassifier from xgboost",
"plt import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler",
"-*- \"\"\" Created on Thu Dec 23 11:24:09 2021 @author: nguy0936 I used",
"vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31,",
") return roc_auc_score(y_test, y_test_pred) #AUC = np.empty([10, 1]) #for i in range(0,10): #",
"np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split",
"= np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1",
"Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree':",
"umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def clf_location(df,y):",
"from xgboost import XGBClassifier from xgboost import cv from sklearn.metrics import roc_auc_score from",
"# load packages import pandas as pd import umap import matplotlib.pyplot as plt",
"y9, X_hand9 = load_feature(mdir9) # set9 df = np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand",
"fmin, hp, tpe from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics",
"import matplotlib.pyplot as plt import numpy as np from sklearn.decomposition import PCA from",
"'scale_pos_weight': 1, 'n_estimators': 200} # train the classifier to the training data xgb_clf",
"dtype=int) y = np.concatenate((y1, y2, y6), axis=0) # plot umap reducer = umap.UMAP(random_state=42,",
"y_test_pred) #AUC = np.empty([10, 1]) #for i in range(0,10): # AUC[i] = clf_location(data_umap,y)",
"plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap = reducer.fit_transform(scaled_df) def",
"# AUC[i] = clf_location(data_umap,y) LALC = df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1])",
"= 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field",
"11:24:09 2021 @author: nguy0936 I used this code to classify noise at different",
"testing) X_train, X_test, y_train, y_test = train_test_split(df, y, test_size = 0.2) # note",
"sklearn.metrics import roc_curve from sklearn.preprocessing import label_binarize ##========== load low-high level features mdir1",
"'result_conv1.csv', header=None) # conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2 embedding",
"StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1) #",
"y = np.concatenate((y1, y2, y6), axis=0) # plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20,",
"pd.read_csv(mdir + 'X_hand.csv') # bias features X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir +",
"##========== load low-high level features mdir1 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine",
"np.concatenate((X_hand1, X_hand2, X_hand6), axis=0) #df_hand = np.concatenate((X_hand1, X_hand2), axis=0) #y_AM = np.concatenate((y1, y2),",
"features X_hand = X_hand.fillna(0) Y = pd.read_csv(mdir + 'Y.csv', header=None) # score y",
"features y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2, 3]) # print( roc_auc_score(y_test,",
"[pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding,",
"embedding X_hand = pd.read_csv(mdir + 'X_hand.csv') # bias features X_hand = X_hand.fillna(0) Y",
"y6), axis=0) # plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap",
"test_size = 0.2) # note X vs Xhand params_deep = {\"objective\":\"multi:softmax\", 'max_depth': 19,",
"axis=0) # plot umap reducer = umap.UMAP(random_state=42, n_neighbors=20, min_dist=0.0, metric='euclidean', n_components=2) data_umap =",
"y_test_pred = xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2, 3]) # print( roc_auc_score(y_test, y_test_pred)",
"Listening\\Data set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6",
"= 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field",
"2021 @author: nguy0936 I used this code to classify noise at different location",
"for testing) X_train, X_test, y_train, y_test = train_test_split(df, y, test_size = 0.2) #",
"mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): #",
"lowd_embedding1, y1, X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2)",
"set\\\\set1\\\\' mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 =",
"score y = Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 =",
"training data xgb_clf = XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train with deep features",
"'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796, 'scale_pos_weight':",
"+ 'Y.csv', header=None) # score y = Y y[:]=np.where(y<3,0,1) # combine data lowd_conv1",
"\"\"\" Created on Thu Dec 23 11:24:09 2021 @author: nguy0936 I used this",
"19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha': 5.0, 'reg_lambda': 0.796,",
"to load data conv1 = pd.read_csv(mdir + 'result_conv1.csv', header=None) # conv1 conv2 =",
"= xgb_clf.predict_proba(X_test) y_test = label_binarize(y_test, classes=[1, 2, 3]) # print( roc_auc_score(y_test, y_test_pred) )",
"LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1]) for i in range(0,10): AUC2[i]",
"= load_feature(mdir6) # set6 lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9) # set9 df",
"import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import xgboost as",
"20% for testing) X_train, X_test, y_train, y_test = train_test_split(df, y, test_size = 0.2)",
"from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import roc_curve from",
"load packages import pandas as pd import umap import matplotlib.pyplot as plt import",
"PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1)",
"lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df = StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1,",
"Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9",
"<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" Created on Thu Dec 23 11:24:09",
"= 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\' def load_feature(mdir): # function",
"data into train and test sets (80% for training and 20% for testing)",
"= {\"objective\":\"multi:softmax\", 'max_depth': 19, 'learning_rate': 0.13, 'gamma': 1.11, 'min_child_weight': 31, 'colsample_bytree': 0.92, 'reg_alpha':",
"lowd_conv1_2, lowd_embedding2, y2, X_hand2 = load_feature(mdir2) # set2 lowd_conv1_6, lowd_embedding6, y6, X_hand6 =",
"#y9 = 4*np.ones((1000,), dtype=int) y = np.concatenate((y1, y2, y6), axis=0) # plot umap",
"lowd_conv1 = PCA(n_components=10).fit_transform(conv1) lowd_conv2 = PCA(n_components=10).fit_transform(conv2) lowd_embedding = PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2),",
"numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection",
"= np.empty([10, 1]) #for i in range(0,10): # AUC[i] = clf_location(data_umap,y) LALC =",
"= PCA(n_components=20).fit_transform(embedding) lowd_frames = [pd.DataFrame(lowd_conv1), pd.DataFrame(lowd_conv2), pd.DataFrame(lowd_embedding)] lowd_df = pd.concat(lowd_frames, axis=1) scaled_lowd_df =",
"Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set9_WL8\\\\'",
"XGBClassifier(**params_deep) xgb_clf.fit(X_train, y_train ) # train with deep features y_test_pred = xgb_clf.predict_proba(X_test) y_test",
"= StandardScaler().fit_transform(lowd_df) return lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1)",
"Dec 23 11:24:09 2021 @author: nguy0936 I used this code to classify noise",
"nguy0936 I used this code to classify noise at different location using Xhand",
"2*np.ones((3000,), dtype=int) y6 = 3*np.ones((1000,), dtype=int) #y9 = 4*np.ones((1000,), dtype=int) y = np.concatenate((y1,",
"code to classify noise at different location using Xhand data \"\"\" # load",
"df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1]) for i",
"mdir2 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm",
"Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc",
"Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set6\\\\' mdir9 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine",
"X_train, X_test, y_train, y_test = train_test_split(df, y, test_size = 0.2) # note X",
"23 11:24:09 2021 @author: nguy0936 I used this code to classify noise at",
"np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,), dtype=int) y2 = 2*np.ones((3000,),",
"+ 'result_conv1.csv', header=None) # conv1 conv2 = pd.read_csv(mdir + 'result_conv2.csv', header=None) # conv2",
"LALC = df[:, [13, 15]] LALC[:,1] = np.multiply(LALC[:,0], LALC[:,1]) AUC2 = np.empty([10, 1])",
"X_hand2), axis=0) #y_AM = np.concatenate((y1, y2), axis=0) scaled_df = StandardScaler().fit_transform(df) y1 = 1*np.ones((5000,),",
"'n_estimators': 200} # train the classifier to the training data xgb_clf = XGBClassifier(**params_deep)",
"lowd_conv1_9, lowd_embedding9, y9, X_hand9 = load_feature(mdir9) # set9 df = np.concatenate((X_hand1, X_hand2, X_hand6),",
"Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine Listening\\Data",
"import XGBClassifier from xgboost import cv from sklearn.metrics import roc_auc_score from hyperopt import",
"Y = pd.read_csv(mdir + 'Y.csv', header=None) # score y = Y y[:]=np.where(y<3,0,1) #",
"lowd_conv1, lowd_embedding, y, X_hand lowd_conv1_1, lowd_embedding1, y1, X_hand1 = load_feature(mdir1) # set1 lowd_conv1_2,",
"y_train, y_test = train_test_split(df, y, test_size = 0.2) # note X vs Xhand",
"Phuc Nguyen\\\\4. Machine Listening\\Data set\\\\set2\\\\' mdir6 = 'R:\\\\CMPH-Windfarm Field Study\\\\Duc Phuc Nguyen\\\\4. Machine",
"from hyperopt import STATUS_OK, Trials, fmin, hp, tpe from sklearn.metrics import roc_auc_score from"
] |
[
"self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn): for dev",
"_search(self): self.start_search(600, 'upnp:rootdevice') print 'search started' def _stop(self): self.stop_search() print 'search stopped' def",
"import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found =",
"while self.running: command = str(raw_input('>>> ')) try: self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split('",
"child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print n += 1 def _cmd_set_server(self,",
"def _help(self): print 'commands: start, stop, list, ' \\ 'browse, set_server, set_render, play,",
"self.start_search(600, 'upnp:rootdevice') print 'search started' def _stop(self): self.stop_search() print 'search stopped' def _help(self):",
"try: self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif",
"= {'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def _initial_subscribes(self):",
"import install_default_reactor reactor = install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call",
"LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor =",
"dev): self.devices_found.append(dev) def on_remove_device(self, udn): for dev in self.devices: if dev.udn == udn:",
"print '\\t\\ttype:', child_dev.device_type print n += 1 def _cmd_set_server(self, id): self._current_server = self.devices_found[id]",
"print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print",
"= False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while self.running:",
"')) try: self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1]))",
"command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print",
"_stop(self): self.stop_search() print 'search stopped' def _help(self): print 'commands: start, stop, list, '",
"child_dev.device_type print n += 1 def _cmd_set_server(self, id): self._current_server = self.devices_found[id] def _cmd_set_render(self,",
"self.devices_found[id] def _cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result =",
"print n += 1 def _cmd_set_server(self, id): self._current_server = self.devices_found[id] def _cmd_set_render(self, id):",
"self.devices_found: print 'device %d:' % n print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print",
"self._current_server = self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def _cmd_browse(self, id): result",
"under the MIT license # http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright 2007-2008",
"on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn): for dev in self.devices: if dev.udn ==",
"')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid command,",
"http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import",
"dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type",
"1 def _cmd_set_server(self, id): self._current_server = self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id]",
"def _stop(self): self.stop_search() print 'search stopped' def _help(self): print 'commands: start, stop, list,",
"for d in result: print \"%s %s %s\" % (d.id, d.title, d.upnp_class) def",
"or see LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor",
"= [] self.commands = {'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help':",
"<<EMAIL>> from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import",
"'\\tservices:', dev.services print '\\ttype:', dev.device_type if dev.devices: print '\\tchild devices:' for child_dev in",
"'search started' def _stop(self): self.stop_search() print 'search stopped' def _help(self): print 'commands: start,",
"if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif",
"self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device)",
"started' def _stop(self): self.stop_search() print 'search stopped' def _help(self): print 'commands: start, stop,",
"= self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def _cmd_browse(self, id): result =",
"'BrowseDirectChildren', '*', 0, 10) result = result['Result'] for d in result: print \"%s",
"'\\t\\ttype:', child_dev.device_type print n += 1 def _cmd_set_server(self, id): self._current_server = self.devices_found[id] def",
"'\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print n",
"result['Result'] for d in result: print \"%s %s %s\" % (d.id, d.title, d.upnp_class)",
"def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search started' def _stop(self): self.stop_search() print 'search stopped'",
"import sys from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def",
"'device %d:' % n print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services",
"dev.device_type if dev.devices: print '\\tchild devices:' for child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn",
"stop, list, ' \\ 'browse, set_server, set_render, play, exit, help' def _exit(self): self.running",
"<NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import sys from brisa.upnp.control_point.control_point_av",
"import ControlPointAV from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running =",
"dev.services print '\\ttype:', dev.device_type if dev.devices: print '\\tchild devices:' for child_dev in dev.devices.values():",
"dev.services print '\\t\\ttype:', child_dev.device_type print n += 1 def _cmd_set_server(self, id): self._current_server =",
"dev in self.devices: if dev.udn == udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n =",
"self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def _cmd_browse(self, id): result = self.browse(id,",
"'\\tchild devices:' for child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print",
"10) result = result['Result'] for d in result: print \"%s %s %s\" %",
"set_render, play, exit, help' def _exit(self): self.running = False def run(self): self.start() run_async_function(self._handle_cmds)",
"else: print 'Invalid command, try help' command = '' except KeyboardInterrupt, k: print",
"child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print n +=",
"% n print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print '\\ttype:',",
"'\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print '\\ttype:', dev.device_type if dev.devices:",
"run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found = []",
"' \\ 'browse, set_server, set_render, play, exit, help' def _exit(self): self.running = False",
"command, try help' command = '' except KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def",
"self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn): for dev in",
"if dev.udn == udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n = 0 for dev",
"{'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event',",
"'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event',",
"print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print n += 1 def _cmd_set_server(self, id):",
"str(raw_input('>>> ')) try: self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split('",
"2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import sys from",
"def _exit(self): self.running = False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self):",
"print \"BRisa ControlPointAV example\\n\" cmdline = CommandLineControlPointAV() cmdline.run() if __name__ == \"__main__\": main()",
"def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn): for dev in self.devices: if dev.udn",
"d in result: print \"%s %s %s\" % (d.id, d.title, d.upnp_class) def _search(self):",
"self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'):",
"dev in self.devices_found: print 'device %d:' % n print '\\tudn:', dev.udn print '\\tfriendly_name:',",
"help' command = '' except KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def main(): print",
"def __init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found = [] self.commands = {'start':",
"print 'search started' def _stop(self): self.stop_search() print 'search stopped' def _help(self): print 'commands:",
"file. # Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor = install_default_reactor()",
"_initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn): for",
"'upnp:rootdevice') print 'search started' def _stop(self): self.stop_search() print 'search stopped' def _help(self): print",
"install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV):",
"self.devices_found.append(dev) def on_remove_device(self, udn): for dev in self.devices: if dev.udn == udn: self.devices_found.remove(dev)",
"break def _cmd_list_devices(self): n = 0 for dev in self.devices_found: print 'device %d:'",
"brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running",
"print 'quiting' reactor.main_quit() def main(): print \"BRisa ControlPointAV example\\n\" cmdline = CommandLineControlPointAV() cmdline.run()",
"MIT license # http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>>",
"sys from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self):",
"command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'):",
"print 'commands: start, stop, list, ' \\ 'browse, set_server, set_render, play, exit, help'",
"from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import ControlPointAV",
"% (d.id, d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search started' def _stop(self):",
"reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while self.running: command = str(raw_input('>>> ')) try: self.commands[command]()",
"def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def _cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren',",
"%d:' % n print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print",
"brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found",
"for dev in self.devices_found: print 'device %d:' % n print '\\tudn:', dev.udn print",
"self.running = True self._initial_subscribes() self.devices_found = [] self.commands = {'start': self._search, 'stop': self._stop,",
"self._initial_subscribes() self.devices_found = [] self.commands = {'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit':",
"elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid command, try help' command = ''",
"if dev.devices: print '\\tchild devices:' for child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print",
"list, ' \\ 'browse, set_server, set_render, play, exit, help' def _exit(self): self.running =",
"ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found = [] self.commands = {'start': self._search, 'stop':",
"d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search started' def _stop(self): self.stop_search() print",
"set_server, set_render, play, exit, help' def _exit(self): self.running = False def run(self): self.start()",
"= 0 for dev in self.devices_found: print 'device %d:' % n print '\\tudn:',",
"reactor.main() def _handle_cmds(self): try: while self.running: command = str(raw_input('>>> ')) try: self.commands[command]() except",
"self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn): for dev in self.devices: if",
"')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid command, try help' command =",
"_handle_cmds(self): try: while self.running: command = str(raw_input('>>> ')) try: self.commands[command]() except KeyError: if",
"license # http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>> from",
"print '\\tservices:', dev.services print '\\ttype:', dev.device_type if dev.devices: print '\\tchild devices:' for child_dev",
"')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1])",
"def main(): print \"BRisa ControlPointAV example\\n\" cmdline = CommandLineControlPointAV() cmdline.run() if __name__ ==",
"self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev)",
"def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while self.running: command =",
"self.stop_search() print 'search stopped' def _help(self): print 'commands: start, stop, list, ' \\",
"n += 1 def _cmd_set_server(self, id): self._current_server = self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer",
"result = result['Result'] for d in result: print \"%s %s %s\" % (d.id,",
"[] self.commands = {'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help}",
"'browse, set_server, set_render, play, exit, help' def _exit(self): self.running = False def run(self):",
"id): self._current_server = self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def _cmd_browse(self, id):",
"print 'device %d:' % n print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:',",
"False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while self.running: command",
"_cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def _cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren', '*',",
"child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print",
"except KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def main(): print \"BRisa ControlPointAV example\\n\" cmdline",
"self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn): for dev in self.devices:",
"_cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result = result['Result'] for",
"for child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services",
"elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid command, try",
"dev.udn == udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n = 0 for dev in",
"udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n = 0 for dev in self.devices_found: print",
"command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid command, try help'",
"print 'Invalid command, try help' command = '' except KeyboardInterrupt, k: print 'quiting'",
"play, exit, help' def _exit(self): self.running = False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop)",
"= self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result = result['Result'] for d in result:",
"')[1]) else: print 'Invalid command, try help' command = '' except KeyboardInterrupt, k:",
"def _cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result = result['Result']",
"n print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print '\\ttype:', dev.device_type",
"# Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import",
"except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split('",
"__init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found = [] self.commands = {'start': self._search,",
"'Invalid command, try help' command = '' except KeyboardInterrupt, k: print 'quiting' reactor.main_quit()",
"exit, help' def _exit(self): self.running = False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main()",
"def on_remove_device(self, udn): for dev in self.devices: if dev.udn == udn: self.devices_found.remove(dev) break",
"dev.devices: print '\\tchild devices:' for child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:',",
"KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def main(): print \"BRisa ControlPointAV example\\n\" cmdline =",
"self.running = False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while",
"print '\\tchild devices:' for child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name",
"self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self,",
"(d.id, d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search started' def _stop(self): self.stop_search()",
"CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found = [] self.commands =",
"try: while self.running: command = str(raw_input('>>> ')) try: self.commands[command]() except KeyError: if command.startswith('browse'):",
"class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes() self.devices_found = [] self.commands",
"in self.devices_found: print 'device %d:' % n print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name",
"+= 1 def _cmd_set_server(self, id): self._current_server = self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer =",
"k: print 'quiting' reactor.main_quit() def main(): print \"BRisa ControlPointAV example\\n\" cmdline = CommandLineControlPointAV()",
"devices:' for child_dev in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:',",
"self.commands = {'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def",
"d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search started' def _stop(self): self.stop_search() print 'search",
"from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self)",
"the MIT license # http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright 2007-2008 <NAME>",
"_cmd_list_devices(self): n = 0 for dev in self.devices_found: print 'device %d:' % n",
"print \"%s %s %s\" % (d.id, d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print",
"main(): print \"BRisa ControlPointAV example\\n\" cmdline = CommandLineControlPointAV() cmdline.run() if __name__ == \"__main__\":",
"print '\\ttype:', dev.device_type if dev.devices: print '\\tchild devices:' for child_dev in dev.devices.values(): print",
"Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import sys",
"udn): for dev in self.devices: if dev.udn == udn: self.devices_found.remove(dev) break def _cmd_list_devices(self):",
"def _handle_cmds(self): try: while self.running: command = str(raw_input('>>> ')) try: self.commands[command]() except KeyError:",
"self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while self.running: command = str(raw_input('>>> '))",
"print '\\tudn:', dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print '\\ttype:', dev.device_type if",
"in self.devices: if dev.udn == udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n = 0",
"%s %s\" % (d.id, d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search started'",
"start, stop, list, ' \\ 'browse, set_server, set_render, play, exit, help' def _exit(self):",
"ControlPointAV from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running = True",
"n = 0 for dev in self.devices_found: print 'device %d:' % n print",
"= self.devices_found[id] def _cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result",
"on_remove_device(self, udn): for dev in self.devices: if dev.udn == udn: self.devices_found.remove(dev) break def",
"'*', 0, 10) result = result['Result'] for d in result: print \"%s %s",
"%s\" % (d.id, d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search started' def",
"'exit': self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev):",
"'\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print '\\ttype:', dev.device_type if dev.devices: print '\\tchild devices:'",
"0 for dev in self.devices_found: print 'device %d:' % n print '\\tudn:', dev.udn",
"== udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n = 0 for dev in self.devices_found:",
"try help' command = '' except KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def main():",
"self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result = result['Result'] for d in result: print",
"'' except KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def main(): print \"BRisa ControlPointAV example\\n\"",
"dev.friendly_name print '\\tservices:', dev.services print '\\ttype:', dev.device_type if dev.devices: print '\\tchild devices:' for",
"run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while self.running: command = str(raw_input('>>>",
"_help(self): print 'commands: start, stop, list, ' \\ 'browse, set_server, set_render, play, exit,",
"from brisa.core.threaded_call import run_async_function class CommandLineControlPointAV(ControlPointAV): def __init__(self): ControlPointAV.__init__(self) self.running = True self._initial_subscribes()",
"def _cmd_set_server(self, id): self._current_server = self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def",
"\"%s %s %s\" % (d.id, d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice') print 'search",
"_exit(self): self.running = False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try:",
"'\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print n += 1 def _cmd_set_server(self, id): self._current_server",
"0, 10) result = result['Result'] for d in result: print \"%s %s %s\"",
"'\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print n += 1 def",
"in result: print \"%s %s %s\" % (d.id, d.title, d.upnp_class) def _search(self): self.start_search(600,",
"_cmd_set_server(self, id): self._current_server = self.devices_found[id] def _cmd_set_render(self, id): self._current_renderer = self.devices_found[id] def _cmd_browse(self,",
"self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self,",
"command = '' except KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def main(): print \"BRisa",
"# http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors",
"reactor = install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import run_async_function",
"command = str(raw_input('>>> ')) try: self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif",
"for dev in self.devices: if dev.udn == udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n",
"elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else:",
"self.devices: if dev.udn == udn: self.devices_found.remove(dev) break def _cmd_list_devices(self): n = 0 for",
"= result['Result'] for d in result: print \"%s %s %s\" % (d.id, d.title,",
"reactor.main_quit() def main(): print \"BRisa ControlPointAV example\\n\" cmdline = CommandLineControlPointAV() cmdline.run() if __name__",
"\\ 'browse, set_server, set_render, play, exit, help' def _exit(self): self.running = False def",
"self.av_play(command.split(' ')[1]) else: print 'Invalid command, try help' command = '' except KeyboardInterrupt,",
"self.devices_found.remove(dev) break def _cmd_list_devices(self): n = 0 for dev in self.devices_found: print 'device",
"self.devices_found = [] self.commands = {'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices, 'exit': self._exit,",
"in dev.devices.values(): print '\\t\\tudn:', child_dev.udn print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:',",
"'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def",
"'quiting' reactor.main_quit() def main(): print \"BRisa ControlPointAV example\\n\" cmdline = CommandLineControlPointAV() cmdline.run() if",
"'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def",
"print 'search stopped' def _help(self): print 'commands: start, stop, list, ' \\ 'browse,",
"self._current_renderer = self.devices_found[id] def _cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren', '*', 0, 10)",
"KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1]))",
"self._stop, 'list': self._cmd_list_devices, 'exit': self._exit, 'help': self._help} def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device)",
"stopped' def _help(self): print 'commands: start, stop, list, ' \\ 'browse, set_server, set_render,",
"id): result = self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result = result['Result'] for d",
"self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid command, try help' command",
"'\\ttype:', dev.device_type if dev.devices: print '\\tchild devices:' for child_dev in dev.devices.values(): print '\\t\\tudn:',",
"result = self.browse(id, 'BrowseDirectChildren', '*', 0, 10) result = result['Result'] for d in",
"install_default_reactor reactor = install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import",
"True self._initial_subscribes() self.devices_found = [] self.commands = {'start': self._search, 'stop': self._stop, 'list': self._cmd_list_devices,",
"def _cmd_list_devices(self): n = 0 for dev in self.devices_found: print 'device %d:' %",
"= True self._initial_subscribes() self.devices_found = [] self.commands = {'start': self._search, 'stop': self._stop, 'list':",
"self.running: command = str(raw_input('>>> ')) try: self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1])",
"print '\\t\\tfriendly_name:', child_dev.friendly_name print '\\t\\tservices:', dev.services print '\\t\\ttype:', child_dev.device_type print n += 1",
"dev.udn print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print '\\ttype:', dev.device_type if dev.devices: print",
"# Licensed under the MIT license # http://opensource.org/licenses/mit-license.php or see LICENSE file. #",
"id): self._current_renderer = self.devices_found[id] def _cmd_browse(self, id): result = self.browse(id, 'BrowseDirectChildren', '*', 0,",
"'commands: start, stop, list, ' \\ 'browse, set_server, set_render, play, exit, help' def",
"run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def _handle_cmds(self): try: while self.running: command = str(raw_input('>>> ')) try:",
"Licensed under the MIT license # http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright",
"= install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import ControlPointAV from brisa.core.threaded_call import run_async_function class",
"brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import sys from brisa.upnp.control_point.control_point_av import ControlPointAV from",
"self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid",
"= '' except KeyboardInterrupt, k: print 'quiting' reactor.main_quit() def main(): print \"BRisa ControlPointAV",
"def _initial_subscribes(self): self.subscribe('new_device_event', self.on_new_device) self.subscribe('remove_device_event', self.on_remove_device) def on_new_device(self, dev): self.devices_found.append(dev) def on_remove_device(self, udn):",
"command.startswith('play'): self.av_play(command.split(' ')[1]) else: print 'Invalid command, try help' command = '' except",
"see LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor",
"= str(raw_input('>>> ')) try: self.commands[command]() except KeyError: if command.startswith('browse'): self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'):",
"result: print \"%s %s %s\" % (d.id, d.title, d.upnp_class) def _search(self): self.start_search(600, 'upnp:rootdevice')",
"'search stopped' def _help(self): print 'commands: start, stop, list, ' \\ 'browse, set_server,",
"help' def _exit(self): self.running = False def run(self): self.start() run_async_function(self._handle_cmds) reactor.add_after_stop_func(self.stop) reactor.main() def",
"self._cmd_browse(command.split(' ')[1]) elif command.startswith('set_server'): self._cmd_set_server(int(command.split(' ')[1])) elif command.startswith('set_render'): self._cmd_set_render(int(command.split(' ')[1])) elif command.startswith('play'): self.av_play(command.split('",
"print '\\tfriendly_name:', dev.friendly_name print '\\tservices:', dev.services print '\\ttype:', dev.device_type if dev.devices: print '\\tchild"
] |
[
"collections import OrderedDict from django.utils.module_loading import import_string from django.conf import settings from django.urls.resolvers",
"有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in urlpattern: if isinstance(item, URLPattern): # 非路由分发 if",
"def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def recursive_url(pre_namespace,",
"def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名 :param pre_url: url前缀",
"非路由分发 if not item.name: continue if pre_namespace: name = '%s:%s' % (pre_namespace, item.name)",
"name = item.name url = pre_url + item.pattern.regex.pattern url = url.replace('^', '').replace('$', '')",
"pre_namespace: if item.namespace: namespace = '%s:%s' % (pre_namespace, item.namespace) else: # namespace =",
"pre_namespace: name = '%s:%s' % (pre_namespace, item.name) else: name = item.name url =",
"# 非路由分发 if not item.name: continue if pre_namespace: name = '%s:%s' % (pre_namespace,",
"import import_string from django.conf import settings from django.urls.resolvers import URLResolver, URLPattern import re",
"pre_url + item.pattern.regex.pattern url = url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue",
"# 路由分发 if pre_namespace: if item.namespace: namespace = '%s:%s' % (pre_namespace, item.namespace) else:",
"import re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True",
"continue if pre_namespace: name = '%s:%s' % (pre_namespace, item.name) else: name = item.name",
"item.namespace else: namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict)",
"= pre_namespace else: if item.namespace: namespace = item.namespace else: namespace = None #",
"urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名 :param pre_url: url前缀 :param urlpattern: 路由关系表",
"else: namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def",
"else: name = item.name url = pre_url + item.pattern.regex.pattern url = url.replace('^', '').replace('$',",
"url} elif isinstance(item, URLResolver): # 路由分发 if pre_namespace: if item.namespace: namespace = '%s:%s'",
"= item.name url = pre_url + item.pattern.regex.pattern url = url.replace('^', '').replace('$', '') #",
"import URLResolver, URLPattern import re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex,",
"check_url_exclude(url): continue url_order_dict[name] = {'name': name, 'url': url} elif isinstance(item, URLResolver): # 路由分发",
"= {'name': name, 'url': url} elif isinstance(item, URLResolver): # 路由分发 if pre_namespace: if",
"(pre_namespace, item.name) else: name = item.name url = pre_url + item.pattern.regex.pattern url =",
"namespace = item.namespace else: namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern,",
"= '%s:%s' % (pre_namespace, item.name) else: name = item.name url = pre_url +",
"url = url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] = {'name':",
"url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] = {'name': name, 'url':",
"URLResolver, URLPattern import re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url):",
"% (pre_namespace, item.name) else: name = item.name url = pre_url + item.pattern.regex.pattern url",
"'url': url} elif isinstance(item, URLResolver): # 路由分发 if pre_namespace: if item.namespace: namespace =",
"OrderedDict from django.utils.module_loading import import_string from django.conf import settings from django.urls.resolvers import URLResolver,",
"name = '%s:%s' % (pre_namespace, item.name) else: name = item.name url = pre_url",
"if pre_namespace: name = '%s:%s' % (pre_namespace, item.name) else: name = item.name url",
"if check_url_exclude(url): continue url_order_dict[name] = {'name': name, 'url': url} elif isinstance(item, URLResolver): #",
"from django.utils.module_loading import import_string from django.conf import settings from django.urls.resolvers import URLResolver, URLPattern",
"url_order_dict[name] = {'name': name, 'url': url} elif isinstance(item, URLResolver): # 路由分发 if pre_namespace:",
"+ item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict() root = import_string(settings.ROOT_URLCONF) recursive_url(None,",
"'%s:%s' % (pre_namespace, item.namespace) else: # namespace = item.namespace # 另一种写法 namespace =",
"settings from django.urls.resolvers import URLResolver, URLPattern import re def check_url_exclude(url): for regex in",
"(pre_namespace, item.namespace) else: # namespace = item.namespace # 另一种写法 namespace = pre_namespace else:",
"递归发现url :param pre_namespace: 根别名 :param pre_url: url前缀 :param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由",
"namespace = pre_namespace else: if item.namespace: namespace = item.namespace else: namespace = None",
"\"\"\" for item in urlpattern: if isinstance(item, URLPattern): # 非路由分发 if not item.name:",
"check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def recursive_url(pre_namespace, pre_url,",
"= '%s:%s' % (pre_namespace, item.namespace) else: # namespace = item.namespace # 另一种写法 namespace",
"django.utils.module_loading import import_string from django.conf import settings from django.urls.resolvers import URLResolver, URLPattern import",
"name, 'url': url} elif isinstance(item, URLResolver): # 路由分发 if pre_namespace: if item.namespace: namespace",
"True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名 :param pre_url:",
"url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict() root = import_string(settings.ROOT_URLCONF) recursive_url(None, '/', root.urlpatterns, url_order_dict)",
"import OrderedDict from django.utils.module_loading import import_string from django.conf import settings from django.urls.resolvers import",
"recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名 :param pre_url: url前缀 :param",
"pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名 :param pre_url: url前缀 :param urlpattern:",
"pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict() root = import_string(settings.ROOT_URLCONF)",
"= None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict",
"item.namespace: namespace = item.namespace else: namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url +",
"路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in urlpattern: if isinstance(item, URLPattern):",
"URLResolver): # 路由分发 if pre_namespace: if item.namespace: namespace = '%s:%s' % (pre_namespace, item.namespace)",
"def get_all_url_dict(): url_order_dict = OrderedDict() root = import_string(settings.ROOT_URLCONF) recursive_url(None, '/', root.urlpatterns, url_order_dict) return",
"= item.namespace else: namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns,",
"item.name) else: name = item.name url = pre_url + item.pattern.regex.pattern url = url.replace('^',",
"+ item.pattern.regex.pattern url = url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name]",
"else: # namespace = item.namespace # 另一种写法 namespace = pre_namespace else: if item.namespace:",
"url前缀 :param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in urlpattern:",
"% (pre_namespace, item.namespace) else: # namespace = item.namespace # 另一种写法 namespace = pre_namespace",
"isinstance(item, URLResolver): # 路由分发 if pre_namespace: if item.namespace: namespace = '%s:%s' % (pre_namespace,",
"item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict() root = import_string(settings.ROOT_URLCONF) recursive_url(None, '/',",
"item.namespace # 另一种写法 namespace = pre_namespace else: if item.namespace: namespace = item.namespace else:",
"url = pre_url + item.pattern.regex.pattern url = url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if",
"# namespace = item.namespace # 另一种写法 namespace = pre_namespace else: if item.namespace: namespace",
"pre_url: url前缀 :param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in",
"get_all_url_dict(): url_order_dict = OrderedDict() root = import_string(settings.ROOT_URLCONF) recursive_url(None, '/', root.urlpatterns, url_order_dict) return url_order_dict",
"# 另一种写法 namespace = pre_namespace else: if item.namespace: namespace = item.namespace else: namespace",
"from collections import OrderedDict from django.utils.module_loading import import_string from django.conf import settings from",
"item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict() root = import_string(settings.ROOT_URLCONF) recursive_url(None, '/', root.urlpatterns,",
":param pre_url: url前缀 :param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item",
"isinstance(item, URLPattern): # 非路由分发 if not item.name: continue if pre_namespace: name = '%s:%s'",
"item.namespace) else: # namespace = item.namespace # 另一种写法 namespace = pre_namespace else: if",
"namespace = item.namespace # 另一种写法 namespace = pre_namespace else: if item.namespace: namespace =",
"re.match(regex, url): return True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace:",
"import_string from django.conf import settings from django.urls.resolvers import URLResolver, URLPattern import re def",
"url): return True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名",
"if pre_namespace: if item.namespace: namespace = '%s:%s' % (pre_namespace, item.namespace) else: # namespace",
"regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict):",
"URLPattern): # 非路由分发 if not item.name: continue if pre_namespace: name = '%s:%s' %",
"namespace = '%s:%s' % (pre_namespace, item.namespace) else: # namespace = item.namespace # 另一种写法",
"item in urlpattern: if isinstance(item, URLPattern): # 非路由分发 if not item.name: continue if",
"django.conf import settings from django.urls.resolvers import URLResolver, URLPattern import re def check_url_exclude(url): for",
"= item.namespace # 另一种写法 namespace = pre_namespace else: if item.namespace: namespace = item.namespace",
":param pre_namespace: 根别名 :param pre_url: url前缀 :param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return:",
"路由分发 if pre_namespace: if item.namespace: namespace = '%s:%s' % (pre_namespace, item.namespace) else: #",
"re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def",
"# print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict()",
"URLPattern import re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return",
"import settings from django.urls.resolvers import URLResolver, URLPattern import re def check_url_exclude(url): for regex",
":return: \"\"\" for item in urlpattern: if isinstance(item, URLPattern): # 非路由分发 if not",
"from django.conf import settings from django.urls.resolvers import URLResolver, URLPattern import re def check_url_exclude(url):",
"in urlpattern: if isinstance(item, URLPattern): # 非路由分发 if not item.name: continue if pre_namespace:",
"urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in urlpattern: if isinstance(item,",
"namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict():",
"for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def recursive_url(pre_namespace, pre_url, urlpattern,",
"elif isinstance(item, URLResolver): # 路由分发 if pre_namespace: if item.namespace: namespace = '%s:%s' %",
"in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\"",
"for item in urlpattern: if isinstance(item, URLPattern): # 非路由分发 if not item.name: continue",
"另一种写法 namespace = pre_namespace else: if item.namespace: namespace = item.namespace else: namespace =",
"settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): return True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url",
"pre_namespace else: if item.namespace: namespace = item.namespace else: namespace = None # print(item.pattern.regex.pattern)",
"if item.namespace: namespace = '%s:%s' % (pre_namespace, item.namespace) else: # namespace = item.namespace",
"pre_namespace: 根别名 :param pre_url: url前缀 :param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\"",
"if isinstance(item, URLPattern): # 非路由分发 if not item.name: continue if pre_namespace: name =",
"continue url_order_dict[name] = {'name': name, 'url': url} elif isinstance(item, URLResolver): # 路由分发 if",
"= url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] = {'name': name,",
"return True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名 :param",
"if not item.name: continue if pre_namespace: name = '%s:%s' % (pre_namespace, item.name) else:",
"'') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] = {'name': name, 'url': url} elif",
"'').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] = {'name': name, 'url': url}",
":param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in urlpattern: if",
"django.urls.resolvers import URLResolver, URLPattern import re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if",
"None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict =",
"if re.match(regex, url): return True def recursive_url(pre_namespace, pre_url, urlpattern, url_order_dict): \"\"\" 递归发现url :param",
"= pre_url + item.pattern.regex.pattern url = url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url):",
"from django.urls.resolvers import URLResolver, URLPattern import re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE:",
"去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] = {'name': name, 'url': url} elif isinstance(item, URLResolver):",
"\"\"\" 递归发现url :param pre_namespace: 根别名 :param pre_url: url前缀 :param urlpattern: 路由关系表 :param url_order_dict",
"'%s:%s' % (pre_namespace, item.name) else: name = item.name url = pre_url + item.pattern.regex.pattern",
"url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in urlpattern: if isinstance(item, URLPattern): # 非路由分发",
"print(item.pattern.regex.pattern) recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict() root",
"# 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] = {'name': name, 'url': url} elif isinstance(item,",
"item.name url = pre_url + item.pattern.regex.pattern url = url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀",
"{'name': name, 'url': url} elif isinstance(item, URLResolver): # 路由分发 if pre_namespace: if item.namespace:",
":param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for item in urlpattern: if isinstance(item, URLPattern): #",
"item.name: continue if pre_namespace: name = '%s:%s' % (pre_namespace, item.name) else: name =",
"urlpattern: if isinstance(item, URLPattern): # 非路由分发 if not item.name: continue if pre_namespace: name",
"recursive_url(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_order_dict) def get_all_url_dict(): url_order_dict = OrderedDict() root =",
"if item.namespace: namespace = item.namespace else: namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace, pre_url",
"item.pattern.regex.pattern url = url.replace('^', '').replace('$', '') # 去掉正则表达式里的前缀和后缀 if check_url_exclude(url): continue url_order_dict[name] =",
"not item.name: continue if pre_namespace: name = '%s:%s' % (pre_namespace, item.name) else: name",
"url_order_dict): \"\"\" 递归发现url :param pre_namespace: 根别名 :param pre_url: url前缀 :param urlpattern: 路由关系表 :param",
"item.namespace: namespace = '%s:%s' % (pre_namespace, item.namespace) else: # namespace = item.namespace #",
"根别名 :param pre_url: url前缀 :param urlpattern: 路由关系表 :param url_order_dict 有序url字典,用于保存递归中获取的所有路由 :return: \"\"\" for",
"else: if item.namespace: namespace = item.namespace else: namespace = None # print(item.pattern.regex.pattern) recursive_url(namespace,"
] |
[
"= CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1",
"qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True",
"True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() ==",
"not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled()",
"250 # ms def stateIsFalse(self, state): return not state def stateIsTrue(self, state): print(\"A:\",",
"qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start",
"# Developed for LSST System Integration, Test and Commissioning. # # See the",
"cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc)",
"a 3-clause BSD-style # license that can be found in the LICENSE file.",
"assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self, qtbot): cc =",
"with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not",
"source code is governed by a 3-clause BSD-style # license that can be",
"check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is",
"qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self, qtbot):",
"cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot): cc =",
"that can be found in the LICENSE file. from PyQt5.QtCore import Qt from",
"assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled()",
"qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert",
"details of code ownership. # # Use of this source code is governed",
"cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self,",
"cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton)",
"stateIsFalse(self, state): return not state def stateIsTrue(self, state): print(\"A:\", state) return state def",
"ms def stateIsFalse(self, state): return not state def stateIsTrue(self, state): print(\"A:\", state) return",
"is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled() is True with qtbot.waitSignal(cc.takeScreenshotState, timeout=self.fast_timeout):",
"Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert",
"== 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget()",
"cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc",
"# # Use of this source code is governed by a 3-clause BSD-style",
"assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget()",
"test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton)",
"512 def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton)",
"= CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start",
"def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked()",
"cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked()",
"Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse):",
"def setup_class(self): self.fast_timeout = 250 # ms def stateIsFalse(self, state): return not state",
"test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert",
"Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with",
"governed by a 3-clause BSD-style # license that can be found in the",
"# ms def stateIsFalse(self, state): return not state def stateIsTrue(self, state): print(\"A:\", state)",
"Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout = 250 #",
"assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState,",
"test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert",
"\"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc)",
"Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert",
"True assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not",
"assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() ==",
"== \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState,",
"== 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512",
"file is part of spot_motion_monitor. # # Developed for LSST System Integration, Test",
"CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled()",
"\"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout,",
"assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() ==",
"of code ownership. # # Use of this source code is governed by",
"cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot):",
"not state def stateIsTrue(self, state): print(\"A:\", state) return state def test_startStopCameraButton(self, qtbot): cc",
"Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue):",
"file. from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def setup_class(self):",
"assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert",
"LSST System Integration, Test and Commissioning. # # See the LICENSE file at",
"qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc)",
"ownership. # # Use of this source code is governed by a 3-clause",
"cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text()",
"== 149 def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() ==",
"Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() ==",
"150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self,",
"CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire",
"Developed for LSST System Integration, Test and Commissioning. # # See the LICENSE",
"cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show()",
"cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc",
"40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert",
"qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked()",
"assert cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc)",
"See the LICENSE file at the top-level directory of this distribution # for",
"with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start",
"cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled() is True with qtbot.waitSignal(cc.takeScreenshotState,",
"Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert",
"state) return state def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not",
"1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def",
"cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\"",
"def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton,",
"cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc)",
"assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox,",
"assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not",
"# See the LICENSE file at the top-level directory of this distribution #",
"assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self,",
"timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" def",
"cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert",
"def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked()",
"not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton,",
"return state def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked()",
"cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is",
"cc.acquireFramesButton.text() == \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked()",
"assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse):",
"assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert",
"check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire",
"cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget()",
"BSD-style # license that can be found in the LICENSE file. from PyQt5.QtCore",
"license that can be found in the LICENSE file. from PyQt5.QtCore import Qt",
"at the top-level directory of this distribution # for details of code ownership.",
"this distribution # for details of code ownership. # # Use of this",
"state def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert",
"spot_motion_monitor. # # Developed for LSST System Integration, Test and Commissioning. # #",
"test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with",
"qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton,",
"# # See the LICENSE file at the top-level directory of this distribution",
"code is governed by a 3-clause BSD-style # license that can be found",
"= CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue):",
"be found in the LICENSE file. from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import",
"TestCameraControl(): def setup_class(self): self.fast_timeout = 250 # ms def stateIsFalse(self, state): return not",
"test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not",
"is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() ==",
"cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled() is",
"is True assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert",
"cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() ==",
"False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled() is True with qtbot.waitSignal(cc.takeScreenshotState, timeout=self.fast_timeout): qtbot.mouseClick(cc.takeScreenshotButton,",
"cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value()",
"cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149",
"check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert",
"System Integration, Test and Commissioning. # # See the LICENSE file at the",
"assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled() is True with",
"cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40",
"== 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown()",
"\"Start Camera\" def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert",
"cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton)",
"cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() ==",
"cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc)",
"assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue):",
"qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\"",
"qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" with",
"qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert cc.startStopButton.isEnabled()",
"qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc =",
"assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value()",
"not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled()",
"timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with",
"cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150",
"state): print(\"A:\", state) return state def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc)",
"from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout = 250 # ms",
"Commissioning. # # See the LICENSE file at the top-level directory of this",
"# This file is part of spot_motion_monitor. # # Developed for LSST System",
"check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot):",
"= 250 # ms def stateIsFalse(self, state): return not state def stateIsTrue(self, state):",
"def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0)",
"cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not",
"cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is False with",
"cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() ==",
"is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text()",
"class TestCameraControl(): def setup_class(self): self.fast_timeout = 250 # ms def stateIsFalse(self, state): return",
"1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert",
"assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot):",
"cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value()",
"= CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" assert",
"assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton,",
"= CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert",
"import CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout = 250 # ms def stateIsFalse(self,",
"assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert",
"setup_class(self): self.fast_timeout = 250 # ms def stateIsFalse(self, state): return not state def",
"assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert",
"cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150",
"cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False",
"= CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048",
"Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc =",
"Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text()",
"qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\" assert",
"= CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self,",
"qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value()",
"qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled() is True with qtbot.waitSignal(cc.takeScreenshotState, timeout=self.fast_timeout): qtbot.mouseClick(cc.takeScreenshotButton, Qt.LeftButton)",
"cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown()",
"Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton)",
"2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget()",
"== \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked()",
"# license that can be found in the LICENSE file. from PyQt5.QtCore import",
"directory of this distribution # for details of code ownership. # # Use",
"this source code is governed by a 3-clause BSD-style # license that can",
"Integration, Test and Commissioning. # # See the LICENSE file at the top-level",
"not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton,",
"top-level directory of this distribution # for details of code ownership. # #",
"in the LICENSE file. from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class",
"can be found in the LICENSE file. from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget",
"with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\"",
"with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start",
"cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked()",
"def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert",
"of this distribution # for details of code ownership. # # Use of",
"assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert",
"assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget()",
"assert cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is False",
"the LICENSE file. from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl():",
"assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert",
"qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState,",
"def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text()",
"with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text()",
"Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout,",
"qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire",
"cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout,",
"\"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout,",
"Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse):",
"Test and Commissioning. # # See the LICENSE file at the top-level directory",
"# for details of code ownership. # # Use of this source code",
"cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton)",
"part of spot_motion_monitor. # # Developed for LSST System Integration, Test and Commissioning.",
"\"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert",
"spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout = 250 # ms def",
"Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self, qtbot): cc",
"cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert",
"assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled()",
"False assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked()",
"from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout",
"LICENSE file. from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def",
"not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not",
"code ownership. # # Use of this source code is governed by a",
"assert cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked()",
"qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value()",
"print(\"A:\", state) return state def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert",
"assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert",
"cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot): cc",
"cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton)",
"by a 3-clause BSD-style # license that can be found in the LICENSE",
"distribution # for details of code ownership. # # Use of this source",
"check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self,",
"== \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState,",
"cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value()",
"found in the LICENSE file. from PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget",
"is governed by a 3-clause BSD-style # license that can be found in",
"== 150 cc.roiFpsSpinBox.stepUp() assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def",
"cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert",
"not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot):",
"qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def",
"== 512 def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox,",
"is part of spot_motion_monitor. # # Developed for LSST System Integration, Test and",
"cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton)",
"qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled() is True",
"Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled()",
"CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200)",
"qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value()",
"\"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not",
"assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc =",
"== \"Start Camera\" def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton)",
"cc.acquireFramesButton.isEnabled() is True with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert",
"qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() ==",
"# Use of this source code is governed by a 3-clause BSD-style #",
"== 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepUp()",
"assert cc.roiFpsSpinBox.value() == 150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot): cc",
"CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is False qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.takeScreenshotButton.isEnabled()",
"the LICENSE file at the top-level directory of this distribution # for details",
"is False assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert",
"Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def",
"timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled()",
"# # Developed for LSST System Integration, Test and Commissioning. # # See",
"cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is True with",
"qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout,",
"qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled()",
"def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp()",
"file at the top-level directory of this distribution # for details of code",
"cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not",
"for details of code ownership. # # Use of this source code is",
"3-clause BSD-style # license that can be found in the LICENSE file. from",
"cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\"",
"CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot):",
"qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState,",
"PyQt5.QtCore import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout =",
"check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState,",
"CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout = 250 # ms def stateIsFalse(self, state):",
"qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text()",
"assert cc.roiFpsSpinBox.value() == 40 cc.roiFpsSpinBox.setValue(0) assert cc.roiFpsSpinBox.value() == 1 cc.roiFpsSpinBox.setValue(200) assert cc.roiFpsSpinBox.value() ==",
"assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert",
"assert cc.startStopButton.text() == \"Stop Camera\" assert cc.acquireRoiCheckBox.isEnabled() is True assert cc.acquireFramesButton.isEnabled() is True",
"qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert",
"== 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot): cc =",
"== \"Start Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show()",
"cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() == 512 def test_showFramesCheckBox(self, qtbot): cc = CameraControlWidget() cc.show()",
"== \"Start Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert",
"Use of this source code is governed by a 3-clause BSD-style # license",
"cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton)",
"timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self,",
"CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireRoiCheckBox,",
"qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False",
"state def stateIsTrue(self, state): print(\"A:\", state) return state def test_startStopCameraButton(self, qtbot): cc =",
"state): return not state def stateIsTrue(self, state): print(\"A:\", state) return state def test_startStopCameraButton(self,",
"cc.acquireRoiCheckBox.isChecked() assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton)",
"cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton,",
"not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.takeScreenshotButton.isEnabled() is",
"149 def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024",
"cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024) cc.bufferSizeSpinBox.stepDown() assert cc.bufferSizeSpinBox.value() ==",
"test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() ==",
"of this source code is governed by a 3-clause BSD-style # license that",
"return not state def stateIsTrue(self, state): print(\"A:\", state) return state def test_startStopCameraButton(self, qtbot):",
"qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\"",
"assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton,",
"not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show()",
"150 cc.roiFpsSpinBox.stepDown() assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show()",
"Camera\" def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert not",
"stateIsTrue(self, state): print(\"A:\", state) return state def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget() cc.show()",
"cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop Acquire Frames\" with qtbot.waitSignal(cc.acquireFramesState, timeout=self.fast_timeout,",
"False with qtbot.waitSignal(cc.cameraState, timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.startStopButton, Qt.LeftButton) assert cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Stop",
"assert cc.roiFpsSpinBox.value() == 149 def test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert",
"of spot_motion_monitor. # # Developed for LSST System Integration, Test and Commissioning. #",
"cc.show() qtbot.addWidget(cc) assert not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is",
"cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value()",
"test_bufferSizeSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert",
"def stateIsTrue(self, state): print(\"A:\", state) return state def test_startStopCameraButton(self, qtbot): cc = CameraControlWidget()",
"assert not cc.roiFpsSpinBox.isEnabled() assert not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert",
"the top-level directory of this distribution # for details of code ownership. #",
"self.fast_timeout = 250 # ms def stateIsFalse(self, state): return not state def stateIsTrue(self,",
"cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget() cc.show()",
"with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled()",
"cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def",
"assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.roiFpsSpinBox.value() ==",
"cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" assert cc.acquireRoiCheckBox.isEnabled() is False assert cc.acquireFramesButton.isEnabled() is",
"CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.bufferSizeSpinBox.value() == 1024 cc.bufferSizeSpinBox.stepUp() assert cc.bufferSizeSpinBox.value() == 2048 cc.bufferSizeSpinBox.setValue(1024)",
"LICENSE file at the top-level directory of this distribution # for details of",
"not cc.bufferSizeSpinBox.isEnabled() with qtbot.waitSignal(cc.acquireRoiState, timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled()",
"import Qt from spot_motion_monitor.views.camera_control_widget import CameraControlWidget class TestCameraControl(): def setup_class(self): self.fast_timeout = 250",
"qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert cc.showFramesCheckBox.isChecked() qtbot.mouseClick(cc.showFramesCheckBox, Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked()",
"timeout=self.fast_timeout, check_params_cb=self.stateIsFalse): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert not cc.acquireFramesButton.isChecked() assert cc.acquireFramesButton.text() == \"Start Acquire Frames\"",
"This file is part of spot_motion_monitor. # # Developed for LSST System Integration,",
"Acquire Frames\" assert cc.startStopButton.isEnabled() def test_acquireRoiCheckbox(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) qtbot.mouseClick(cc.startStopButton,",
"and Commissioning. # # See the LICENSE file at the top-level directory of",
"def stateIsFalse(self, state): return not state def stateIsTrue(self, state): print(\"A:\", state) return state",
"timeout=self.fast_timeout, check_params_cb=self.stateIsTrue): qtbot.mouseClick(cc.acquireFramesButton, Qt.LeftButton) assert cc.acquireFramesButton.isChecked() assert not cc.startStopButton.isEnabled() assert cc.acquireFramesButton.text() == \"Stop",
"Qt.LeftButton) assert not cc.showFramesCheckBox.isChecked() def test_takeScreenshotButton(self, qtbot): cc = CameraControlWidget() cc.show() qtbot.addWidget(cc) assert",
"qtbot.mouseClick(cc.acquireRoiCheckBox, Qt.LeftButton) assert not cc.acquireRoiCheckBox.isChecked() assert cc.roiFpsSpinBox.isEnabled() assert cc.bufferSizeSpinBox.isEnabled() def test_roiFpsSpinBox(self, qtbot): cc",
"for LSST System Integration, Test and Commissioning. # # See the LICENSE file",
"not cc.startStopButton.isChecked() assert cc.startStopButton.text() == \"Start Camera\" def test_acquireFramesButton(self, qtbot): cc = CameraControlWidget()"
] |
[
"= MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as",
"dne = [] for imgnum, file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')):",
"imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize)",
"corr_root): dne = [] for imgnum, file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum),",
"e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as f: f.write('') if __name__ == \"__main__\":",
"save_dir, opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except",
"in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return list(zip(img_nums, file_names))[:10000] def",
"= check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def main(): import numpy as np from",
"vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for imgnum in tqdm(missing): print(imgnum) save_dir",
"for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return img_nums,",
"sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return",
"list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne = [] for imgnum, file_path in tqdm(get_imgnums(src_root)):",
"= sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num in img_nums]",
"'BtoA.npy')): dne.append(imgnum) return dne missing = check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def main():",
"= [f'{base_name}_{num}.png' for num in img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne",
"file_names))[:10000] def check_missing(src_root, corr_root): dne = [] for imgnum, file_path in tqdm(get_imgnums(src_root)): if",
"opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A, B) mls =",
"main(): import numpy as np from models import vgg19_model from algorithms import neural_best_buddies",
"if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A",
"netdissect import pidfile from options.options import Options from tqdm import tqdm opt =",
"missing = check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def main(): import numpy as np",
"models import vgg19_model from algorithms import neural_best_buddies as NBBs from util import util",
"= os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape)",
"dne.append(imgnum) return dne missing = check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def main(): import",
"on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target,",
"= os.path.basename(opt.source) def main(): import numpy as np from models import vgg19_model from",
"os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num",
"= sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num in img_nums]",
"sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return",
"import tqdm opt = Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in",
"from util import util from util import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images",
"= Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names =",
"Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png'",
"from models import vgg19_model from algorithms import neural_best_buddies as NBBs from util import",
"file_names def get_imgnums(root): base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)])",
"os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root,",
"in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return img_nums, file_names def",
"img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne = [] for imgnum, file_path",
"os from netdissect import pidfile from options.options import Options from tqdm import tqdm",
"try: print('Working on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B",
"opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32)",
"opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception",
"def check_missing(src_root, corr_root): dne = [] for imgnum, file_path in tqdm(get_imgnums(src_root)): if not",
"opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir)",
"from options.options import Options from tqdm import tqdm opt = Options().parse() def get_imgs():",
"MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for imgnum in tqdm(missing): print(imgnum)",
"num in img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne = [] for",
"except Exception as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as f: f.write('') if",
"'BtoA.npy')): continue try: print('Working on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path,",
"imgnum in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try:",
"from netdissect import pidfile from options.options import Options from tqdm import tqdm opt",
"util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau,",
"util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final,",
"A = util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19,",
"opt.k_final, opt.fast) points = nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as",
"<reponame>iviazovetskyi/rewriting import os from netdissect import pidfile from options.options import Options from tqdm",
"get_imgs() for imgnum in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')):",
"str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png')",
"util import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for imgnum in",
"source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape,",
"for f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return list(zip(img_nums,",
"[f'{base_name}_{num}.png' for num in img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne =",
"MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as f:",
"import vgg19_model from algorithms import neural_best_buddies as NBBs from util import util from",
"opt.results_dir) base_name = os.path.basename(opt.source) def main(): import numpy as np from models import",
"vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for imgnum in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir,",
"import Options from tqdm import tqdm opt = Options().parse() def get_imgs(): img_nums =",
"numpy as np from models import vgg19_model from algorithms import neural_best_buddies as NBBs",
"[f'{base_name}_{num}.png' for num in img_nums] return img_nums, file_names def get_imgnums(root): base_name = os.path.basename(root)",
"os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs",
"print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points",
"return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne = [] for imgnum, file_path in",
"in img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne = [] for imgnum,",
"return img_nums, file_names def get_imgnums(root): base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f",
"num in img_nums] return img_nums, file_names def get_imgnums(root): base_name = os.path.basename(root) img_nums =",
"= get_imgs() for imgnum in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir,",
"points = nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e)",
"base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png'",
"opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size,",
"nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A,",
"img_nums, file_names def get_imgnums(root): base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in",
"in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working",
"mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w')",
"= os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for",
"tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on',",
"vgg19_model from algorithms import neural_best_buddies as NBBs from util import util from util",
"import numpy as np from models import vgg19_model from algorithms import neural_best_buddies as",
"from tqdm import tqdm opt = Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for",
"options.options import Options from tqdm import tqdm opt = Options().parse() def get_imgs(): img_nums",
"for num in img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root): dne = []",
"os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return img_nums, file_names def get_imgnums(root):",
"os.path.basename(opt.source) def main(): import numpy as np from models import vgg19_model from algorithms",
"imgnum, file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing",
"= util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level,",
"NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A, B) mls",
"f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return list(zip(img_nums, file_names))[:10000]",
"print('Working on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B =",
"img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num in",
"for imgnum in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue",
"util from util import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for",
"mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as f: f.write('')",
"np from models import vgg19_model from algorithms import neural_best_buddies as NBBs from util",
"util import util from util import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images =",
"opt.fast) points = nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e:",
"opt = Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names",
"= [f'{base_name}_{num}.png' for num in img_nums] return img_nums, file_names def get_imgnums(root): base_name =",
"img_nums] return img_nums, file_names def get_imgnums(root): base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for",
"file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing =",
"img_nums, images = get_imgs() for imgnum in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum))",
"save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on', imgnum) source_path",
"[] for imgnum, file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return",
"as NBBs from util import util from util import MLS vgg19 = vgg19_model.define_Vgg19(opt)",
"opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast)",
"str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing = check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def",
"def main(): import numpy as np from models import vgg19_model from algorithms import",
"def get_imgnums(root): base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names",
"check_missing(src_root, corr_root): dne = [] for imgnum, file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root,",
"algorithms import neural_best_buddies as NBBs from util import util from util import MLS",
"= vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for imgnum in tqdm(missing): print(imgnum) save_dir =",
"from util import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for imgnum",
"if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing = check_missing(opt.source, opt.results_dir) base_name",
"in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing = check_missing(opt.source,",
"import neural_best_buddies as NBBs from util import util from util import MLS vgg19",
"os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A =",
"= util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids,",
"os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing = check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source)",
"dne missing = check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def main(): import numpy as",
"file_names = [f'{base_name}_{num}.png' for num in img_nums] return img_nums, file_names def get_imgnums(root): base_name",
"B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'),",
"Exception as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as f: f.write('') if __name__",
"from algorithms import neural_best_buddies as NBBs from util import util from util import",
"as e: print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as f: f.write('') if __name__ ==",
"pidfile from options.options import Options from tqdm import tqdm opt = Options().parse() def",
"nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e) with open(os.path.join(save_dir,",
"not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing = check_missing(opt.source, opt.results_dir) base_name =",
"in img_nums] return img_nums, file_names def get_imgnums(root): base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0])",
"= NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points = nbbs.run(A, B)",
"tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne missing = check_missing(opt.source, opt.results_dir)",
"print(e) with open(os.path.join(save_dir, 'no_correspondence.txt'), 'w') as f: f.write('') if __name__ == \"__main__\": main()",
"f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num in img_nums] return img_nums, file_names",
"return dne missing = check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def main(): import numpy",
"as np from models import vgg19_model from algorithms import neural_best_buddies as NBBs from",
"def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for",
"import pidfile from options.options import Options from tqdm import tqdm opt = Options().parse()",
"NBBs from util import util from util import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums,",
"B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir, opt.k_per_level, opt.k_final, opt.fast) points =",
"= nbbs.run(A, B) mls = MLS.MLS(v_class=np.int32) mls.run_MLS_in_folder(root_folder=save_dir) except Exception as e: print(e) with",
"os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on', imgnum) source_path = os.path.join(opt.source,",
"tqdm opt = Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)])",
"img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names = [f'{base_name}_{num}.png' for num in",
"get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{num}.png' for num",
"images = get_imgs() for imgnum in tqdm(missing): print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if",
"tqdm import tqdm opt = Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f",
"import util from util import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs()",
"base_name = os.path.basename(opt.source) def main(): import numpy as np from models import vgg19_model",
"get_imgnums(root): base_name = os.path.basename(root) img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(root)]) file_names =",
"print(imgnum) save_dir = os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on', imgnum)",
"f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize) B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs =",
"continue try: print('Working on', imgnum) source_path = os.path.join(opt.source, f'{base_name}_{imgnum}.png') A = util.read_image(source_path, opt.imageSize)",
"for imgnum, file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum) return dne",
"= [] for imgnum, file_path in tqdm(get_imgnums(src_root)): if not os.path.exists(os.path.join(corr_root, str(imgnum), 'BtoA.npy')): dne.append(imgnum)",
"for num in img_nums] return img_nums, file_names def get_imgnums(root): base_name = os.path.basename(root) img_nums",
"Options from tqdm import tqdm opt = Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0])",
"check_missing(opt.source, opt.results_dir) base_name = os.path.basename(opt.source) def main(): import numpy as np from models",
"import MLS vgg19 = vgg19_model.define_Vgg19(opt) img_nums, images = get_imgs() for imgnum in tqdm(missing):",
"B = util.read_image(opt.target, opt.imageSize) print(A.shape, B.shape) nbbs = NBBs.sparse_semantic_correspondence(vgg19, opt.gpu_ids, opt.tau, opt.border_size, save_dir,",
"= os.path.join(opt.results_dir, str(imgnum)) if os.path.exists(os.path.join(save_dir, 'BtoA.npy')): continue try: print('Working on', imgnum) source_path =",
"import os from netdissect import pidfile from options.options import Options from tqdm import",
"file_names = [f'{base_name}_{num}.png' for num in img_nums] return list(zip(img_nums, file_names))[:10000] def check_missing(src_root, corr_root):",
"neural_best_buddies as NBBs from util import util from util import MLS vgg19 ="
] |
[
"= TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring",
"self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total,",
"self._total == self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool reached burst limit\", \"There",
"return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async def connection_waiter(self):",
"service=self._service_name, ): return await super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags +",
"redis connections to satisfy all users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring",
"tags=self._extra_tags + [\"method:wait\"], ) async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return",
"service=self._service_name, ): return await super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if not self.available.empty(): statsd.increment(",
"self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool no longer bursting\", f\"Number of connections has",
"tags=self._extra_tags + [\"method:new\"], ) async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return",
"enough redis connections to satisfy all users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0):",
"_ConnectionPool __all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args,",
"return connection_waiter(self) def _get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], )",
"tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn() @asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]: #",
"to {self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting = False",
"async def get_connection(self) -> AsyncIterator[Conn]: # type: ignore async with AsyncExitStack() as stack:",
"statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters,",
"@asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]: # type: ignore async with AsyncExitStack() as",
"from asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class",
"0 self._service_name = service_name self._is_bursting = False self._reported_hitting_burst_limit = False self._extra_tags = extra_tags",
"f\"{self._service_name} pool using burst capacity\", f\"Pool max size of {self.max_size} will be exceeded",
"== self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool reached burst limit\", \"There are",
") async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker() return",
"**kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name = service_name self._is_bursting = False self._reported_hitting_burst_limit",
"tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total > self.max_size: if",
"f\"Number of connections has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total ==",
"def _record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self):",
"below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total == self.burst_limit: self._reported_hitting_burst_limit = True statsd.event(",
"connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter() return connection_waiter(self) def _get_conn(self):",
"AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await",
"f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ):",
"ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name",
"value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"],",
"from ddtrace import tracer from typing import AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool",
"as stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await stack.enter_async_context(super().get_connection())",
"typing import AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",)",
"self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name} pool using burst capacity\", f\"Pool max size",
"tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool",
"with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await stack.enter_async_context(super().get_connection()) finally: self._record_connection_acquiring(-1) self._record_pressure() yield",
"f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn() @asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]:",
"are not enough redis connections to satisfy all users\", alert_type=\"error\", tags=self._extra_tags, ) def",
"class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0",
"statsd.event( f\"{self._service_name} pool no longer bursting\", f\"Number of connections has dropped below {self.max_size}\",",
"statsd.event( f\"{self._service_name} pool reached burst limit\", \"There are not enough redis connections to",
"service_name self._is_bursting = False self._reported_hitting_burst_limit = False self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics)",
"self._reported_hitting_burst_limit = False self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure()",
"tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await stack.enter_async_context(super().get_connection()) finally: self._record_connection_acquiring(-1) self._record_pressure() yield conn",
"f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await stack.enter_async_context(super().get_connection()) finally: self._record_connection_acquiring(-1) self._record_pressure() yield conn self._record_pressure()",
"def get_connection(self) -> AsyncIterator[Conn]: # type: ignore async with AsyncExitStack() as stack: self._record_connection_acquiring(1)",
"+ [\"method:available\"], ) return super()._get_conn() @asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]: # type:",
"will be exceeded temporarily, up to {self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags, )",
"{self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit",
"self._connections_acquiring = 0 self._service_name = service_name self._is_bursting = False self._reported_hitting_burst_limit = False self._extra_tags",
"or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge(",
"<gh_stars>1-10 from contextlib import asynccontextmanager, AsyncExitStack from datadog import statsd from ddtrace import",
"self._is_bursting = False self._reported_hitting_burst_limit = False self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def",
"self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags )",
"self._is_bursting = False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool no longer bursting\", f\"Number",
"f\"{self._service_name} pool reached burst limit\", \"There are not enough redis connections to satisfy",
"def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async def connection_maker(self): with tracer.trace(",
"{self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total == self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name}",
"f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async",
"f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ):",
"if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn() @asynccontextmanager async",
") def _record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def",
"AsyncIterator[Conn]: # type: ignore async with AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with tracer.trace(",
"burst capacity\", f\"Pool max size of {self.max_size} will be exceeded temporarily, up to",
"asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]):",
"service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name = service_name self._is_bursting",
"of {self.max_size} will be exceeded temporarily, up to {self.burst_limit}\", # noqa E501 alert_type=\"warning\",",
"[\"method:new\"], ) async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker()",
"f\"{self._service_name} pool no longer bursting\", f\"Number of connections has dropped below {self.max_size}\", alert_type=\"success\",",
"statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], )",
"no longer bursting\", f\"Number of connections has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, )",
"return await super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], )",
"connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async def connection_waiter(self): with",
"self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags,",
"False self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60,",
"of connections has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total == self.burst_limit:",
"= False self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally:",
") async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter() return",
"self.max_size: if not self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name} pool using burst capacity\",",
"with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment(",
"{self.max_size} will be exceeded temporarily, up to {self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags,",
"import AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn",
"[] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\",",
"alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags,",
"self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async def",
"True statsd.event( f\"{self._service_name} pool using burst capacity\", f\"Pool max size of {self.max_size} will",
"ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self,",
"(\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args,",
"datadog import statsd from ddtrace import tracer from typing import AsyncIterator, TypeVar from",
"from datadog import statsd from ddtrace import tracer from typing import AsyncIterator, TypeVar",
"statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total > self.max_size: if not self._is_bursting:",
"self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn() @asynccontextmanager async def get_connection(self)",
"self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags",
"**kwargs) self._connections_acquiring = 0 self._service_name = service_name self._is_bursting = False self._reported_hitting_burst_limit = False",
"return await super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags",
"-> AsyncIterator[Conn]: # type: ignore async with AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with",
"type: ignore async with AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name,",
") self._record_connection_acquiring() if self._total > self.max_size: if not self._is_bursting: self._is_bursting = True statsd.event(",
"_record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\",",
") statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if",
"self._is_bursting = True statsd.event( f\"{self._service_name} pool using burst capacity\", f\"Pool max size of",
"if self._total == self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool reached burst limit\",",
"await super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags +",
"noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit = False",
"tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge(",
"asynccontextmanager, AsyncExitStack from datadog import statsd from ddtrace import tracer from typing import",
"): return await super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"],",
"not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn() @asynccontextmanager async def",
"users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring,",
"TypeVar from asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\")",
"__init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name = service_name",
"Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs)",
"burst limit\", \"There are not enough redis connections to satisfy all users\", alert_type=\"error\",",
"self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\",",
"AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn =",
"self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool no longer bursting\",",
"super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async def",
"= False self._reported_hitting_burst_limit = False self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self):",
"_connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\",",
"ignore async with AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ):",
"def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker() return connection_maker(self) def",
"tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\",",
"if self._total > self.max_size: if not self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name} pool",
"def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async def connection_waiter(self): with tracer.trace(",
"statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total",
"TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring =",
"from contextlib import asynccontextmanager, AsyncExitStack from datadog import statsd from ddtrace import tracer",
"not enough redis connections to satisfy all users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self,",
"async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker() return connection_maker(self)",
"+= value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags +",
"= (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None, **kwargs):",
"False statsd.event( f\"{self._service_name} pool no longer bursting\", f\"Number of connections has dropped below",
"with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if",
"tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, )",
"super()._get_conn() @asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]: # type: ignore async with AsyncExitStack()",
"be exceeded temporarily, up to {self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif",
"import statsd from ddtrace import tracer from typing import AsyncIterator, TypeVar from asyncio_connection_pool",
"bursting\", f\"Number of connections has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total",
"statsd.event( f\"{self._service_name} pool using burst capacity\", f\"Pool max size of {self.max_size} will be",
"def _get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn()",
"await super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async",
"dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total == self.burst_limit: self._reported_hitting_burst_limit = True",
"> self.max_size: if not self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name} pool using burst",
"def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter() return connection_waiter(self) def",
"ddtrace import tracer from typing import AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool as",
"connections to satisfy all users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring +=",
"stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await stack.enter_async_context(super().get_connection()) finally:",
"as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name,",
"def __init__(self, service_name, *args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name =",
"f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total > self.max_size: if not self._is_bursting: self._is_bursting",
"not self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name} pool using burst capacity\", f\"Pool max",
"= True statsd.event( f\"{self._service_name} pool using burst capacity\", f\"Pool max size of {self.max_size}",
"extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self):",
"super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name = service_name self._is_bursting = False self._reported_hitting_burst_limit =",
"f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags,",
"contextlib import asynccontextmanager, AsyncExitStack from datadog import statsd from ddtrace import tracer from",
"self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, )",
"capacity\", f\"Pool max size of {self.max_size} will be exceeded temporarily, up to {self.burst_limit}\",",
"max size of {self.max_size} will be exceeded temporarily, up to {self.burst_limit}\", # noqa",
"# type: ignore async with AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\",",
"tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async def connection_maker(self):",
"up to {self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting =",
"_record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment(",
"using burst capacity\", f\"Pool max size of {self.max_size} will be exceeded temporarily, up",
"exceeded temporarily, up to {self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting:",
") if self._total == self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool reached burst",
"statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn() @asynccontextmanager async def get_connection(self) ->",
"pool using burst capacity\", f\"Pool max size of {self.max_size} will be exceeded temporarily,",
"False self._reported_hitting_burst_limit = False self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try:",
"f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total >",
"connections has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total == self.burst_limit: self._reported_hitting_burst_limit",
"try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await stack.enter_async_context(super().get_connection()) finally: self._record_connection_acquiring(-1) self._record_pressure()",
"AsyncExitStack from datadog import statsd from ddtrace import tracer from typing import AsyncIterator,",
"to satisfy all users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring += value",
"import asynccontextmanager, AsyncExitStack from datadog import statsd from ddtrace import tracer from typing",
"self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total > self.max_size:",
"all users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\",",
"connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker() return connection_maker(self) def _connection_waiter(self):",
") def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async def connection_maker(self): with",
"with AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn =",
") elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool no",
"self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, )",
"= False statsd.event( f\"{self._service_name} pool no longer bursting\", f\"Number of connections has dropped",
"_get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return super()._get_conn() @asynccontextmanager",
"True statsd.event( f\"{self._service_name} pool reached burst limit\", \"There are not enough redis connections",
"if not self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name} pool using burst capacity\", f\"Pool",
"= extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def",
"statsd from ddtrace import tracer from typing import AsyncIterator, TypeVar from asyncio_connection_pool import",
"self._extra_tags = extra_tags or [] self._loop.call_soon(self._periodically_send_metrics) def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics)",
"tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if not",
"False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool no longer bursting\", f\"Number of connections",
"f\"Pool max size of {self.max_size} will be exceeded temporarily, up to {self.burst_limit}\", #",
"statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use,",
"get_connection(self) -> AsyncIterator[Conn]: # type: ignore async with AsyncExitStack() as stack: self._record_connection_acquiring(1) try:",
"_connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\",",
"from typing import AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__ =",
"self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool reached burst limit\", \"There are not enough",
"temporarily, up to {self.burst_limit}\", # noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting",
"def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge(",
"tags=self._extra_tags, ) self._record_connection_acquiring() if self._total > self.max_size: if not self._is_bursting: self._is_bursting = True",
"elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool no longer",
"self._total > self.max_size: if not self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name} pool using",
"E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit = False statsd.event(",
"extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name = service_name self._is_bursting = False",
"= 0 self._service_name = service_name self._is_bursting = False self._reported_hitting_burst_limit = False self._extra_tags =",
"self._service_name = service_name self._is_bursting = False self._reported_hitting_burst_limit = False self._extra_tags = extra_tags or",
"pool no longer bursting\", f\"Number of connections has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags,",
") statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\",",
"limit\", \"There are not enough redis connections to satisfy all users\", alert_type=\"error\", tags=self._extra_tags,",
"super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"],",
"= service_name self._is_bursting = False self._reported_hitting_burst_limit = False self._extra_tags = extra_tags or []",
"# noqa E501 alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit =",
"return super()._get_conn() @asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]: # type: ignore async with",
"value=0): self._connections_acquiring += value statsd.gauge( f\"{self._service_name}.pool.connections_acquiring\", self._connections_acquiring, tags=self._extra_tags, ) def _connection_maker(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\",",
"alert_type=\"success\", tags=self._extra_tags, ) if self._total == self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool",
"try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge(",
"finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(),",
"statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:new\"], ) async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name,",
"self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total > self.max_size: if not self._is_bursting: self._is_bursting =",
"satisfy all users\", alert_type=\"error\", tags=self._extra_tags, ) def _record_connection_acquiring(self, value=0): self._connections_acquiring += value statsd.gauge(",
"size of {self.max_size} will be exceeded temporarily, up to {self.burst_limit}\", # noqa E501",
"[\"method:wait\"], ) async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter()",
"f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if not self.available.empty():",
"longer bursting\", f\"Number of connections has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if",
"import tracer from typing import AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool as _ConnectionPool",
") statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring() if self._total > self.max_size: if not",
"__all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def __init__(self, service_name, *args, extra_tags=None,",
"pool reached burst limit\", \"There are not enough redis connections to satisfy all",
"def _periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags,",
"tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags ) statsd.gauge( f\"{self._service_name}.pool.connections_used\", self.in_use, tags=self._extra_tags, ) self._record_connection_acquiring()",
"+ [\"method:new\"], ) async def connection_maker(self): with tracer.trace( f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await",
"f\"{self._service_name}.pool._create_new_connection\", service=self._service_name, ): return await super()._connection_maker() return connection_maker(self) def _connection_waiter(self): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags",
"self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn = await stack.enter_async_context(super().get_connection()) finally: self._record_connection_acquiring(-1)",
"tracer from typing import AsyncIterator, TypeVar from asyncio_connection_pool import ConnectionPool as _ConnectionPool __all__",
"_periodically_send_metrics(self): try: self._record_pressure() finally: self._loop.call_later(60, self._periodically_send_metrics) def _record_pressure(self): statsd.gauge( f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, )",
"tags=self._extra_tags, ) if self._total == self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool reached",
"async with AsyncExitStack() as stack: self._record_connection_acquiring(1) try: with tracer.trace( f\"{self._service_name}.pool.acquire_connection\", service=self._service_name, ): conn",
"reached burst limit\", \"There are not enough redis connections to satisfy all users\",",
"): return await super()._connection_waiter() return connection_waiter(self) def _get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\",",
"import ConnectionPool as _ConnectionPool __all__ = (\"ConnectionPool\",) Conn = TypeVar(\"Conn\") class ConnectionPool(_ConnectionPool[Conn]): def",
"f\"{self._service_name}.pool.total_connections\", self._total, tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.available_connections\", self.available.qsize(), tags=self._extra_tags, ) statsd.gauge( f\"{self._service_name}.pool.waiting\", self._waiters, tags=self._extra_tags",
"connection_waiter(self) def _get_conn(self): if not self.available.empty(): statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:available\"], ) return",
") return super()._get_conn() @asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]: # type: ignore async",
"= False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name} pool no longer bursting\", f\"Number of",
"statsd.increment( f\"{self._service_name}.pool.getting_connection\", tags=self._extra_tags + [\"method:wait\"], ) async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name,",
"self._record_connection_acquiring() if self._total > self.max_size: if not self._is_bursting: self._is_bursting = True statsd.event( f\"{self._service_name}",
"*args, extra_tags=None, **kwargs): super().__init__(*args, **kwargs) self._connections_acquiring = 0 self._service_name = service_name self._is_bursting =",
"+ [\"method:wait\"], ) async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await",
"= True statsd.event( f\"{self._service_name} pool reached burst limit\", \"There are not enough redis",
"self.burst_limit: self._reported_hitting_burst_limit = True statsd.event( f\"{self._service_name} pool reached burst limit\", \"There are not",
"\"There are not enough redis connections to satisfy all users\", alert_type=\"error\", tags=self._extra_tags, )",
"async def connection_waiter(self): with tracer.trace( f\"{self._service_name}.pool._wait_for_connection\", service=self._service_name, ): return await super()._connection_waiter() return connection_waiter(self)",
"[\"method:available\"], ) return super()._get_conn() @asynccontextmanager async def get_connection(self) -> AsyncIterator[Conn]: # type: ignore",
"has dropped below {self.max_size}\", alert_type=\"success\", tags=self._extra_tags, ) if self._total == self.burst_limit: self._reported_hitting_burst_limit =",
"alert_type=\"warning\", tags=self._extra_tags, ) elif self._is_bursting: self._is_bursting = False self._reported_hitting_burst_limit = False statsd.event( f\"{self._service_name}"
] |
[
"on the map (usually works better by over-estimating the number of colors)\", required=True",
"json import numpy as np import cv2 def display_img(img, title=\"\", big=False) : if",
"display_img(img, title=\"\", big=False) : if big : plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')",
"= preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered =",
"ex : \"(20, 30, 200, 400) , (0, 0, 100, 100)\"') parser.add_argument( \"--colors\",",
"image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered",
"# with open('/tmp/shape_'+str(i)+'.json', 'w') as f : # dict_shape = shape.to_dict() # json_rep",
"# img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR with Tesseract ...') ocr_results",
"plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup",
"results..') for group in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img,",
"group))) print('Done') def disp_ocr_results(img, ocr_results) : todisp = img.copy() disp_color = (int(np.max(img)) ,",
"args = get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored",
"help=\"The estimated number of color on the map (usually works better by over-estimating",
"plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup in",
"'w') as f : # dict_shape = shape.to_dict() # json_rep = json.dumps(dict_shape) #",
": # dict_shape = shape.to_dict() # json_rep = json.dumps(dict_shape) # f.write(json_rep) # for",
"maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX,",
"ocr_results) : todisp = img.copy() disp_color = (int(np.max(img)) , 0, 0) for i,",
"type=int, dest=\"nb_colors\", help=\"The estimated number of color on the map (usually works better",
"in range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r') as f : # jsonrep =",
"# f.write(json_rep) # for i in range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r') as",
"'r') as f : # jsonrep = f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) #",
"[geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup in eval(box_string)] def get_args() : parser =",
"disp_ocr_results(img, ocr_results) : todisp = img.copy() disp_color = (int(np.max(img)) , 0, 0) for",
"cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup in eval(box_string)]",
"dest=\"input_file\", help=\"Path of the map to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list",
"= preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i,",
"img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR with Tesseract ...') ocr_results =",
", 0, 0) for i, row in ocr_results.iterrows(): (minx, miny, maxx, maxy) =",
"def main() : args = get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes",
"tup[1], tup[2], tup[3]) for tup in eval(box_string)] def get_args() : parser = argparse.ArgumentParser(description='Parse",
"(usually works better by over-estimating the number of colors)\", required=True ) return parser.parse_args()",
"100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number of color on the map",
"= get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored areas...')",
": # with open('/tmp/shape_'+str(i)+'.json', 'w') as f : # dict_shape = shape.to_dict() #",
"type=str, dest=\"ignored_boxes\", help='A list of comma separated rectangle (minx, miny, maxx, maxy), ex",
"...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..') for group in polygon_groups: pg_group_named =",
"for i, shape in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w') as f :",
"cv2 def display_img(img, title=\"\", big=False) : if big : plt.figure(figsize=(18, 16), dpi= 80,",
"a map to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the map to",
"of color on the map (usually works better by over-estimating the number of",
"map_extractor import preprocessing, shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup import PolygonGroup import json",
"polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i, shape in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json',",
"to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the map to parse\", required=True)",
"dest=\"ignored_boxes\", help='A list of comma separated rectangle (minx, miny, maxx, maxy), ex :",
"# for i in range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r') as f :",
"= shape_extraction.extract_shapes(image_clustered) # for i, shape in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w')",
"tup[2], tup[3]) for tup in eval(box_string)] def get_args() : parser = argparse.ArgumentParser(description='Parse a",
"colors)\", required=True ) return parser.parse_args() def main() : args = get_args() print('Loading image...')",
"in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w') as f : # dict_shape =",
"as f : # jsonrep = f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a)",
"numpy as np import cv2 def display_img(img, title=\"\", big=False) : if big :",
"estimated number of color on the map (usually works better by over-estimating the",
"= skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i, shape in enumerate(shapes) : #",
"skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i, shape in enumerate(shapes) : # with",
"import preprocessing, shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup import PolygonGroup import json import",
"argparse import matplotlib.pyplot as plt from shapely import geometry from map_extractor import preprocessing,",
"# dict_shape = shape.to_dict() # json_rep = json.dumps(dict_shape) # f.write(json_rep) # for i",
"works better by over-estimating the number of colors)\", required=True ) return parser.parse_args() def",
"parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of comma separated rectangle (minx, miny,",
"shape.to_dict() # json_rep = json.dumps(dict_shape) # f.write(json_rep) # for i in range(16) :",
": plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string):",
"map (usually works better by over-estimating the number of colors)\", required=True ) return",
"# jsonrep = f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img =",
"with open('/tmp/shape_'+str(i)+'.json', 'r') as f : # jsonrep = f.read() # a =",
"by over-estimating the number of colors)\", required=True ) return parser.parse_args() def main() :",
"parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups",
"parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number of color on the map (usually",
"for i, row in ocr_results.iterrows(): (minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx,",
", (0, 0, 100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number of",
"parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of comma separated rectangle (minx, miny, maxx, maxy),",
"0) for i, row in ocr_results.iterrows(): (minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp,",
"as f : # dict_shape = shape.to_dict() # json_rep = json.dumps(dict_shape) # f.write(json_rep)",
") return parser.parse_args() def main() : args = get_args() print('Loading image...') image =",
"def disp_ocr_results(img, ocr_results) : todisp = img.copy() disp_color = (int(np.max(img)) , 0, 0)",
"geometry from map_extractor import preprocessing, shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup import PolygonGroup",
"<filename>parse_map.py import argparse import matplotlib.pyplot as plt from shapely import geometry from map_extractor",
"parser = argparse.ArgumentParser(description='Parse a map to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of",
"\"(20, 30, 200, 400) , (0, 0, 100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\",",
"help=\"Path of the map to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of",
": \"(20, 30, 200, 400) , (0, 0, 100, 100)\"') parser.add_argument( \"--colors\", type=int,",
"of comma separated rectangle (minx, miny, maxx, maxy), ex : \"(20, 30, 200,",
"image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes))",
"miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '',",
"= [] print('Performing OCR with Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..')",
"ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..') for group in polygon_groups: pg_group_named = np.concatenate((pg_group_named,",
"image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image,",
"country_naming import skimage.color from map_extractor.PolygonGroup import PolygonGroup import json import numpy as np",
"# json_rep = json.dumps(dict_shape) # f.write(json_rep) # for i in range(16) : #",
"eval(box_string)] def get_args() : parser = argparse.ArgumentParser(description='Parse a map to labelled svgs') parser.add_argument(\"--input\",",
"(minx, miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp,",
"matplotlib.pyplot as plt from shapely import geometry from map_extractor import preprocessing, shape_extraction, country_naming",
"i, shape in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w') as f : #",
"for tup in eval(box_string)] def get_args() : parser = argparse.ArgumentParser(description='Parse a map to",
"separated rectangle (minx, miny, maxx, maxy), ex : \"(20, 30, 200, 400) ,",
": # with open('/tmp/shape_'+str(i)+'.json', 'r') as f : # jsonrep = f.read() #",
"cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '', True) if __name__ == \"__main__\" : main()",
"ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors)",
"import argparse import matplotlib.pyplot as plt from shapely import geometry from map_extractor import",
"(int(np.max(img)) , 0, 0) for i, row in ocr_results.iterrows(): (minx, miny, maxx, maxy)",
"\"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number of color on the map (usually works",
", 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '', True) if __name__",
"image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i, shape in enumerate(shapes) :",
"as plt from shapely import geometry from map_extractor import preprocessing, shape_extraction, country_naming import",
"color on the map (usually works better by over-estimating the number of colors)\",",
"main() : args = get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes :",
"parser.parse_args() def main() : args = get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if",
"= np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1,",
"print('Performing OCR with Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..') for group",
"cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '', True) if __name__ == \"__main__\"",
"the map to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of comma separated",
"in eval(box_string)] def get_args() : parser = argparse.ArgumentParser(description='Parse a map to labelled svgs')",
"print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image,",
"required=True ) return parser.parse_args() def main() : args = get_args() print('Loading image...') image",
"image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for",
"json.dumps(dict_shape) # f.write(json_rep) # for i in range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r')",
"OCR results..') for group in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def",
"i, row in ocr_results.iterrows(): (minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny),",
"cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2)",
"args.ignored_boxes : print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered",
"maxx, maxy), ex : \"(20, 30, 200, 400) , (0, 0, 100, 100)\"')",
"areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) #",
"f.write(json_rep) # for i in range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r') as f",
"list of comma separated rectangle (minx, miny, maxx, maxy), ex : \"(20, 30,",
"for i in range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r') as f : #",
"print('Extracting OCR results..') for group in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done')",
"as np import cv2 def display_img(img, title=\"\", big=False) : if big : plt.figure(figsize=(18,",
"shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup import PolygonGroup import json import numpy as",
"preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i, shape",
"country_naming.apply_tesseract(image) print('Extracting OCR results..') for group in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group)))",
"img.copy() disp_color = (int(np.max(img)) , 0, 0) for i, row in ocr_results.iterrows(): (minx,",
": parser = argparse.ArgumentParser(description='Parse a map to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path",
"if big : plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show()",
"number of colors)\", required=True ) return parser.parse_args() def main() : args = get_args()",
"polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR with Tesseract ...')",
"maxy), ex : \"(20, 30, 200, 400) , (0, 0, 100, 100)\"') parser.add_argument(",
": args = get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing",
"PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR with",
"= (int(np.max(img)) , 0, 0) for i, row in ocr_results.iterrows(): (minx, miny, maxx,",
"parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the map to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\",",
"facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3])",
"to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of comma separated rectangle (minx,",
"import matplotlib.pyplot as plt from shapely import geometry from map_extractor import preprocessing, shape_extraction,",
"big : plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def",
"argparse.ArgumentParser(description='Parse a map to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the map",
"map to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of comma separated rectangle",
"import PolygonGroup import json import numpy as np import cv2 def display_img(img, title=\"\",",
"skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR with Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting",
"import json import numpy as np import cv2 def display_img(img, title=\"\", big=False) :",
"80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2],",
"svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the map to parse\", required=True) parser.add_argument(\"--ignore\", type=str,",
"required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of comma separated rectangle (minx, miny, maxx,",
"16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0],",
"preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png'))",
"parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup in eval(box_string)] def get_args() :",
"of colors)\", required=True ) return parser.parse_args() def main() : args = get_args() print('Loading",
"country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results) : todisp = img.copy() disp_color = (int(np.max(img))",
"help='A list of comma separated rectangle (minx, miny, maxx, maxy), ex : \"(20,",
"from map_extractor import preprocessing, shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup import PolygonGroup import",
"jsonrep = f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png'))",
"row in ocr_results.iterrows(): (minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx,",
"import geometry from map_extractor import preprocessing, shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup import",
"dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1],",
"= shape.to_dict() # json_rep = json.dumps(dict_shape) # f.write(json_rep) # for i in range(16)",
"miny, maxx, maxy), ex : \"(20, 30, 200, 400) , (0, 0, 100,",
"skimage.color from map_extractor.PolygonGroup import PolygonGroup import json import numpy as np import cv2",
"print('Clustering image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups =",
"the number of colors)\", required=True ) return parser.parse_args() def main() : args =",
"tup[3]) for tup in eval(box_string)] def get_args() : parser = argparse.ArgumentParser(description='Parse a map",
"(minx, miny, maxx, maxy), ex : \"(20, 30, 200, 400) , (0, 0,",
"shape in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w') as f : # dict_shape",
"i in range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r') as f : # jsonrep",
"disp_color = (int(np.max(img)) , 0, 0) for i, row in ocr_results.iterrows(): (minx, miny,",
"import skimage.color from map_extractor.PolygonGroup import PolygonGroup import json import numpy as np import",
"print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored areas...') image =",
"skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image",
"# image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i, shape in enumerate(shapes)",
"tup in eval(box_string)] def get_args() : parser = argparse.ArgumentParser(description='Parse a map to labelled",
"number of color on the map (usually works better by over-estimating the number",
"better by over-estimating the number of colors)\", required=True ) return parser.parse_args() def main()",
"get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored areas...') image",
"miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'],",
"over-estimating the number of colors)\", required=True ) return parser.parse_args() def main() : args",
"for group in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results)",
"np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color,",
"ocr_results.iterrows(): (minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color ,",
"# for i, shape in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w') as f",
"(0, 0, 100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number of color",
"dict_shape = shape.to_dict() # json_rep = json.dumps(dict_shape) # f.write(json_rep) # for i in",
"= f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named",
"print('Done') def disp_ocr_results(img, ocr_results) : todisp = img.copy() disp_color = (int(np.max(img)) , 0,",
": todisp = img.copy() disp_color = (int(np.max(img)) , 0, 0) for i, row",
"type=str, dest=\"input_file\", help=\"Path of the map to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A",
": if big : plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray')",
"= img.copy() disp_color = (int(np.max(img)) , 0, 0) for i, row in ocr_results.iterrows():",
"np import cv2 def display_img(img, title=\"\", big=False) : if big : plt.figure(figsize=(18, 16),",
"big=False) : if big : plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img,",
"= country_naming.apply_tesseract(image) print('Extracting OCR results..') for group in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results,",
"enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w') as f : # dict_shape = shape.to_dict()",
"30, 200, 400) , (0, 0, 100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The",
"# a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = []",
"0, 100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number of color on",
"pg_group_named = [] print('Performing OCR with Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR",
"OCR with Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..') for group in",
"return parser.parse_args() def main() : args = get_args() print('Loading image...') image = skimage.color.rgba2rgb(plt.imread(args.input_file))",
"in ocr_results.iterrows(): (minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color",
"= json.dumps(dict_shape) # f.write(json_rep) # for i in range(16) : # with open('/tmp/shape_'+str(i)+'.json',",
"def display_img(img, title=\"\", big=False) : if big : plt.figure(figsize=(18, 16), dpi= 80, facecolor='w',",
"json_rep = json.dumps(dict_shape) # f.write(json_rep) # for i in range(16) : # with",
"np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results) : todisp = img.copy() disp_color =",
"todisp = img.copy() disp_color = (int(np.max(img)) , 0, 0) for i, row in",
"= argparse.ArgumentParser(description='Parse a map to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the",
"with open('/tmp/shape_'+str(i)+'.json', 'w') as f : # dict_shape = shape.to_dict() # json_rep =",
"map to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the map to parse\",",
"image colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered)",
"plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup in eval(box_string)] def",
"[] print('Performing OCR with Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..') for",
"maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy),",
"import numpy as np import cv2 def display_img(img, title=\"\", big=False) : if big",
"from map_extractor.PolygonGroup import PolygonGroup import json import numpy as np import cv2 def",
"import cv2 def display_img(img, title=\"\", big=False) : if big : plt.figure(figsize=(18, 16), dpi=",
"100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number of color on the",
"open('/tmp/shape_'+str(i)+'.json', 'w') as f : # dict_shape = shape.to_dict() # json_rep = json.dumps(dict_shape)",
"open('/tmp/shape_'+str(i)+'.json', 'r') as f : # jsonrep = f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep))",
"= skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR with Tesseract ...') ocr_results = country_naming.apply_tesseract(image)",
"Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..') for group in polygon_groups: pg_group_named",
"= np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results) : todisp = img.copy() disp_color",
"PolygonGroup import json import numpy as np import cv2 def display_img(img, title=\"\", big=False)",
"if args.ignored_boxes : print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..')",
"f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named =",
"the map (usually works better by over-estimating the number of colors)\", required=True )",
"(maxx, maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '', True)",
"of the map to parse\", required=True) parser.add_argument(\"--ignore\", type=str, dest=\"ignored_boxes\", help='A list of comma",
"def get_args() : parser = argparse.ArgumentParser(description='Parse a map to labelled svgs') parser.add_argument(\"--input\", type=str,",
"preprocessing, shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup import PolygonGroup import json import numpy",
"plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return",
"return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup in eval(box_string)] def get_args() : parser",
"f : # jsonrep = f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) #",
"in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results) : todisp",
"range(16) : # with open('/tmp/shape_'+str(i)+'.json', 'r') as f : # jsonrep = f.read()",
"# with open('/tmp/shape_'+str(i)+'.json', 'r') as f : # jsonrep = f.read() # a",
"labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\", help=\"Path of the map to parse\", required=True) parser.add_argument(\"--ignore\",",
"plt from shapely import geometry from map_extractor import preprocessing, shape_extraction, country_naming import skimage.color",
": # jsonrep = f.read() # a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img",
"get_args() : parser = argparse.ArgumentParser(description='Parse a map to labelled svgs') parser.add_argument(\"--input\", type=str, dest=\"input_file\",",
"f : # dict_shape = shape.to_dict() # json_rep = json.dumps(dict_shape) # f.write(json_rep) #",
"# polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR with Tesseract",
"pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results) : todisp = img.copy()",
"def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for tup in eval(box_string)] def get_args()",
"= PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing OCR",
"a = PolygonGroup.from_dict(json.loads(jsonrep)) # polygon_groups.append(a) # img = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/europe_cleaned.png')) pg_group_named = [] print('Performing",
"with Tesseract ...') ocr_results = country_naming.apply_tesseract(image) print('Extracting OCR results..') for group in polygon_groups:",
"edgecolor='k') plt.title(title) plt.imshow(img, cmap='gray') plt.show() def parse_ignored_boxes(box_string): return [geometry.box(tup[0], tup[1], tup[2], tup[3]) for",
"polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results) : todisp =",
"shape_extraction.extract_shapes(image_clustered) # for i, shape in enumerate(shapes) : # with open('/tmp/shape_'+str(i)+'.json', 'w') as",
"400) , (0, 0, 100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated number",
": print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering image colors..') image_clustered =",
"comma separated rectangle (minx, miny, maxx, maxy), ex : \"(20, 30, 200, 400)",
"group in polygon_groups: pg_group_named = np.concatenate((pg_group_named, country_naming.label_polygon_group(ocr_results, group))) print('Done') def disp_ocr_results(img, ocr_results) :",
"0, 0) for i, row in ocr_results.iterrows(): (minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int)",
"colors..') image_clustered = preprocessing.regroup_image_colors(image, args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) #",
"maxy),disp_color , 2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '', True) if",
"2) cv2.putText(todisp,row['text'], (maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '', True) if __name__ ==",
"rectangle (minx, miny, maxx, maxy), ex : \"(20, 30, 200, 400) , (0,",
"dest=\"nb_colors\", help=\"The estimated number of color on the map (usually works better by",
"(minx, miny, maxx, maxy) = np.array(row['bbox'].bounds).astype(int) cv2.rectangle(todisp, (minx, miny), (maxx, maxy),disp_color , 2)",
"from shapely import geometry from map_extractor import preprocessing, shape_extraction, country_naming import skimage.color from",
"args.nb_colors) # image_clustered = skimage.color.rgba2rgb(plt.imread('notebooks/tmp/clustered_europe.png')) polygon_groups = shape_extraction.extract_shapes(image_clustered) # for i, shape in",
"map_extractor.PolygonGroup import PolygonGroup import json import numpy as np import cv2 def display_img(img,",
"= skimage.color.rgba2rgb(plt.imread(args.input_file)) if args.ignored_boxes : print('Removing ignored areas...') image = preprocessing.remove_ignored_areas(image, parse_ignored_boxes(args.ignored_boxes)) print('Clustering",
"200, 400) , (0, 0, 100, 100)\"') parser.add_argument( \"--colors\", type=int, dest=\"nb_colors\", help=\"The estimated",
"(maxx+3,maxy), cv2.FONT_HERSHEY_SIMPLEX, 1, disp_color, 2) display_img(todisp, '', True) if __name__ == \"__main__\" :",
"title=\"\", big=False) : if big : plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k') plt.title(title)",
"shapely import geometry from map_extractor import preprocessing, shape_extraction, country_naming import skimage.color from map_extractor.PolygonGroup"
] |
[
"be in all CAPS.\" elif field == \"id\": if not value == \"<AUTO_INCREMENT>\":",
"assemblyline.al.common import log as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser()",
"validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if",
"\"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] =",
"% rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation (%s)\" % res['message']['error'])) return failed_list def",
"the following schema: ORG_000000\" return True, \"\" def check_for_id_conflicts(self, rid, rev): if rid",
"if not value == \"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\") if len(num) !=",
"find matching rule to increment revision number.\")) continue key = \"%sr.%s\" % (rule['meta']['id'],",
"if name_lookup['total'] > 0: return True if name in self._name_cache: return True return",
"= logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore() self.yp = yara_parser_class() self.log",
"YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None):",
"if not value: return False, \"%s cannot be empty.\" % field elif field",
"field == \"yara_version\": if value not in self.yp.VALID_YARA_VERSION: return False, \"yara_version should be",
"try: org, num = value.split(\"_\") if len(num) != 6: error = True elif",
"rule['meta']['organisation']: error = True else: int(num) error = False except: error = True",
"== \"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\") if len(num) != 6: error =",
"raise Exception(\"File '%s' does not exists.\") def parse_files(self, files, force_safe_str=False): output = {}",
"from assemblyline.al.common import log as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class =",
"= \"%sr.%s\" % (rid, rev) id_lookup = self.ds.get_signature(key) if id_lookup: return True return",
"not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'], \"Could not find matching",
"\"rule_group\": if value not in self.yp.RULE_GROUPS: return False, \"rule_group should be one of",
"following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if value != value.upper():",
"<reponame>dendisuhubdy/grokmachine import os import logging from assemblyline.common import isotime from assemblyline.al.common import forge",
"= yara_parser_class() self.log = logger self._id_cache = {} self._name_cache = [] def _get_next_id(self,",
"def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list = [] for",
"% \", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try: int(value) except: return False, \"rule_version",
"following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try: int(value) except: return",
"\"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'],",
"return failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self, field,",
"not logger: from assemblyline.al.common import log as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO)",
"!= rule['meta']['organisation']: error = True else: int(num) error = False except: error =",
"if name in self._name_cache: return True return False finally: self._name_cache.append(name) def parse_data(self, yara_bin,",
"force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file: yara_bin =",
"= \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by']",
"= self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True),",
"int(value) except: return False, \"rule_version should be a simple integer value\" elif field",
"REQUIRED_META = ['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None): if",
"forge class YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def",
"def check_for_id_conflicts(self, rid, rev): if rid is None or rev is None: return",
"files, force_safe_str=False): output = {} for cur_file in files: try: output[cur_file] = self.parse_file(cur_file,",
"\"rule_group should be one of the following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif field",
"item not in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict =",
"in parsed_rules: missing_meta = [] for item in self.REQUIRED_META: if item not in",
"should be in all CAPS.\" elif field == \"id\": if not value ==",
"int(num) error = False except: error = True if error: return False, \"id",
"self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list = [] for rule in rules: validation_error",
"= self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total'] > 0: return True if name",
"force_safe_str=False): output = [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta",
"missing_meta = [] for item in self.REQUIRED_META: if item not in rule['meta']: missing_meta.append(item)",
"translate_rule(self, rule): return rule def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules):",
"rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously failed rule validation (%s)\" % validation_error)) continue",
"except: return False, \"rule_version should be a simple integer value\" elif field ==",
"return True return False def check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name,",
"signature %s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation (%s)\" % res['message']['error'])) return",
"if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is",
"validation_error = rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously failed rule validation (%s)\" %",
"id_conflict, \"name_conflict\": name_conflict}) return output def parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if",
"should be one of the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field ==",
"\"rb\") as yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s'",
"for rule in rules: validation_error = rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously failed",
"return rule def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules,",
"'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None): if not logger: from",
"> 0: return True if name in self._name_cache: return True return False finally:",
"return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does not exists.\") def parse_files(self, files,",
"self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does not exists.\") def parse_files(self, files, force_safe_str=False):",
"org != rule['meta']['organisation']: error = True else: int(num) error = False except: error",
"cur_file in files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except Exception, e: output[cur_file] =",
"self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self, rule): return rule",
"org, num = value.split(\"_\") if len(num) != 6: error = True elif org",
"rule def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True)",
"name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return",
"elif field == \"id\": if not value == \"<AUTO_INCREMENT>\": try: org, num =",
"return False, \"%s cannot be empty.\" % field elif field == \"name\": if",
"failed_list.append((rule['name'], \"Previously failed rule validation (%s)\" % validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\":",
"% name, rows=0) if name_lookup['total'] > 0: return True if name in self._name_cache:",
"rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation (%s)\" % res['message']['error'])) return failed_list def validate_rule(self,",
"True elif org != rule['meta']['organisation']: error = True else: int(num) error = False",
"org): if org in self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) +",
"= self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self, rule): return",
"'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None): if not logger: from assemblyline.al.common import log",
"value not in self.yp.VALID_YARA_VERSION: return False, \"yara_version should be one of the following:",
"= rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously failed rule validation (%s)\" % validation_error))",
"id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta,",
"del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not None and",
"value not in self.yp.RULE_GROUPS: return False, \"rule_group should be one of the following:",
"if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id,",
"None)) res = self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added",
"be a simple integer value\" elif field == \"rule_group\": if value not in",
"else: raise Exception(\"File '%s' does not exists.\") def parse_files(self, files, force_safe_str=False): output =",
"reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output def parse_file(self, cur_file, force_safe_str=False): cur_file =",
"def parse_files(self, files, force_safe_str=False): output = {} for cur_file in files: try: output[cur_file]",
"value, rule): if not value: return False, \"%s cannot be empty.\" % field",
"return False, \"rule_version should be a simple integer value\" elif field == \"rule_group\":",
"if rid is None or rev is None: return False key = \"%sr.%s\"",
"value.split(\"_\") if len(num) != 6: error = True elif org != rule['meta']['organisation']: error",
"noinspection PyBroadException def validate(self, field, value, rule): if not value: return False, \"%s",
"return False key = \"%sr.%s\" % (rid, rev) id_lookup = self.ds.get_signature(key) if id_lookup:",
"one of the following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if",
"= isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res =",
"= {} self._name_cache = [] def _get_next_id(self, org): if org in self._id_cache: self._id_cache[org]",
"display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self,",
"rule) self.log.info(\"Added signature %s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation (%s)\" %",
"if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] ==",
"integer value\" elif field == \"rule_group\": if value not in self.yp.RULE_GROUPS: return False,",
"if id_lookup: return True return False def check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\"",
"field elif field == \"name\": if \" \" in value: return False, \"There",
"in self._name_cache: return True return False finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output",
"al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore() self.yp =",
"\" in value: return False, \"There should be no space in the name.\"",
"check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total'] > 0:",
"self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output def",
"validation (%s)\" % res['message']['error'])) return failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection",
"field == \"organisation\": if value != value.upper(): return False, \"organisation should be in",
"rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'], \"Could not find matching rule to increment",
"force_safe_str=False): output = {} for cur_file in files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str)",
"{} self._name_cache = [] def _get_next_id(self, org): if org in self._id_cache: self._id_cache[org] +=",
"rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'], \"Could not find matching rule to",
"= self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output",
"log as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds =",
"= [] for item in self.REQUIRED_META: if item not in rule['meta']: missing_meta.append(item) id_conflict",
"import_now(self, rules): failed_list = [] for rule in rules: validation_error = rule.get('validation_error', None)",
"'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None): if not logger: from assemblyline.al.common import",
"\"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision',",
"rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\":",
"parse_files(self, files, force_safe_str=False): output = {} for cur_file in files: try: output[cur_file] =",
"if new_id is not None and new_rev is not None: rule['meta']['id'], rule['meta']['rule_version'] =",
"= new_id, new_rev else: failed_list.append((rule['name'], \"Could not find matching rule to increment revision",
"assemblyline.common import isotime from assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META = ['description', 'id',",
"not find matching rule to increment revision number.\")) continue key = \"%sr.%s\" %",
"forge.get_datastore() self.yp = yara_parser_class() self.log = logger self._id_cache = {} self._name_cache = []",
"\"%s cannot be empty.\" % field elif field == \"name\": if \" \"",
"cannot be empty.\" % field elif field == \"name\": if \" \" in",
"self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self, rule): return rule def display_rule(self, rule): return",
"self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision']",
"= \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if",
"= ['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None): if not",
"value.upper(): return False, \"organisation should be in all CAPS.\" elif field == \"id\":",
"parse_data(self, yara_bin, force_safe_str=False): output = [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in",
"'rule_group'] def __init__(self, logger=None): if not logger: from assemblyline.al.common import log as al_log",
"if validation_error: failed_list.append((rule['name'], \"Previously failed rule validation (%s)\" % validation_error)) continue if rule['meta']['id']",
"schema: ORG_000000\" return True, \"\" def check_for_id_conflicts(self, rid, rev): if rid is None",
"a simple integer value\" elif field == \"rule_group\": if value not in self.yp.RULE_GROUPS:",
"if len(num) != 6: error = True elif org != rule['meta']['organisation']: error =",
"not in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name'])",
"else: int(num) error = False except: error = True if error: return False,",
"logger: from assemblyline.al.common import log as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class",
"PyMethodMayBeStatic def translate_rule(self, rule): return rule def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def",
"import isotime from assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation',",
"return False finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output = [] parsed_rules =",
"files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except Exception, e: output[cur_file] = e return",
"== \"rule_group\": if value not in self.yp.RULE_GROUPS: return False, \"rule_group should be one",
"key = \"%sr.%s\" % (rid, rev) id_lookup = self.ds.get_signature(key) if id_lookup: return True",
"= self.ds.get_signature(key) if id_lookup: return True return False def check_for_name_conflicts(self, name): try: name_lookup",
"should be one of the following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif field ==",
"False, \"id should have the following schema: ORG_000000\" return True, \"\" def check_for_id_conflicts(self,",
"[] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta = [] for",
"parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file:",
"if value not in self.yp.RULE_GROUPS: return False, \"rule_group should be one of the",
"= self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not None and new_rev is not None:",
"output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output def parse_file(self,",
"sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output def parse_file(self, cur_file, force_safe_str=False): cur_file",
"new_rev is not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'], \"Could not",
"error = False except: error = True if error: return False, \"id should",
"rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list = [] for rule in",
"== \"rule_version\": try: int(value) except: return False, \"rule_version should be a simple integer",
"error = True elif org != rule['meta']['organisation']: error = True else: int(num) error",
"error: return False, \"id should have the following schema: ORG_000000\" return True, \"\"",
"open(cur_file, \"rb\") as yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File",
"[] for item in self.REQUIRED_META: if item not in rule['meta']: missing_meta.append(item) id_conflict =",
"= yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does not exists.\") def",
"= [] def _get_next_id(self, org): if org in self._id_cache: self._id_cache[org] += 1 else:",
"\"name_conflict\": name_conflict}) return output def parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file):",
"False, \"rule_version should be a simple integer value\" elif field == \"rule_group\": if",
"= os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file: yara_bin = yara_file.read() return",
"be one of the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\":",
"elif field == \"rule_version\": try: int(value) except: return False, \"rule_version should be a",
"and new_rev is not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'], \"Could",
"True return False def check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0)",
"def validate(self, field, value, rule): if not value: return False, \"%s cannot be",
"rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning',",
"in self.REQUIRED_META: if item not in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version',",
"not exists.\") def parse_files(self, files, force_safe_str=False): output = {} for cur_file in files:",
"= True elif org != rule['meta']['organisation']: error = True else: int(num) error =",
"!= 6: error = True elif org != rule['meta']['organisation']: error = True else:",
"os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin,",
"= True else: int(num) error = False except: error = True if error:",
"def parse_data(self, yara_bin, force_safe_str=False): output = [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule",
"the name.\" elif field == \"yara_version\": if value not in self.yp.VALID_YARA_VERSION: return False,",
"name, rows=0) if name_lookup['total'] > 0: return True if name in self._name_cache: return",
"have the following schema: ORG_000000\" return True, \"\" def check_for_id_conflicts(self, rid, rev): if",
"should be a simple integer value\" elif field == \"rule_group\": if value not",
"new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not None and new_rev is not",
"+= 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] # noinspection PyMethodMayBeStatic",
"= rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'],",
"yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does not exists.\") def parse_files(self,",
"value == \"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\") if len(num) != 6: error",
"name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total'] > 0: return",
"return False, \"rule_group should be one of the following: %s\" % \", \".join(self.yp.RULE_GROUPS)",
"return False def check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0) if",
"= self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta = [] for item in",
"name.\" elif field == \"yara_version\": if value not in self.yp.VALID_YARA_VERSION: return False, \"yara_version",
"not value == \"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\") if len(num) != 6:",
"class YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self,",
"0: return True if name in self._name_cache: return True return False finally: self._name_cache.append(name)",
"matching rule to increment revision number.\")) continue key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version'])",
"rev): if rid is None or rev is None: return False key =",
"key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso()",
"validate(self, field, value, rule): if not value: return False, \"%s cannot be empty.\"",
"\".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try: int(value) except: return False, \"rule_version should be",
"increment revision number.\")) continue key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version',",
"parsed_rules: missing_meta = [] for item in self.REQUIRED_META: if item not in rule['meta']:",
"rid is None or rev is None: return False key = \"%sr.%s\" %",
"value != value.upper(): return False, \"organisation should be in all CAPS.\" elif field",
"[] def _get_next_id(self, org): if org in self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org]",
"None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict})",
"def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def",
"in value: return False, \"There should be no space in the name.\" elif",
"output def parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\")",
"os import logging from assemblyline.common import isotime from assemblyline.al.common import forge class YaraImporter(object):",
"\", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try: int(value) except: return False, \"rule_version should",
"== \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version']",
"= rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if res['valid']:",
"yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does not",
"len(num) != 6: error = True elif org != rule['meta']['organisation']: error = True",
"False, \"%s cannot be empty.\" % field elif field == \"name\": if \"",
"rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name'])",
"be one of the following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\":",
"\"rule_version\": try: int(value) except: return False, \"rule_version should be a simple integer value\"",
"return True, \"\" def check_for_id_conflicts(self, rid, rev): if rid is None or rev",
"['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None): if not logger:",
"in files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except Exception, e: output[cur_file] = e",
"if res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" % rule['name'])",
"= res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed",
"self.REQUIRED_META: if item not in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None))",
"== \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev =",
"\"There should be no space in the name.\" elif field == \"yara_version\": if",
"CAPS.\" elif field == \"id\": if not value == \"<AUTO_INCREMENT>\": try: org, num",
"rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules']",
"new_rev else: failed_list.append((rule['name'], \"Could not find matching rule to increment revision number.\")) continue",
"return False, \"yara_version should be one of the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION)",
"for rule in parsed_rules: missing_meta = [] for item in self.REQUIRED_META: if item",
"rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" % rule['name']) else: failed_list.append((rule['name'],",
"\"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\") if len(num) != 6: error = True",
"should be no space in the name.\" elif field == \"yara_version\": if value",
"% \", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if value != value.upper(): return False,",
"be no space in the name.\" elif field == \"yara_version\": if value not",
"else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self,",
"\"id should have the following schema: ORG_000000\" return True, \"\" def check_for_id_conflicts(self, rid,",
"yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does not exists.\")",
"= True if error: return False, \"id should have the following schema: ORG_000000\"",
"revision number.\")) continue key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None)",
"rows=0) if name_lookup['total'] > 0: return True if name in self._name_cache: return True",
"exists.\") def parse_files(self, files, force_safe_str=False): output = {} for cur_file in files: try:",
"one of the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try:",
"in all CAPS.\" elif field == \"id\": if not value == \"<AUTO_INCREMENT>\": try:",
"name_conflict}) return output def parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with",
"%s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try: int(value) except: return False,",
"the following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if value !=",
"rule in rules: validation_error = rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously failed rule",
"validation (%s)\" % validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" %",
"if error: return False, \"id should have the following schema: ORG_000000\" return True,",
"rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not",
"False finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output = [] parsed_rules = self.yp.parse_rule_file(yara_bin,",
"1 return self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self, rule): return rule def display_rule(self,",
"if os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str)",
"in self.yp.VALID_YARA_VERSION: return False, \"yara_version should be one of the following: %s\" %",
"False key = \"%sr.%s\" % (rid, rev) id_lookup = self.ds.get_signature(key) if id_lookup: return",
"in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule':",
"logging from assemblyline.common import isotime from assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META =",
"os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else:",
"return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list",
"is not None and new_rev is not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev",
"else: failed_list.append((rule['name'], \"Could not find matching rule to increment revision number.\")) continue key",
"self._id_cache = {} self._name_cache = [] def _get_next_id(self, org): if org in self._id_cache:",
"[] for rule in rules: validation_error = rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously",
"return True if name in self._name_cache: return True return False finally: self._name_cache.append(name) def",
"from assemblyline.common import isotime from assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META = ['description',",
"assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version',",
"'yara_version', 'rule_group'] def __init__(self, logger=None): if not logger: from assemblyline.al.common import log as",
"= [] for rule in rules: validation_error = rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'],",
"number.\")) continue key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date']",
"\"Could not find matching rule to increment revision number.\")) continue key = \"%sr.%s\"",
"(%s)\" % res['message']['error'])) return failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection PyBroadException",
"== \"id\": if not value == \"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\") if",
"import os import logging from assemblyline.common import isotime from assemblyline.al.common import forge class",
"%s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation (%s)\" % res['message']['error'])) return failed_list",
"logger self._id_cache = {} self._name_cache = [] def _get_next_id(self, org): if org in",
"True, \"\" def check_for_id_conflicts(self, rid, rev): if rid is None or rev is",
"% (rid, rev) id_lookup = self.ds.get_signature(key) if id_lookup: return True return False def",
"check_for_id_conflicts(self, rid, rev): if rid is None or rev is None: return False",
"Exception(\"File '%s' does not exists.\") def parse_files(self, files, force_safe_str=False): output = {} for",
"self._id_cache[org] += 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] # noinspection",
"self.yp = yara_parser_class() self.log = logger self._id_cache = {} self._name_cache = [] def",
"no space in the name.\" elif field == \"yara_version\": if value not in",
"is None or rev is None: return False key = \"%sr.%s\" % (rid,",
"True if name in self._name_cache: return True return False finally: self._name_cache.append(name) def parse_data(self,",
"self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self, rule):",
"import log as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds",
"self.ds = forge.get_datastore() self.yp = yara_parser_class() self.log = logger self._id_cache = {} self._name_cache",
"PyBroadException def validate(self, field, value, rule): if not value: return False, \"%s cannot",
"False except: error = True if error: return False, \"id should have the",
"rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if",
"is None: return False key = \"%sr.%s\" % (rid, rev) id_lookup = self.ds.get_signature(key)",
"None) if validation_error: failed_list.append((rule['name'], \"Previously failed rule validation (%s)\" % validation_error)) continue if",
"% validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation']))",
"\", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if value != value.upper(): return False, \"organisation",
"validation_error: failed_list.append((rule['name'], \"Previously failed rule validation (%s)\" % validation_error)) continue if rule['meta']['id'] ==",
"= self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning', None)",
"ORG_000000\" return True, \"\" def check_for_id_conflicts(self, rid, rev): if rid is None or",
"rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version,",
"def validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self, field, value, rule):",
"return self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self, field, value, rule): if not value:",
"None or rev is None: return False key = \"%sr.%s\" % (rid, rev)",
"force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does not exists.\") def parse_files(self, files, force_safe_str=False): output",
"name_lookup['total'] > 0: return True if name in self._name_cache: return True return False",
"== \"name\": if \" \" in value: return False, \"There should be no",
"validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self, field, value, rule): if",
"rev) id_lookup = self.ds.get_signature(key) if id_lookup: return True return False def check_for_name_conflicts(self, name):",
"\"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output def parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file)",
"self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] #",
"rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if res['valid']: rule['warning']",
"continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version']",
"# noinspection PyMethodMayBeStatic def translate_rule(self, rule): return rule def display_rule(self, rule): return self.yp.dump_rule_file([rule],",
"self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self, field, value, rule): if not value: return",
"self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" %",
"elif field == \"organisation\": if value != value.upper(): return False, \"organisation should be",
"field == \"id\": if not value == \"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\")",
"(rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del",
"failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self, field, value,",
"try: int(value) except: return False, \"rule_version should be a simple integer value\" elif",
"None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation",
"rules): failed_list = [] for rule in rules: validation_error = rule.get('validation_error', None) if",
"if org in self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1",
"return output def parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file,",
"\"yara_version should be one of the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field",
"al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore() self.yp",
"\"id\": if not value == \"<AUTO_INCREMENT>\": try: org, num = value.split(\"_\") if len(num)",
"elif field == \"rule_group\": if value not in self.yp.RULE_GROUPS: return False, \"rule_group should",
"False, \"organisation should be in all CAPS.\" elif field == \"id\": if not",
"return False, \"id should have the following schema: ORG_000000\" return True, \"\" def",
"error = True if error: return False, \"id should have the following schema:",
"__init__(self, logger=None): if not logger: from assemblyline.al.common import log as al_log al_log.init_logging('yara_importer') logger",
"def import_now(self, rules): failed_list = [] for rule in rules: validation_error = rule.get('validation_error',",
"should have the following schema: ORG_000000\" return True, \"\" def check_for_id_conflicts(self, rid, rev):",
"failed_list.append((rule['name'], \"Could not find matching rule to increment revision number.\")) continue key =",
"False, \"There should be no space in the name.\" elif field == \"yara_version\":",
"try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except Exception, e: output[cur_file] = e return output",
"does not exists.\") def parse_files(self, files, force_safe_str=False): output = {} for cur_file in",
"rid, rev): if rid is None or rev is None: return False key",
"\"organisation\": if value != value.upper(): return False, \"organisation should be in all CAPS.\"",
"if value not in self.yp.VALID_YARA_VERSION: return False, \"yara_version should be one of the",
"fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list = []",
"\"Failed rule validation (%s)\" % res['message']['error'])) return failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule)",
"return False, \"There should be no space in the name.\" elif field ==",
"self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta = [] for item in self.REQUIRED_META:",
"rule['name']) if new_id is not None and new_rev is not None: rule['meta']['id'], rule['meta']['rule_version']",
"self.yp.VALID_YARA_VERSION: return False, \"yara_version should be one of the following: %s\" % \",",
"self.log.info(\"Added signature %s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation (%s)\" % res['message']['error']))",
"empty.\" % field elif field == \"name\": if \" \" in value: return",
"\"rule_version should be a simple integer value\" elif field == \"rule_group\": if value",
"for cur_file in files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except Exception, e: output[cur_file]",
"display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list = [] for rule",
"% res['message']['error'])) return failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection PyBroadException def",
"elif org != rule['meta']['organisation']: error = True else: int(num) error = False except:",
"_get_next_id(self, org): if org in self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org)",
"yara_parser_class() self.log = logger self._id_cache = {} self._name_cache = [] def _get_next_id(self, org):",
"parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta = [] for item",
"cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file: yara_bin = yara_file.read()",
"rule to increment revision number.\")) continue key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version",
"id_lookup: return True return False def check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" %",
"= value.split(\"_\") if len(num) != 6: error = True elif org != rule['meta']['organisation']:",
"failed_list = [] for rule in rules: validation_error = rule.get('validation_error', None) if validation_error:",
"1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return self._id_cache[org] # noinspection PyMethodMayBeStatic def",
"be empty.\" % field elif field == \"name\": if \" \" in value:",
"all CAPS.\" elif field == \"id\": if not value == \"<AUTO_INCREMENT>\": try: org,",
"% (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False):",
"is not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'], \"Could not find",
"res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed rule",
"failed_list.append((rule['name'], \"Failed rule validation (%s)\" % res['message']['error'])) return failed_list def validate_rule(self, rule): return",
"else: failed_list.append((rule['name'], \"Failed rule validation (%s)\" % res['message']['error'])) return failed_list def validate_rule(self, rule):",
"None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None))",
"= logger self._id_cache = {} self._name_cache = [] def _get_next_id(self, org): if org",
"rules: validation_error = rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously failed rule validation (%s)\"",
"logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore() self.yp = yara_parser_class()",
"as yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise Exception(\"File '%s' does",
"rule validation (%s)\" % res['message']['error'])) return failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule) #",
"\"\" def check_for_id_conflicts(self, rid, rev): if rid is None or rev is None:",
"== \"yara_version\": if value not in self.yp.VALID_YARA_VERSION: return False, \"yara_version should be one",
"if \" \" in value: return False, \"There should be no space in",
"res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" % rule['name']) else:",
"field, value, rule): if not value: return False, \"%s cannot be empty.\" %",
"rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res",
"with open(cur_file, \"rb\") as yara_file: yara_bin = yara_file.read() return self.parse_data(yara_bin, force_safe_str=force_safe_str) else: raise",
"{} for cur_file in files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except Exception, e:",
"to increment revision number.\")) continue key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version =",
"value: return False, \"%s cannot be empty.\" % field elif field == \"name\":",
"rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule,",
"cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\") as yara_file: yara_bin",
"new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not None and new_rev is",
"self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\" % rule['name']) else: failed_list.append((rule['name'], \"Failed rule validation (%s)\"",
"!= value.upper(): return False, \"organisation should be in all CAPS.\" elif field ==",
"\"Previously failed rule validation (%s)\" % validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id']",
"space in the name.\" elif field == \"yara_version\": if value not in self.yp.VALID_YARA_VERSION:",
"of the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try: int(value)",
"force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta = [] for item in self.REQUIRED_META: if",
"rule in parsed_rules: missing_meta = [] for item in self.REQUIRED_META: if item not",
"= self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature %s\"",
"self._name_cache = [] def _get_next_id(self, org): if org in self._id_cache: self._id_cache[org] += 1",
"failed rule validation (%s)\" % validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] =",
"True if error: return False, \"id should have the following schema: ORG_000000\" return",
"def translate_rule(self, rule): return rule def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self,",
"simple integer value\" elif field == \"rule_group\": if value not in self.yp.RULE_GROUPS: return",
"if item not in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict",
"or rev is None: return False key = \"%sr.%s\" % (rid, rev) id_lookup",
"True else: int(num) error = False except: error = True if error: return",
"if value != value.upper(): return False, \"organisation should be in all CAPS.\" elif",
"following schema: ORG_000000\" return True, \"\" def check_for_id_conflicts(self, rid, rev): if rid is",
"\"name\": if \" \" in value: return False, \"There should be no space",
"self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list =",
"value\" elif field == \"rule_group\": if value not in self.yp.RULE_GROUPS: return False, \"rule_group",
"yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] =",
"self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key,",
"False): del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not None",
"output = {} for cur_file in files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except",
"if not logger: from assemblyline.al.common import log as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer')",
"False def check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total']",
"field == \"rule_version\": try: int(value) except: return False, \"rule_version should be a simple",
"\"organisation should be in all CAPS.\" elif field == \"id\": if not value",
"self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output = [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for",
"res['message']['error'])) return failed_list def validate_rule(self, rule): return self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self,",
"in self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return self._id_cache[org]",
"name in self._name_cache: return True return False finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False):",
"in self.yp.RULE_GROUPS: return False, \"rule_group should be one of the following: %s\" %",
"(rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'],",
"return False, \"organisation should be in all CAPS.\" elif field == \"id\": if",
"def parse_file(self, cur_file, force_safe_str=False): cur_file = os.path.expanduser(cur_file) if os.path.exists(cur_file): with open(cur_file, \"rb\") as",
"import logging from assemblyline.common import isotime from assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META",
"new_id, new_rev else: failed_list.append((rule['name'], \"Could not find matching rule to increment revision number.\"))",
"\"%sr.%s\" % (rid, rev) id_lookup = self.ds.get_signature(key) if id_lookup: return True return False",
"isotime from assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation', 'poc',",
"(rid, rev) id_lookup = self.ds.get_signature(key) if id_lookup: return True return False def check_for_name_conflicts(self,",
"def check_for_name_conflicts(self, name): try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total'] >",
"item in self.REQUIRED_META: if item not in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None),",
"logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore() self.yp = yara_parser_class() self.log = logger",
"self.ds.get_signature(key) if id_lookup: return True return False def check_for_name_conflicts(self, name): try: name_lookup =",
"= {} for cur_file in files: try: output[cur_file] = self.parse_file(cur_file, force_safe_str=force_safe_str) except Exception,",
"\"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output def parse_file(self, cur_file, force_safe_str=False):",
"%s\" % \", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if value != value.upper(): return",
"fake_dependencies=True) def import_now(self, rules): failed_list = [] for rule in rules: validation_error =",
"from assemblyline.al.common import forge class YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation', 'poc', 'rule_version',",
"self.yp.RULE_GROUPS: return False, \"rule_group should be one of the following: %s\" % \",",
"as al_log al_log.init_logging('yara_importer') logger = logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore()",
"not None and new_rev is not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else:",
"self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total'] > 0: return True if name in",
"+ 1 return self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self, rule): return rule def",
"num = value.split(\"_\") if len(num) != 6: error = True elif org !=",
"False, \"rule_group should be one of the following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif",
"rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if res['valid']: rule['warning'] =",
"not in self.yp.VALID_YARA_VERSION: return False, \"yara_version should be one of the following: %s\"",
"name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total'] > 0: return True if",
"self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\":",
"yara_bin, force_safe_str=False): output = [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules:",
"not in self.yp.RULE_GROUPS: return False, \"rule_group should be one of the following: %s\"",
"elif field == \"yara_version\": if value not in self.yp.VALID_YARA_VERSION: return False, \"yara_version should",
"rule validation (%s)\" % validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\"",
"% field elif field == \"name\": if \" \" in value: return False,",
"id_lookup = self.ds.get_signature(key) if id_lookup: return True return False def check_for_name_conflicts(self, name): try:",
"= forge.get_datastore() self.yp = yara_parser_class() self.log = logger self._id_cache = {} self._name_cache =",
"finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output = [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str)",
"of the following: %s\" % \", \".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if value",
"except: error = True if error: return False, \"id should have the following",
"'%s' does not exists.\") def parse_files(self, files, force_safe_str=False): output = {} for cur_file",
"None: return False key = \"%sr.%s\" % (rid, rev) id_lookup = self.ds.get_signature(key) if",
"def _get_next_id(self, org): if org in self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org] =",
"rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev",
"isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by'] rule['depends'], rule['modules'] = self.yp.parse_dependencies(rule['condition'], self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule)",
"in the name.\" elif field == \"yara_version\": if value not in self.yp.VALID_YARA_VERSION: return",
"= False except: error = True if error: return False, \"id should have",
"yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore() self.yp = yara_parser_class() self.log = logger self._id_cache",
"org in self._id_cache: self._id_cache[org] += 1 else: self._id_cache[org] = self.ds.get_last_signature_id(org) + 1 return",
"rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules):",
"return self._id_cache[org] # noinspection PyMethodMayBeStatic def translate_rule(self, rule): return rule def display_rule(self, rule):",
"rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not None and new_rev",
"\"yara_version\": if value not in self.yp.VALID_YARA_VERSION: return False, \"yara_version should be one of",
"rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict, \"name_conflict\": name_conflict}) return output def parse_file(self, cur_file,",
"= [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta = []",
"elif field == \"name\": if \" \" in value: return False, \"There should",
"\".join(self.yp.RULE_GROUPS) elif field == \"organisation\": if value != value.upper(): return False, \"organisation should",
"not value: return False, \"%s cannot be empty.\" % field elif field ==",
"rule): if not value: return False, \"%s cannot be empty.\" % field elif",
"rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\":",
"\"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] =",
"return True return False finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output = []",
"= forge.get_yara_parser() self.ds = forge.get_datastore() self.yp = yara_parser_class() self.log = logger self._id_cache =",
"continue key = \"%sr.%s\" % (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] =",
"self._name_cache: return True return False finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output =",
"False, \"yara_version should be one of the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif",
"rule): return rule def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True) def display_rules(self, rules): return",
"return self.yp.dump_rule_file(rules, fake_dependencies=True) def import_now(self, rules): failed_list = [] for rule in rules:",
"try: name_lookup = self.ds.search_signature(query=\"name:%s\" % name, rows=0) if name_lookup['total'] > 0: return True",
"res = self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule) self.log.info(\"Added signature",
"None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'], \"Could not find matching rule",
"in rules: validation_error = rule.get('validation_error', None) if validation_error: failed_list.append((rule['name'], \"Previously failed rule validation",
"rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'], self._get_next_id(rule['meta']['organisation'])) if rule['meta']['rule_version'] == \"<AUTO_INCREMENT>\": rule['meta']['rule_version'] = self.ds.get_last_rev_for_id(rule['meta']['id'])",
"self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id is not None and new_rev is not None: rule['meta']['id'],",
"rev is None: return False key = \"%sr.%s\" % (rid, rev) id_lookup =",
"= self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if",
"\" \" in value: return False, \"There should be no space in the",
"value: return False, \"There should be no space in the name.\" elif field",
"rule): return self.yp.validate_rule(rule) # noinspection PyBroadException def validate(self, field, value, rule): if not",
"'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group'] def __init__(self, logger=None): if not logger: from assemblyline.al.common",
"field == \"name\": if \" \" in value: return False, \"There should be",
"== \"organisation\": if value != value.upper(): return False, \"organisation should be in all",
"import forge class YaraImporter(object): REQUIRED_META = ['description', 'id', 'organisation', 'poc', 'rule_version', 'yara_version', 'rule_group']",
"logger=None): if not logger: from assemblyline.al.common import log as al_log al_log.init_logging('yara_importer') logger =",
"% (rule['meta']['id'], rule['meta']['rule_version']) yara_version = rule['meta'].get('yara_version', None) rule['meta']['creation_date'] = isotime.now_as_iso() rule['meta']['last_saved_by'] = rule['meta']['al_imported_by']",
"noinspection PyMethodMayBeStatic def translate_rule(self, rule): return rule def display_rule(self, rule): return self.yp.dump_rule_file([rule], fake_dependencies=True)",
"self.yp.YARA_MODULES.get(yara_version, None)) res = self.yp.validate_rule(rule) if res['valid']: rule['warning'] = res.get('warning', None) self.ds.save_signature(key, rule)",
"self.log = logger self._id_cache = {} self._name_cache = [] def _get_next_id(self, org): if",
"self.ds.get_last_rev_for_id(rule['meta']['id']) if rule.get('is_new_revision', False): del rule['is_new_revision'] new_id, new_rev = self.ds.get_next_rev_for_name(rule['meta']['organisation'], rule['name']) if new_id",
"error = True else: int(num) error = False except: error = True if",
"the following: %s\" % \", \".join(self.yp.VALID_YARA_VERSION) elif field == \"rule_version\": try: int(value) except:",
"logging.getLogger('assemblyline.yara_importer') logger.setLevel(logging.INFO) yara_parser_class = forge.get_yara_parser() self.ds = forge.get_datastore() self.yp = yara_parser_class() self.log =",
"def __init__(self, logger=None): if not logger: from assemblyline.al.common import log as al_log al_log.init_logging('yara_importer')",
"True return False finally: self._name_cache.append(name) def parse_data(self, yara_bin, force_safe_str=False): output = [] parsed_rules",
"for item in self.REQUIRED_META: if item not in rule['meta']: missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id',",
"(%s)\" % validation_error)) continue if rule['meta']['id'] == \"<AUTO_INCREMENT>\": rule['meta']['id'] = \"%s_%06d\" % (rule['meta']['organisation'],",
"output = [] parsed_rules = self.yp.parse_rule_file(yara_bin, force_safe_str=force_safe_str) for rule in parsed_rules: missing_meta =",
"missing_meta.append(item) id_conflict = self.check_for_id_conflicts(rule['meta'].get('id', None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\":",
"new_id is not None and new_rev is not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id,",
"None), rule['meta'].get('rule_version', None)) name_conflict = self.check_for_name_conflicts(rule['name']) output.append({'rule': rule, \"missing_meta\": sorted(missing_meta, reverse=True), \"id_conflict\": id_conflict,",
"field == \"rule_group\": if value not in self.yp.RULE_GROUPS: return False, \"rule_group should be",
"# noinspection PyBroadException def validate(self, field, value, rule): if not value: return False,",
"6: error = True elif org != rule['meta']['organisation']: error = True else: int(num)",
"None and new_rev is not None: rule['meta']['id'], rule['meta']['rule_version'] = new_id, new_rev else: failed_list.append((rule['name'],",
"forge.get_yara_parser() self.ds = forge.get_datastore() self.yp = yara_parser_class() self.log = logger self._id_cache = {}"
] |
[
"# async def main(loop): # processes = 8 # pool = mp.Pool(processes) #",
"# # # We are using the low-level \"loop.create_task()\" API here because #",
"<filename>test.py # import asyncio # import functools # import time # import random",
"# def on_finish(task): # # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # # def mp_schedule():",
"# tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages] # # responses =",
"# import numpy as np # from tqdm import tqdm # # #",
"break # # # Wait until *fut* has a result (1 second) and",
"print('registering callbacks on future') # # page = 1 # # while True:",
"print(results) # print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() # for title, page_urls, url in",
"page = 1 # # while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) # #",
"asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total time: \", time.time() - t1)",
"# # print(results) # print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() # for title, page_urls,",
"in htmls] # results = pool.map(parse, htmls) # # results = pool.map_async(parse, htmls).get()",
"# # print('setting result of future') # # all_done.set_result('the result') # # event_loop",
"loop.close() # print(\"Async total time: \", time.time() - t1) import requests import json",
"await r.text() # await asyncio.sleep(0.1) # slightly delay for downloading # return html",
"t1 = time.time() # loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() # print(\"Async",
"in pool.map(download, urls): # # pbar.update() # # async def schedule(): # #",
"= ['{}{}'.format(prefix, page) for page in pages] # # pbar = tqdm(total=len(urls), ncols=80)",
"cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing as mp # import time # async",
"# if __name__ == '__main__': # cost = time.time() # apply_async_with_callback() # print(\"total",
"5: # # break # # # Wait until *fut* has a result",
"on future') # # page = 1 # # while True: # #",
"# # # 回调函数 # # def on_finish(task): # # print('下载完成:', task.result()) #",
"# finally: # # event_loop.close() # # async def download(fut, delay, value): #",
"whenever foo_pool(i) returns a result. # # result_list is modified only by the",
"soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href']) for url in urls]) # url =",
"# # # url_chunks = np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5) as pool:",
"args=(html,)) for html in htmls] # results = pool.map(parse, htmls) # # results",
"Task. # # # We are using the low-level \"loop.create_task()\" API here because",
"def on_finish(task): # # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # # def mp_schedule(): #",
"模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost, 3)) # # # 回调函数 # #",
"# for url_chunk in urls: # # pool.apply_async(download, args = (url_chunk, ), callback",
"# urls = ['{}{}'.format(prefix, page) for page in pages] # # # url_chunks",
"# # Create a new Future object. # # # fut = loop.create_future()",
"# cost = time.time() # apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3))) # #",
"loop at hand. # # # Otherwise we could have just used \"asyncio.create_task()\".",
"bs4 import BeautifulSoup # from urllib.request import urljoin # import re # import",
"total time: \", time.time() - t1) import requests import json import pandas as",
"1 # # asyncio.create_task(download(fut, 1, page)) # # if page > 5: #",
"aiohttp.ClientSession() as session: # count = 1 # while len(unseen) != 0: #",
"n=page)) # # page += 1 # # if page > 5: #",
"it. # # print(await fut) # # asyncio.run(main()) # import aiohttp # import",
"# # pbar.update() # # async def schedule(): # # pages = list(range(500))",
"tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if __name__ == '__main__': # # uvloop.install() #",
"# def parse(html): # soup = BeautifulSoup(html, 'lxml') # urls = soup.find_all('a', {\"href\":",
"for title, page_urls, url in results: # # print(count, title, url) # unseen.update(page_urls",
"print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() # for title, page_urls, url in results: #",
"urllib.request import urljoin # import re # import multiprocessing as mp # base_url",
"BeautifulSoup(html, 'lxml') # urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() #",
"round(time.time()-cost, 3))) # # async def main(): # # # Get the current",
"= BeautifulSoup(html, 'lxml') # urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip()",
"pandas as pd url = 'http://127.0.0.1:5010/get_all/' def a(): try: resp = requests.get(url) except",
"import urljoin # import re # import multiprocessing as mp # base_url =",
"# # print(count, title, url) # unseen.update(page_urls - seen) # count += 1",
"register_callbacks(all_done) # # print('setting result of future') # # all_done.set_result('the result') # #",
"async def main(): # # # Get the current event loop. # #",
"# # Run \"set_after()\" coroutine in a parallel Task. # # # We",
"# print(results) # print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() # for title, page_urls, url",
"mp.Pool(processes=3) # for i in range(10): # pool.apply_async(foo_pool, args = (i, ), callback",
"in range(10): # pool.apply_async(foo_pool, args = (i, ), callback = log_result) # pool.close()",
"# for i in range(10): # pool.apply_async(foo_pool, args = (i, ), callback =",
"in pages] # # responses = [await t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks),",
"low-level \"loop.create_task()\" API here because # # # we already have a reference",
"print(result) # def apply_async_with_callback(): # pool = mp.Pool(processes=3) # for i in range(10):",
"pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix,",
"by the main process, not the pool workers. # result_list.append(result) # print(result) #",
"a new Future object. # # # fut = loop.create_future() # # #",
"page in pages] # # pbar = tqdm(total=len(urls), ncols=80) # # async with",
"url_chunks = np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5) as pool: # # for",
"page) for page in pages] # # # url_chunks = np.array_split(urls ,5) #",
"= await r.text() # await asyncio.sleep(0.1) # slightly delay for downloading # return",
"download(fut, delay, value): # # cost = time.time() # # # Sleep for",
"\"set_after()\" coroutine in a parallel Task. # # # We are using the",
"page > 5: # # return # # async def main(all_done): # #",
"await register_callbacks(all_done) # # print('setting result of future') # # all_done.set_result('the result') #",
"= time.time() # apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3))) # # def on_finish(future,",
"# pool.apply_async(download, args = (url_chunk, ), callback = on_finish) # # async def",
"def on_finish(future, n): # # print('{}: future done: {}'.format(n, future.result())) # # async",
"# fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3))) # # async def main(): #",
"because # # # we already have a reference to the event loop",
"as a result of *fut* Future. # # fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost,",
"# # def on_finish(task): # # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # # def",
"# with multiprocessing.Pool(processes=5) as pool: # # for url_chunk in urls: # #",
"def crawl(url, session): # r = await session.get(url) # html = await r.text()",
"# cost = time.time() # # # asyncio.run(schedule()) # # mp_schedule() # #",
"+= 1 # if __name__ == \"__main__\": # t1 = time.time() # loop",
"fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3))) # # async def main(): # #",
"tasks = [loop.create_task(crawl(url, session)) for url in unseen] # finished, unfinished = await",
"== '__main__': # cost = time.time() # apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3)))",
"= list(range(500)) # # prefix = 'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix, page)",
"# page_urls = set([urljoin(base_url, url['href']) for url in urls]) # url = soup.find('meta',",
"with multiprocessing.Pool(processes=5) as pool: # # for url_chunk in urls: # # pool.apply_async(download,",
"pages] # # # url_chunks = np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5) as",
"# while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page += 1 #",
"= mp.Pool(processes=3) # for i in range(10): # pool.apply_async(foo_pool, args = (i, ),",
"回调函数 # # def on_finish(task): # # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # #",
"# # # we already have a reference to the event loop at",
"# we already have a reference to the event loop at hand. #",
"def download(fut, delay, value): # # cost = time.time() # # # Sleep",
"print(count, title, url) # unseen.update(page_urls - seen) # count += 1 # if",
"# print(result_list) # if __name__ == '__main__': # cost = time.time() # apply_async_with_callback()",
"= time.time() # # await asyncio.sleep(3) # 模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost,",
"# Wait until *fut* has a result (1 second) and print it. #",
"= loop.create_future() # # # Run \"set_after()\" coroutine in a parallel Task. #",
"# seen = set() # unseen = set([base_url]) # def parse(html): # soup",
"unseen.update(page_urls - seen) # count += 1 # if __name__ == \"__main__\": #",
"# urls = ['{}{}'.format(prefix, page) for page in pages] # # pbar =",
"def schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' #",
"url # async def crawl(url, session): # r = await session.get(url) # html",
"# print(count, title, url) # unseen.update(page_urls - seen) # count += 1 #",
"# results = pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) # results = [j.get() for",
"# if __name__ == \"__main__\": # t1 = time.time() # loop = asyncio.get_event_loop()",
"uvloop # import numpy as np # from tqdm import tqdm # #",
"# import aiomultiprocess # import uvloop # import numpy as np # from",
"has a result (1 second) and print it. # # print(await fut) #",
"> 5: # # return # # async def main(all_done): # # await",
"# # # Otherwise we could have just used \"asyncio.create_task()\". # # while",
"[asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages] # # responses = [await t for",
"functools # import time # import random # import multiprocessing # import aiomultiprocess",
"# # Sleep for *delay* seconds. # # await asyncio.sleep(delay) # # #",
"# import time # from bs4 import BeautifulSoup # from urllib.request import urljoin",
"# def mp_schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/'",
"# # with multiprocessing.Pool(processes=5) as pool: # # for url_chunk in urls: #",
"except Exception as e: print(f'url: {url}, error: {e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content)",
"获取协程返回值或者抛出的异常 # # def mp_schedule(): # # pages = list(range(500)) # # prefix",
"as pool: # # async for result in pool.map(download, urls): # # pbar.update()",
"proxy_list_string = json.loads(resp.content) for proxy in proxy_list_string: print(proxy) # proxy_dict = json.loads(proxy) #",
"print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,)) for html in htmls] # results",
"import functools # import time # import random # import multiprocessing # import",
"# # event_loop = asyncio.get_event_loop() # # try: # # all_done = asyncio.Future()",
"# pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # # urls =",
"# url = soup.find('meta', {'property': \"og:url\"})['content'] # return title, page_urls, url # async",
"t1) import requests import json import pandas as pd url = 'http://127.0.0.1:5010/get_all/' def",
"return pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy in proxy_list_string: print(proxy) # proxy_dict =",
"# async def download(fut, delay, value): # # cost = time.time() # #",
"# # if page > 5: # # return # # async def",
"pages] # # responses = [await t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)]",
"'lxml') # urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() # page_urls",
"= np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5) as pool: # # for url_chunk",
"= [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages] # # responses = [await t",
"# event_loop = asyncio.get_event_loop() # # try: # # all_done = asyncio.Future() #",
"# # loop = asyncio.get_running_loop() # # # Create a new Future object.",
"pool.apply_async(download, args = (url_chunk, ), callback = on_finish) # # async def aio_mp_schedule():",
"url) # unseen.update(page_urls - seen) # count += 1 # if __name__ ==",
"downloading # return html # async def main(loop): # processes = 8 #",
"# # asyncio.run(schedule()) # # mp_schedule() # # print(\"total time cost: {}\".format(round(time.time()-cost, 3)))",
"# slightly affected # async with aiohttp.ClientSession() as session: # count = 1",
"event loop at hand. # # # Otherwise we could have just used",
"main process, not the pool workers. # result_list.append(result) # print(result) # def apply_async_with_callback():",
"urls]) # url = soup.find('meta', {'property': \"og:url\"})['content'] # return title, page_urls, url #",
"= [await t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if __name__",
"time # from bs4 import BeautifulSoup # from urllib.request import urljoin # import",
"pbar = tqdm(total=len(urls), ncols=80) # # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: #",
"delay, value): # # cost = time.time() # # # Sleep for *delay*",
"multiprocessing # import aiomultiprocess # import uvloop # import numpy as np #",
"# all_done.set_result('the result') # # event_loop = asyncio.get_event_loop() # # try: # #",
"# responses = [await t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # #",
"# return x*x # result_list = [] # def log_result(result): # # This",
"# tasks = [loop.create_task(crawl(url, session)) for url in unseen] # finished, unfinished =",
"slightly affected # async with aiohttp.ClientSession() as session: # count = 1 #",
"= 1 # # while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page",
"API here because # # # we already have a reference to the",
"= 1 # # asyncio.create_task(download(fut, 1, page)) # # if page > 5:",
"# base_url = \"https://morvanzhou.github.io/\" # seen = set() # unseen = set([base_url]) #",
"# print(\"Async total time: \", time.time() - t1) import requests import json import",
"# async def aio_mp_schedule(): # # pages = list(range(500)) # # prefix =",
"__name__ == '__main__': # cost = time.time() # apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost,",
"# prefix = 'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in",
"on_finish) # # async def aio_mp_schedule(): # # pages = list(range(500)) # #",
"# Create a new Future object. # # # fut = loop.create_future() #",
"# async def main(all_done): # # await register_callbacks(all_done) # # print('setting result of",
"try: # # all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # # finally: #",
"future') # # all_done.set_result('the result') # # event_loop = asyncio.get_event_loop() # # try:",
"asyncio.get_event_loop() # # try: # # all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done)) #",
"# # We are using the low-level \"loop.create_task()\" API here because # #",
"3))) # # def on_finish(future, n): # # print('{}: future done: {}'.format(n, future.result()))",
"# # await asyncio.sleep(delay) # # # Set *value* as a result of",
"= list(range(500)) # # prefix = 'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page)))",
"crawl(url, session): # r = await session.get(url) # html = await r.text() #",
"__name__ == '__main__': # # uvloop.install() # # cost = time.time() # #",
"= log_result) # pool.close() # pool.join() # print(result_list) # if __name__ == '__main__':",
"print(\"Async total time: \", time.time() - t1) import requests import json import pandas",
"# import multiprocessing as mp # import time # async def foo_pool(x): #",
"# Set *value* as a result of *fut* Future. # # fut.set_result('task: {}",
"task.result()) # 获取协程返回值或者抛出的异常 # # def mp_schedule(): # # pages = list(range(500)) #",
"# loop = asyncio.get_running_loop() # # # Create a new Future object. #",
"fut = loop.create_future() # # # Run \"set_after()\" coroutine in a parallel Task.",
"return html # async def main(loop): # processes = 8 # pool =",
"# # # Sleep for *delay* seconds. # # await asyncio.sleep(delay) # #",
"the low-level \"loop.create_task()\" API here because # # # we already have a",
"asyncio.wait(tasks) # htmls = [f.result() for f in finished] # print('\\nDistributed Parsing...') #",
"hand. # # # Otherwise we could have just used \"asyncio.create_task()\". # #",
"async for result in pool.map(download, urls): # # pbar.update() # # async def",
"# page += 1 # # if page > 5: # # return",
"[pool.apply_async(parse, args=(html,)) for html in htmls] # results = pool.map(parse, htmls) # #",
"time.time() # apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3))) # # def on_finish(future, n):",
"cost = time.time() # # # Sleep for *delay* seconds. # # await",
"= pool.map(parse, htmls) # # results = pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) #",
"page) for page in pages] # # pbar = tqdm(total=len(urls), ncols=80) # #",
"as pool: # # for url_chunk in urls: # # pool.apply_async(download, args =",
"*fut* Future. # # fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3))) # # async",
"# # pool.apply_async(download, args = (url_chunk, ), callback = on_finish) # # async",
"# This is called whenever foo_pool(i) returns a result. # # result_list is",
"page_urls = set([urljoin(base_url, url['href']) for url in urls]) # url = soup.find('meta', {'property':",
"url['href']) for url in urls]) # url = soup.find('meta', {'property': \"og:url\"})['content'] # return",
"as pd url = 'http://127.0.0.1:5010/get_all/' def a(): try: resp = requests.get(url) except Exception",
"# # async def download(url): # # cost = time.time() # # await",
"# import time # import random # import multiprocessing # import aiomultiprocess #",
"# print(result) # def apply_async_with_callback(): # pool = mp.Pool(processes=3) # for i in",
"# 获取协程返回值或者抛出的异常 # # def mp_schedule(): # # pages = list(range(500)) # #",
"pool: # # for url_chunk in urls: # # pool.apply_async(download, args = (url_chunk,",
"results = [j.get() for j in parse_jobs] # # print(results) # print('\\nAnalysing...') #",
"only by the main process, not the pool workers. # result_list.append(result) # print(result)",
"requests import json import pandas as pd url = 'http://127.0.0.1:5010/get_all/' def a(): try:",
"# import uvloop # import numpy as np # from tqdm import tqdm",
"for page in pages] # # responses = [await t for t in",
"htmls).get() # # print(parse_jobs.get()) # results = [j.get() for j in parse_jobs] #",
"x*x # result_list = [] # def log_result(result): # # This is called",
"# page = 1 # # asyncio.create_task(download(fut, 1, page)) # # if page",
"results = pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) # results = [j.get() for j",
"async def crawl(url, session): # r = await session.get(url) # html = await",
"a(): try: resp = requests.get(url) except Exception as e: print(f'url: {url}, error: {e}')",
"time # import random # import multiprocessing # import aiomultiprocess # import uvloop",
"# pool.close() # pool.join() # print(result_list) # if __name__ == '__main__': # cost",
"requests.get(url) except Exception as e: print(f'url: {url}, error: {e}') return pd.DataFrame() proxy_list_string =",
"\", time.time() - t1) import requests import json import pandas as pd url",
"result of future') # # all_done.set_result('the result') # # event_loop = asyncio.get_event_loop() #",
"i in range(10): # pool.apply_async(foo_pool, args = (i, ), callback = log_result) #",
"# async for result in pool.map(download, urls): # # pbar.update() # # async",
"# # def on_finish(future, n): # # print('{}: future done: {}'.format(n, future.result())) #",
"Run \"set_after()\" coroutine in a parallel Task. # # # We are using",
"# # 回调函数 # # def on_finish(task): # # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常",
"title, page_urls, url in results: # # print(count, title, url) # unseen.update(page_urls -",
"# parse_jobs = [pool.apply_async(parse, args=(html,)) for html in htmls] # results = pool.map(parse,",
"result. # # result_list is modified only by the main process, not the",
"pool.map(download, urls): # # pbar.update() # # async def schedule(): # # pages",
"in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if __name__ == '__main__': # # uvloop.install()",
"asyncio.sleep(delay) # # # Set *value* as a result of *fut* Future. #",
"Create a new Future object. # # # fut = loop.create_future() # #",
"0: # print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url, session)) for url in unseen]",
"of future') # # all_done.set_result('the result') # # event_loop = asyncio.get_event_loop() # #",
"import aiohttp # import asyncio # import time # from bs4 import BeautifulSoup",
"= (i, ), callback = log_result) # pool.close() # pool.join() # print(result_list) #",
"async with aiohttp.ClientSession() as session: # count = 1 # while len(unseen) !=",
"'__main__': # cost = time.time() # apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3))) #",
"'http://127.0.0.1:5010/get_all/' def a(): try: resp = requests.get(url) except Exception as e: print(f'url: {url},",
"loop. # # # loop = asyncio.get_running_loop() # # # Create a new",
"# if page > 5: # # return # # async def main(all_done):",
"time cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing as mp # import time #",
"await session.get(url) # html = await r.text() # await asyncio.sleep(0.1) # slightly delay",
"as e: print(f'url: {url}, error: {e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy",
"'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix, page) for page in pages] # #",
"下载协程 # # async def download(url): # # cost = time.time() # #",
"# pool.join() # print(result_list) # if __name__ == '__main__': # cost = time.time()",
"# all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page += 1 # # if page >",
"# soup = BeautifulSoup(html, 'lxml') # urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title",
"# unseen.update(page_urls - seen) # count += 1 # if __name__ == \"__main__\":",
"second) and print it. # # print(await fut) # # asyncio.run(main()) # import",
"Exception as e: print(f'url: {url}, error: {e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content) for",
"using the low-level \"loop.create_task()\" API here because # # # we already have",
"- t1) import requests import json import pandas as pd url = 'http://127.0.0.1:5010/get_all/'",
"# asyncio.run(main()) # import aiohttp # import asyncio # import time # from",
"page))) for page in pages] # # responses = [await t for t",
"import multiprocessing as mp # import time # async def foo_pool(x): # await",
"apply_async_with_callback(): # pool = mp.Pool(processes=3) # for i in range(10): # pool.apply_async(foo_pool, args",
"for page in pages] # # # url_chunks = np.array_split(urls ,5) # #",
"page > 5: # # break # # # Wait until *fut* has",
"# import time # async def foo_pool(x): # await asyncio.sleep(2) # return x*x",
"# return title, page_urls, url # async def crawl(url, session): # r =",
"{}'.format(round(time.time()-cost, 3)) # # # 回调函数 # # def on_finish(task): # # print('下载完成:',",
"callback = log_result) # pool.close() # pool.join() # print(result_list) # if __name__ ==",
"base_url = \"https://morvanzhou.github.io/\" # seen = set() # unseen = set([base_url]) # def",
"page in pages] # # # url_chunks = np.array_split(urls ,5) # # with",
"Crawling...') # tasks = [loop.create_task(crawl(url, session)) for url in unseen] # finished, unfinished",
"# # 下载协程 # # async def download(url): # # cost = time.time()",
"page = 1 # # asyncio.create_task(download(fut, 1, page)) # # if page >",
"# # asyncio.create_task(download(fut, 1, page)) # # if page > 5: # #",
"# while True: # # page = 1 # # asyncio.create_task(download(fut, 1, page))",
"on_finish(future, n): # # print('{}: future done: {}'.format(n, future.result())) # # async def",
"urljoin # import re # import multiprocessing as mp # base_url = \"https://morvanzhou.github.io/\"",
"# results = [j.get() for j in parse_jobs] # # print(results) # print('\\nAnalysing...')",
"# result_list = [] # def log_result(result): # # This is called whenever",
"aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # # async for result in pool.map(download, urls): #",
"for url_chunk in urls: # # pool.apply_async(download, args = (url_chunk, ), callback =",
"# 下载协程 # # async def download(url): # # cost = time.time() #",
"'cost: {}'.format(round(time.time()-cost, 3)) # # # 回调函数 # # def on_finish(task): # #",
"# all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # # finally: # # event_loop.close()",
"return x*x # result_list = [] # def log_result(result): # # This is",
"# apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3))) # # def on_finish(future, n): #",
"# # Wait until *fut* has a result (1 second) and print it.",
"import time # from bs4 import BeautifulSoup # from urllib.request import urljoin #",
"*fut* has a result (1 second) and print it. # # print(await fut)",
"# count = 1 # while len(unseen) != 0: # print('\\nAsync Crawling...') #",
"finished, unfinished = await asyncio.wait(tasks) # htmls = [f.result() for f in finished]",
"# # urls = ['{}{}'.format(prefix, page) for page in pages] # # #",
"# loop.close() # print(\"Async total time: \", time.time() - t1) import requests import",
"a result. # # result_list is modified only by the main process, not",
"event loop. # # # loop = asyncio.get_running_loop() # # # Create a",
"result (1 second) and print it. # # print(await fut) # # asyncio.run(main())",
"unseen = set([base_url]) # def parse(html): # soup = BeautifulSoup(html, 'lxml') # urls",
"\"https://morvanzhou.github.io/\" # seen = set() # unseen = set([base_url]) # def parse(html): #",
"download(url): # # cost = time.time() # # await asyncio.sleep(3) # 模拟1秒的下载过程 #",
"in unseen] # finished, unfinished = await asyncio.wait(tasks) # htmls = [f.result() for",
"# finished, unfinished = await asyncio.wait(tasks) # htmls = [f.result() for f in",
"= pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) # results = [j.get() for j in",
"# print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() # for title, page_urls, url in results:",
"# # we already have a reference to the event loop at hand.",
"# pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # # tasks =",
"import requests import json import pandas as pd url = 'http://127.0.0.1:5010/get_all/' def a():",
"json import pandas as pd url = 'http://127.0.0.1:5010/get_all/' def a(): try: resp =",
"and print it. # # print(await fut) # # asyncio.run(main()) # import aiohttp",
"page += 1 # # if page > 5: # # return #",
"(i, ), callback = log_result) # pool.close() # pool.join() # print(result_list) # if",
"for url in unseen] # finished, unfinished = await asyncio.wait(tasks) # htmls =",
"# async with aiohttp.ClientSession() as session: # count = 1 # while len(unseen)",
"return title, page_urls, url # async def crawl(url, session): # r = await",
"# seen.update(unseen) # unseen.clear() # for title, page_urls, url in results: # #",
"while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page += 1 # #",
"# # result_list is modified only by the main process, not the pool",
"(url_chunk, ), callback = on_finish) # # async def aio_mp_schedule(): # # pages",
"import BeautifulSoup # from urllib.request import urljoin # import re # import multiprocessing",
"cost = time.time() # # await asyncio.sleep(3) # 模拟1秒的下载过程 # # return 'cost:",
"htmls] # results = pool.map(parse, htmls) # # results = pool.map_async(parse, htmls).get() #",
"url_chunk in urls: # # pool.apply_async(download, args = (url_chunk, ), callback = on_finish)",
"Future object. # # # fut = loop.create_future() # # # Run \"set_after()\"",
"# count += 1 # if __name__ == \"__main__\": # t1 = time.time()",
"time.time() # loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total time:",
"# # all_done.set_result('the result') # # event_loop = asyncio.get_event_loop() # # try: #",
"), callback = log_result) # pool.close() # pool.join() # print(result_list) # if __name__",
"# result_list.append(result) # print(result) # def apply_async_with_callback(): # pool = mp.Pool(processes=3) # for",
"import uvloop # import numpy as np # from tqdm import tqdm #",
"# from tqdm import tqdm # # # 下载协程 # # async def",
"def apply_async_with_callback(): # pool = mp.Pool(processes=3) # for i in range(10): # pool.apply_async(foo_pool,",
"responses = [await t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if",
"# # prefix = 'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix, page) for page",
"# # event_loop.close() # # async def download(fut, delay, value): # # cost",
"range(10): # pool.apply_async(foo_pool, args = (i, ), callback = log_result) # pool.close() #",
"# # uvloop.install() # # cost = time.time() # # # asyncio.run(schedule()) #",
"set() # unseen = set([base_url]) # def parse(html): # soup = BeautifulSoup(html, 'lxml')",
"already have a reference to the event loop at hand. # # #",
"np # from tqdm import tqdm # # # 下载协程 # # async",
"# page = 1 # # while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) #",
"reference to the event loop at hand. # # # Otherwise we could",
"await asyncio.wait(tasks) # htmls = [f.result() for f in finished] # print('\\nDistributed Parsing...')",
"in finished] # print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,)) for html in",
"# # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # # def mp_schedule(): # # pages",
"# asyncio.create_task(download(fut, 1, page)) # # if page > 5: # # break",
"here because # # # we already have a reference to the event",
"# # responses = [await t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] #",
"with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # # async for result in pool.map(download, urls):",
"[j.get() for j in parse_jobs] # # print(results) # print('\\nAnalysing...') # seen.update(unseen) #",
"# async def foo_pool(x): # await asyncio.sleep(2) # return x*x # result_list =",
"== \"__main__\": # t1 = time.time() # loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) #",
"# print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # # def mp_schedule(): # # pages =",
"returns a result. # # result_list is modified only by the main process,",
"['{}{}'.format(prefix, page) for page in pages] # # pbar = tqdm(total=len(urls), ncols=80) #",
"for *delay* seconds. # # await asyncio.sleep(delay) # # # Set *value* as",
"# from urllib.request import urljoin # import re # import multiprocessing as mp",
"== '__main__': # # uvloop.install() # # cost = time.time() # # #",
"# # # Set *value* as a result of *fut* Future. # #",
"seen = set() # unseen = set([base_url]) # def parse(html): # soup =",
"# unseen.clear() # for title, page_urls, url in results: # # print(count, title,",
"# # print('{}: future done: {}'.format(n, future.result())) # # async def register_callbacks(all_done): #",
"1 # if __name__ == \"__main__\": # t1 = time.time() # loop =",
"['{}{}'.format(prefix, page) for page in pages] # # # url_chunks = np.array_split(urls ,5)",
"pool.close() # pool.join() # print(result_list) # if __name__ == '__main__': # cost =",
"BeautifulSoup # from urllib.request import urljoin # import re # import multiprocessing as",
"# # Otherwise we could have just used \"asyncio.create_task()\". # # while True:",
"print(await fut) # # asyncio.run(main()) # import aiohttp # import asyncio # import",
"list(range(500)) # # prefix = 'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix, page) for",
"all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page += 1 # # if page > 5:",
"[loop.create_task(crawl(url, session)) for url in unseen] # finished, unfinished = await asyncio.wait(tasks) #",
"loop.create_future() # # # Run \"set_after()\" coroutine in a parallel Task. # #",
"callbacks on future') # # page = 1 # # while True: #",
"for url in urls]) # url = soup.find('meta', {'property': \"og:url\"})['content'] # return title,",
"# # async def register_callbacks(all_done): # # print('registering callbacks on future') # #",
"# print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url, session)) for url in unseen] #",
"tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages] # # responses = [await",
"page_urls, url # async def crawl(url, session): # r = await session.get(url) #",
"# 回调函数 # # def on_finish(task): # # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 #",
"url in results: # # print(count, title, url) # unseen.update(page_urls - seen) #",
"Get the current event loop. # # # loop = asyncio.get_running_loop() # #",
"import time # async def foo_pool(x): # await asyncio.sleep(2) # return x*x #",
"title = soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href']) for url in urls]) #",
"import pandas as pd url = 'http://127.0.0.1:5010/get_all/' def a(): try: resp = requests.get(url)",
"# # print(await fut) # # asyncio.run(main()) # import aiohttp # import asyncio",
"asyncio # import functools # import time # import random # import multiprocessing",
"# processes = 8 # pool = mp.Pool(processes) # slightly affected # async",
"# import aiohttp # import asyncio # import time # from bs4 import",
"# # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # # async for result",
"of *fut* Future. # # fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3))) # #",
"await asyncio.sleep(0.1) # slightly delay for downloading # return html # async def",
"html in htmls] # results = pool.map(parse, htmls) # # results = pool.map_async(parse,",
"# loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total time: \", time.time() - t1) import",
"from tqdm import tqdm # # # 下载协程 # # async def download(url):",
"__name__ == \"__main__\": # t1 = time.time() # loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop))",
"# # fut = loop.create_future() # # # Run \"set_after()\" coroutine in a",
"import aiomultiprocess # import uvloop # import numpy as np # from tqdm",
"# import random # import multiprocessing # import aiomultiprocess # import uvloop #",
"# url_chunks = np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5) as pool: # #",
"# print('registering callbacks on future') # # page = 1 # # while",
"event_loop.close() # # async def download(fut, delay, value): # # cost = time.time()",
"# await register_callbacks(all_done) # # print('setting result of future') # # all_done.set_result('the result')",
"session: # count = 1 # while len(unseen) != 0: # print('\\nAsync Crawling...')",
"count = 1 # while len(unseen) != 0: # print('\\nAsync Crawling...') # tasks",
"# import multiprocessing # import aiomultiprocess # import uvloop # import numpy as",
"# # cost = time.time() # # # asyncio.run(schedule()) # # mp_schedule() #",
"event_loop = asyncio.get_event_loop() # # try: # # all_done = asyncio.Future() # #",
"(1 second) and print it. # # print(await fut) # # asyncio.run(main()) #",
"# async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # # async for result in",
"# # # asyncio.run(schedule()) # # mp_schedule() # # print(\"total time cost: {}\".format(round(time.time()-cost,",
"in urls: # # pool.apply_async(download, args = (url_chunk, ), callback = on_finish) #",
"current event loop. # # # loop = asyncio.get_running_loop() # # # Create",
"urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url,",
"= set([urljoin(base_url, url['href']) for url in urls]) # url = soup.find('meta', {'property': \"og:url\"})['content']",
"import json import pandas as pd url = 'http://127.0.0.1:5010/get_all/' def a(): try: resp",
"async def aio_mp_schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/'",
"tqdm import tqdm # # # 下载协程 # # async def download(url): #",
"asyncio.sleep(2) # return x*x # result_list = [] # def log_result(result): # #",
"1 # while len(unseen) != 0: # print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url,",
"# # for url_chunk in urls: # # pool.apply_async(download, args = (url_chunk, ),",
"coroutine in a parallel Task. # # # We are using the low-level",
"asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # # finally: # # event_loop.close() # # async",
"soup = BeautifulSoup(html, 'lxml') # urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title =",
"= requests.get(url) except Exception as e: print(f'url: {url}, error: {e}') return pd.DataFrame() proxy_list_string",
"schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # #",
"print(result_list) # if __name__ == '__main__': # cost = time.time() # apply_async_with_callback() #",
"for html in htmls] # results = pool.map(parse, htmls) # # results =",
"def aio_mp_schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' #",
"# if page > 5: # # break # # # Wait until",
"delay for downloading # return html # async def main(loop): # processes =",
"# # # 下载协程 # # async def download(url): # # cost =",
"import time # import random # import multiprocessing # import aiomultiprocess # import",
"# # return 'cost: {}'.format(round(time.time()-cost, 3)) # # # 回调函数 # # def",
"+= 1 # # if page > 5: # # return # #",
"True: # # page = 1 # # asyncio.create_task(download(fut, 1, page)) # #",
"set([urljoin(base_url, url['href']) for url in urls]) # url = soup.find('meta', {'property': \"og:url\"})['content'] #",
"title, url) # unseen.update(page_urls - seen) # count += 1 # if __name__",
"pool = mp.Pool(processes) # slightly affected # async with aiohttp.ClientSession() as session: #",
"event_loop.run_until_complete(main(all_done)) # # finally: # # event_loop.close() # # async def download(fut, delay,",
"# pool.apply_async(foo_pool, args = (i, ), callback = log_result) # pool.close() # pool.join()",
"json.loads(resp.content) for proxy in proxy_list_string: print(proxy) # proxy_dict = json.loads(proxy) # print(proxy_dict) a()",
"urls = ['{}{}'.format(prefix, page) for page in pages] # # # url_chunks =",
"8 # pool = mp.Pool(processes) # slightly affected # async with aiohttp.ClientSession() as",
"{}\".format(round(time.time()-cost, 3))) # import multiprocessing as mp # import time # async def",
"tqdm(total=len(urls), ncols=80) # # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # # async",
"# await asyncio.sleep(delay) # # # Set *value* as a result of *fut*",
"total=len(tasks), ncols=80)] # # if __name__ == '__main__': # # uvloop.install() # #",
"# # # Wait until *fut* has a result (1 second) and print",
"# # fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3))) # # async def main():",
"# # mp_schedule() # # print(\"total time cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing",
"# pool = mp.Pool(processes) # slightly affected # async with aiohttp.ClientSession() as session:",
"[] # def log_result(result): # # This is called whenever foo_pool(i) returns a",
"# from bs4 import BeautifulSoup # from urllib.request import urljoin # import re",
"seen.update(unseen) # unseen.clear() # for title, page_urls, url in results: # # print(count,",
"multiprocessing as mp # base_url = \"https://morvanzhou.github.io/\" # seen = set() # unseen",
"pool: # # async for result in pool.map(download, urls): # # pbar.update() #",
"t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if __name__ == '__main__':",
"as np # from tqdm import tqdm # # # 下载协程 # #",
"have just used \"asyncio.create_task()\". # # while True: # # page = 1",
"# while len(unseen) != 0: # print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url, session))",
"async def download(url): # # cost = time.time() # # await asyncio.sleep(3) #",
"import tqdm # # # 下载协程 # # async def download(url): # #",
"\"asyncio.create_task()\". # # while True: # # page = 1 # # asyncio.create_task(download(fut,",
"results: # # print(count, title, url) # unseen.update(page_urls - seen) # count +=",
"# import asyncio # import functools # import time # import random #",
"# # prefix = 'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page",
"foo_pool(x): # await asyncio.sleep(2) # return x*x # result_list = [] # def",
"# print(\"total cost: {}\".format(round(time.time()-cost, 3))) # # def on_finish(future, n): # # print('{}:",
"def a(): try: resp = requests.get(url) except Exception as e: print(f'url: {url}, error:",
"# # url_chunks = np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5) as pool: #",
"from bs4 import BeautifulSoup # from urllib.request import urljoin # import re #",
"url in urls]) # url = soup.find('meta', {'property': \"og:url\"})['content'] # return title, page_urls,",
"Set *value* as a result of *fut* Future. # # fut.set_result('task: {} cost:",
"mp # base_url = \"https://morvanzhou.github.io/\" # seen = set() # unseen = set([base_url])",
"if __name__ == '__main__': # # uvloop.install() # # cost = time.time() #",
"return # # async def main(all_done): # # await register_callbacks(all_done) # # print('setting",
"# Otherwise we could have just used \"asyncio.create_task()\". # # while True: #",
"fut) # # asyncio.run(main()) # import aiohttp # import asyncio # import time",
"async def main(loop): # processes = 8 # pool = mp.Pool(processes) # slightly",
"f in finished] # print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,)) for html",
"= set() # unseen = set([base_url]) # def parse(html): # soup = BeautifulSoup(html,",
"r = await session.get(url) # html = await r.text() # await asyncio.sleep(0.1) #",
"= mp.Pool(processes) # slightly affected # async with aiohttp.ClientSession() as session: # count",
"Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,)) for html in htmls] # results =",
"), callback = on_finish) # # async def aio_mp_schedule(): # # pages =",
"cost = time.time() # # # asyncio.run(schedule()) # # mp_schedule() # # print(\"total",
"# # # Get the current event loop. # # # loop =",
"= set([base_url]) # def parse(html): # soup = BeautifulSoup(html, 'lxml') # urls =",
"random # import multiprocessing # import aiomultiprocess # import uvloop # import numpy",
"import random # import multiprocessing # import aiomultiprocess # import uvloop # import",
"is modified only by the main process, not the pool workers. # result_list.append(result)",
"if page > 5: # # return # # async def main(all_done): #",
"aiohttp # import asyncio # import time # from bs4 import BeautifulSoup #",
"pages] # # pbar = tqdm(total=len(urls), ncols=80) # # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop)",
"page)) # # if page > 5: # # break # # #",
"soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href']) for",
"import multiprocessing # import aiomultiprocess # import uvloop # import numpy as np",
"print(\"total time cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing as mp # import time",
"args = (i, ), callback = log_result) # pool.close() # pool.join() # print(result_list)",
"seen) # count += 1 # if __name__ == \"__main__\": # t1 =",
"# # def mp_schedule(): # # pages = list(range(500)) # # prefix =",
"print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # # def mp_schedule(): # # pages = list(range(500))",
"asyncio.create_task(download(fut, 1, page)) # # if page > 5: # # break #",
"value): # # cost = time.time() # # # Sleep for *delay* seconds.",
"# fut = loop.create_future() # # # Run \"set_after()\" coroutine in a parallel",
"urls: # # pool.apply_async(download, args = (url_chunk, ), callback = on_finish) # #",
"# event_loop.close() # # async def download(fut, delay, value): # # cost =",
"1, page)) # # if page > 5: # # break # #",
"{}'.format(n, future.result())) # # async def register_callbacks(all_done): # # print('registering callbacks on future')",
"We are using the low-level \"loop.create_task()\" API here because # # # we",
"# # Set *value* as a result of *fut* Future. # # fut.set_result('task:",
"# # # Create a new Future object. # # # fut =",
"multiprocessing.Pool(processes=5) as pool: # # for url_chunk in urls: # # pool.apply_async(download, args",
"# # print(\"total time cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing as mp #",
"import re # import multiprocessing as mp # base_url = \"https://morvanzhou.github.io/\" # seen",
"aio_mp_schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # #",
"resp = requests.get(url) except Exception as e: print(f'url: {url}, error: {e}') return pd.DataFrame()",
"all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # # finally: # # event_loop.close() #",
"# # while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page += 1",
"args = (url_chunk, ), callback = on_finish) # # async def aio_mp_schedule(): #",
"prefix = 'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages]",
"we already have a reference to the event loop at hand. # #",
"# async def crawl(url, session): # r = await session.get(url) # html =",
"# # while True: # # page = 1 # # asyncio.create_task(download(fut, 1,",
"= soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href']) for url in urls]) # url",
"# uvloop.install() # # cost = time.time() # # # asyncio.run(schedule()) # #",
"= asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total time: \", time.time() -",
"loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total time: \", time.time() - t1) import requests",
"could have just used \"asyncio.create_task()\". # # while True: # # page =",
"t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if __name__ == '__main__': # #",
"result') # # event_loop = asyncio.get_event_loop() # # try: # # all_done =",
"# def log_result(result): # # This is called whenever foo_pool(i) returns a result.",
"# pbar.update() # # async def schedule(): # # pages = list(range(500)) #",
"# # page += 1 # # if page > 5: # #",
"# import re # import multiprocessing as mp # base_url = \"https://morvanzhou.github.io/\" #",
"# break # # # Wait until *fut* has a result (1 second)",
"called whenever foo_pool(i) returns a result. # # result_list is modified only by",
"# # return # # async def main(all_done): # # await register_callbacks(all_done) #",
"re # import multiprocessing as mp # base_url = \"https://morvanzhou.github.io/\" # seen =",
"just used \"asyncio.create_task()\". # # while True: # # page = 1 #",
"future') # # page = 1 # # while True: # # all_done.add_done_callback(functools.partial(on_finish,",
"= 'http://127.0.0.1:5010/get_all/' def a(): try: resp = requests.get(url) except Exception as e: print(f'url:",
"= tqdm(total=len(urls), ncols=80) # # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # #",
"print it. # # print(await fut) # # asyncio.run(main()) # import aiohttp #",
"# print(await fut) # # asyncio.run(main()) # import aiohttp # import asyncio #",
"= [] # def log_result(result): # # This is called whenever foo_pool(i) returns",
"in pages] # # pbar = tqdm(total=len(urls), ncols=80) # # async with aiomultiprocess.Pool(processes=5,",
"{}'.format(value, round(time.time()-cost, 3))) # # async def main(): # # # Get the",
"# # Get the current event loop. # # # loop = asyncio.get_running_loop()",
"error: {e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy in proxy_list_string: print(proxy) #",
"# html = await r.text() # await asyncio.sleep(0.1) # slightly delay for downloading",
"# for title, page_urls, url in results: # # print(count, title, url) #",
"count += 1 # if __name__ == \"__main__\": # t1 = time.time() #",
"url = 'http://127.0.0.1:5010/get_all/' def a(): try: resp = requests.get(url) except Exception as e:",
"*value* as a result of *fut* Future. # # fut.set_result('task: {} cost: {}'.format(value,",
"pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy in proxy_list_string: print(proxy) # proxy_dict = json.loads(proxy)",
"print(\"total cost: {}\".format(round(time.time()-cost, 3))) # # def on_finish(future, n): # # print('{}: future",
"parse(html): # soup = BeautifulSoup(html, 'lxml') # urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) #",
"soup.find('meta', {'property': \"og:url\"})['content'] # return title, page_urls, url # async def crawl(url, session):",
"result_list = [] # def log_result(result): # # This is called whenever foo_pool(i)",
"main(): # # # Get the current event loop. # # # loop",
"# # if page > 5: # # break # # # Wait",
"# unseen = set([base_url]) # def parse(html): # soup = BeautifulSoup(html, 'lxml') #",
"= on_finish) # # async def aio_mp_schedule(): # # pages = list(range(500)) #",
"finally: # # event_loop.close() # # async def download(fut, delay, value): # #",
"future.result())) # # async def register_callbacks(all_done): # # print('registering callbacks on future') #",
"a parallel Task. # # # We are using the low-level \"loop.create_task()\" API",
"# urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() # page_urls =",
"def register_callbacks(all_done): # # print('registering callbacks on future') # # page = 1",
"for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if __name__ == '__main__': #",
"for f in finished] # print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,)) for",
"# return # # async def main(all_done): # # await register_callbacks(all_done) # #",
"# return html # async def main(loop): # processes = 8 # pool",
"{\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href']) for url",
"try: resp = requests.get(url) except Exception as e: print(f'url: {url}, error: {e}') return",
"is called whenever foo_pool(i) returns a result. # # result_list is modified only",
"pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix,",
"# try: # # all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # # finally:",
"ncols=80) # # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # # async for",
"process, not the pool workers. # result_list.append(result) # print(result) # def apply_async_with_callback(): #",
"pool = mp.Pool(processes=3) # for i in range(10): # pool.apply_async(foo_pool, args = (i,",
"# Sleep for *delay* seconds. # # await asyncio.sleep(delay) # # # Set",
"a result (1 second) and print it. # # print(await fut) # #",
"This is called whenever foo_pool(i) returns a result. # # result_list is modified",
"# # if __name__ == '__main__': # # uvloop.install() # # cost =",
"# print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,)) for html in htmls] #",
"# # await register_callbacks(all_done) # # print('setting result of future') # # all_done.set_result('the",
"= asyncio.get_running_loop() # # # Create a new Future object. # # #",
"# print('{}: future done: {}'.format(n, future.result())) # # async def register_callbacks(all_done): # #",
"def parse(html): # soup = BeautifulSoup(html, 'lxml') # urls = soup.find_all('a', {\"href\": re.compile('^/.+?/$')})",
"in results: # # print(count, title, url) # unseen.update(page_urls - seen) # count",
"pd url = 'http://127.0.0.1:5010/get_all/' def a(): try: resp = requests.get(url) except Exception as",
"# asyncio.run(schedule()) # # mp_schedule() # # print(\"total time cost: {}\".format(round(time.time()-cost, 3))) #",
"# # async for result in pool.map(download, urls): # # pbar.update() # #",
"# # async def schedule(): # # pages = list(range(500)) # # prefix",
"[f.result() for f in finished] # print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,))",
"# # cost = time.time() # # await asyncio.sleep(3) # 模拟1秒的下载过程 # #",
"# import asyncio # import time # from bs4 import BeautifulSoup # from",
"new Future object. # # # fut = loop.create_future() # # # Run",
"log_result(result): # # This is called whenever foo_pool(i) returns a result. # #",
"= 'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix, page) for page in pages] #",
"= time.time() # # # asyncio.run(schedule()) # # mp_schedule() # # print(\"total time",
"result in pool.map(download, urls): # # pbar.update() # # async def schedule(): #",
"not the pool workers. # result_list.append(result) # print(result) # def apply_async_with_callback(): # pool",
"# t1 = time.time() # loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() #",
"time # async def foo_pool(x): # await asyncio.sleep(2) # return x*x # result_list",
"3)) # # # 回调函数 # # def on_finish(task): # # print('下载完成:', task.result())",
"tqdm # # # 下载协程 # # async def download(url): # # cost",
"# async def register_callbacks(all_done): # # print('registering callbacks on future') # # page",
"# # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages] # # responses",
"pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) # results = [j.get() for j in parse_jobs]",
"time.time() # # # Sleep for *delay* seconds. # # await asyncio.sleep(delay) #",
"have a reference to the event loop at hand. # # # Otherwise",
"j in parse_jobs] # # print(results) # print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() #",
"time.time() # # await asyncio.sleep(3) # 模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost, 3))",
"as session: # count = 1 # while len(unseen) != 0: # print('\\nAsync",
"asyncio.run(main()) # import aiohttp # import asyncio # import time # from bs4",
"the main process, not the pool workers. # result_list.append(result) # print(result) # def",
"= json.loads(resp.content) for proxy in proxy_list_string: print(proxy) # proxy_dict = json.loads(proxy) # print(proxy_dict)",
"True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page += 1 # # if",
"loop = asyncio.get_running_loop() # # # Create a new Future object. # #",
"log_result) # pool.close() # pool.join() # print(result_list) # if __name__ == '__main__': #",
"# 模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost, 3)) # # # 回调函数 #",
"asyncio.get_running_loop() # # # Create a new Future object. # # # fut",
"3))) # # async def main(): # # # Get the current event",
"# Get the current event loop. # # # loop = asyncio.get_running_loop() #",
"results = pool.map(parse, htmls) # # results = pool.map_async(parse, htmls).get() # # print(parse_jobs.get())",
"{'property': \"og:url\"})['content'] # return title, page_urls, url # async def crawl(url, session): #",
"asyncio.run(schedule()) # # mp_schedule() # # print(\"total time cost: {}\".format(round(time.time()-cost, 3))) # import",
"are using the low-level \"loop.create_task()\" API here because # # # we already",
"# # all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # # finally: # #",
"# # print('registering callbacks on future') # # page = 1 # #",
"result_list is modified only by the main process, not the pool workers. #",
"# We are using the low-level \"loop.create_task()\" API here because # # #",
"aiomultiprocess # import uvloop # import numpy as np # from tqdm import",
"register_callbacks(all_done): # # print('registering callbacks on future') # # page = 1 #",
"import asyncio # import functools # import time # import random # import",
"async def register_callbacks(all_done): # # print('registering callbacks on future') # # page =",
"set([base_url]) # def parse(html): # soup = BeautifulSoup(html, 'lxml') # urls = soup.find_all('a',",
"# import multiprocessing as mp # base_url = \"https://morvanzhou.github.io/\" # seen = set()",
"pool.map(parse, htmls) # # results = pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) # results",
"as mp # base_url = \"https://morvanzhou.github.io/\" # seen = set() # unseen =",
"until *fut* has a result (1 second) and print it. # # print(await",
"in a parallel Task. # # # We are using the low-level \"loop.create_task()\"",
"in parse_jobs] # # print(results) # print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() # for",
"asyncio.sleep(3) # 模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost, 3)) # # # 回调函数",
"len(unseen) != 0: # print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url, session)) for url",
"Future. # # fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3))) # # async def",
"# cost = time.time() # # # Sleep for *delay* seconds. # #",
"\"loop.create_task()\" API here because # # # we already have a reference to",
"n): # # print('{}: future done: {}'.format(n, future.result())) # # async def register_callbacks(all_done):",
"await asyncio.sleep(3) # 模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost, 3)) # # #",
"all_done.set_result('the result') # # event_loop = asyncio.get_event_loop() # # try: # # all_done",
"unseen.clear() # for title, page_urls, url in results: # # print(count, title, url)",
"= asyncio.get_event_loop() # # try: # # all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done))",
"= asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # # finally: # # event_loop.close() # #",
"while True: # # page = 1 # # asyncio.create_task(download(fut, 1, page)) #",
"apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3))) # # def on_finish(future, n): # #",
"if __name__ == '__main__': # cost = time.time() # apply_async_with_callback() # print(\"total cost:",
"Otherwise we could have just used \"asyncio.create_task()\". # # while True: # #",
"async def download(fut, delay, value): # # cost = time.time() # # #",
"np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5) as pool: # # for url_chunk in",
"for result in pool.map(download, urls): # # pbar.update() # # async def schedule():",
"# # cost = time.time() # # # Sleep for *delay* seconds. #",
"# # asyncio.run(main()) # import aiohttp # import asyncio # import time #",
"at hand. # # # Otherwise we could have just used \"asyncio.create_task()\". #",
"def foo_pool(x): # await asyncio.sleep(2) # return x*x # result_list = [] #",
"the event loop at hand. # # # Otherwise we could have just",
"the pool workers. # result_list.append(result) # print(result) # def apply_async_with_callback(): # pool =",
"def main(loop): # processes = 8 # pool = mp.Pool(processes) # slightly affected",
"# # page = 1 # # while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page))",
"# cost = time.time() # # await asyncio.sleep(3) # 模拟1秒的下载过程 # # return",
"# mp_schedule() # # print(\"total time cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing as",
"page in pages] # # responses = [await t for t in tqdm(asyncio.as_completed(tasks),",
"# await asyncio.sleep(0.1) # slightly delay for downloading # return html # async",
"# def apply_async_with_callback(): # pool = mp.Pool(processes=3) # for i in range(10): #",
"# return 'cost: {}'.format(round(time.time()-cost, 3)) # # # 回调函数 # # def on_finish(task):",
"urls): # # pbar.update() # # async def schedule(): # # pages =",
"url in unseen] # finished, unfinished = await asyncio.wait(tasks) # htmls = [f.result()",
"# # # Run \"set_after()\" coroutine in a parallel Task. # # #",
"future done: {}'.format(n, future.result())) # # async def register_callbacks(all_done): # # print('registering callbacks",
"as mp # import time # async def foo_pool(x): # await asyncio.sleep(2) #",
"await asyncio.sleep(delay) # # # Set *value* as a result of *fut* Future.",
"urls = ['{}{}'.format(prefix, page) for page in pages] # # pbar = tqdm(total=len(urls),",
"= soup.find('meta', {'property': \"og:url\"})['content'] # return title, page_urls, url # async def crawl(url,",
"= \"https://morvanzhou.github.io/\" # seen = set() # unseen = set([base_url]) # def parse(html):",
"in pages] # # # url_chunks = np.array_split(urls ,5) # # with multiprocessing.Pool(processes=5)",
"modified only by the main process, not the pool workers. # result_list.append(result) #",
"def main(all_done): # # await register_callbacks(all_done) # # print('setting result of future') #",
"# # break # # # Wait until *fut* has a result (1",
"foo_pool(i) returns a result. # # result_list is modified only by the main",
"with aiohttp.ClientSession() as session: # count = 1 # while len(unseen) != 0:",
"mp.Pool(processes) # slightly affected # async with aiohttp.ClientSession() as session: # count =",
"# # # loop = asyncio.get_running_loop() # # # Create a new Future",
"# # urls = ['{}{}'.format(prefix, page) for page in pages] # # pbar",
"3))) # import multiprocessing as mp # import time # async def foo_pool(x):",
"ncols=80)] # # if __name__ == '__main__': # # uvloop.install() # # cost",
"# Run \"set_after()\" coroutine in a parallel Task. # # # We are",
",5) # # with multiprocessing.Pool(processes=5) as pool: # # for url_chunk in urls:",
"import asyncio # import time # from bs4 import BeautifulSoup # from urllib.request",
"# print(\"total time cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing as mp # import",
"parse_jobs = [pool.apply_async(parse, args=(html,)) for html in htmls] # results = pool.map(parse, htmls)",
"# # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # # tasks",
"# # async def main(): # # # Get the current event loop.",
"pool.join() # print(result_list) # if __name__ == '__main__': # cost = time.time() #",
"# # # fut = loop.create_future() # # # Run \"set_after()\" coroutine in",
"# r = await session.get(url) # html = await r.text() # await asyncio.sleep(0.1)",
"async def foo_pool(x): # await asyncio.sleep(2) # return x*x # result_list = []",
"in urls]) # url = soup.find('meta', {'property': \"og:url\"})['content'] # return title, page_urls, url",
"# prefix = 'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix, page) for page in",
"{e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy in proxy_list_string: print(proxy) # proxy_dict",
"# def on_finish(future, n): # # print('{}: future done: {}'.format(n, future.result())) # #",
"{} cost: {}'.format(value, round(time.time()-cost, 3))) # # async def main(): # # #",
"title, page_urls, url # async def crawl(url, session): # r = await session.get(url)",
"pool.apply_async(foo_pool, args = (i, ), callback = log_result) # pool.close() # pool.join() #",
"for i in range(10): # pool.apply_async(foo_pool, args = (i, ), callback = log_result)",
"time.time() # # # asyncio.run(schedule()) # # mp_schedule() # # print(\"total time cost:",
"asyncio.sleep(0.1) # slightly delay for downloading # return html # async def main(loop):",
"await asyncio.sleep(2) # return x*x # result_list = [] # def log_result(result): #",
"a result of *fut* Future. # # fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3)))",
"mp # import time # async def foo_pool(x): # await asyncio.sleep(2) # return",
"loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total time: \", time.time()",
"mp_schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # #",
"seconds. # # await asyncio.sleep(delay) # # # Set *value* as a result",
"processes = 8 # pool = mp.Pool(processes) # slightly affected # async with",
"# async def download(url): # # cost = time.time() # # await asyncio.sleep(3)",
"page_urls, url in results: # # print(count, title, url) # unseen.update(page_urls - seen)",
"# # all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page += 1 # # if page",
"# # event_loop.run_until_complete(main(all_done)) # # finally: # # event_loop.close() # # async def",
"# # finally: # # event_loop.close() # # async def download(fut, delay, value):",
"print(parse_jobs.get()) # results = [j.get() for j in parse_jobs] # # print(results) #",
"loop_initializer=uvloop.new_event_loop) as pool: # # async for result in pool.map(download, urls): # #",
"for j in parse_jobs] # # print(results) # print('\\nAnalysing...') # seen.update(unseen) # unseen.clear()",
"= [j.get() for j in parse_jobs] # # print(results) # print('\\nAnalysing...') # seen.update(unseen)",
"[await t for t in tqdm(asyncio.as_completed(tasks), total=len(tasks), ncols=80)] # # if __name__ ==",
"multiprocessing as mp # import time # async def foo_pool(x): # await asyncio.sleep(2)",
"time: \", time.time() - t1) import requests import json import pandas as pd",
"!= 0: # print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url, session)) for url in",
"# import functools # import time # import random # import multiprocessing #",
"workers. # result_list.append(result) # print(result) # def apply_async_with_callback(): # pool = mp.Pool(processes=3) #",
"# await asyncio.sleep(3) # 模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost, 3)) # #",
"def log_result(result): # # This is called whenever foo_pool(i) returns a result. #",
"# # print(parse_jobs.get()) # results = [j.get() for j in parse_jobs] # #",
"import numpy as np # from tqdm import tqdm # # # 下载协程",
"time.time() - t1) import requests import json import pandas as pd url =",
"print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url, session)) for url in unseen] # finished,",
"done: {}'.format(n, future.result())) # # async def register_callbacks(all_done): # # print('registering callbacks on",
"# event_loop.run_until_complete(main(all_done)) # # finally: # # event_loop.close() # # async def download(fut,",
"\"__main__\": # t1 = time.time() # loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close()",
"htmls = [f.result() for f in finished] # print('\\nDistributed Parsing...') # parse_jobs =",
"html = await r.text() # await asyncio.sleep(0.1) # slightly delay for downloading #",
"{url}, error: {e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy in proxy_list_string: print(proxy)",
"cost: {}'.format(value, round(time.time()-cost, 3))) # # async def main(): # # # Get",
"# # try: # # all_done = asyncio.Future() # # event_loop.run_until_complete(main(all_done)) # #",
"# # async def aio_mp_schedule(): # # pages = list(range(500)) # # prefix",
"from urllib.request import urljoin # import re # import multiprocessing as mp #",
"# results = pool.map(parse, htmls) # # results = pool.map_async(parse, htmls).get() # #",
"htmls) # # results = pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) # results =",
"return 'cost: {}'.format(round(time.time()-cost, 3)) # # # 回调函数 # # def on_finish(task): #",
"asyncio # import time # from bs4 import BeautifulSoup # from urllib.request import",
"# # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' # # urls",
"async def schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/'",
"1 # # if page > 5: # # return # # async",
"= [loop.create_task(crawl(url, session)) for url in unseen] # finished, unfinished = await asyncio.wait(tasks)",
"# # async def main(all_done): # # await register_callbacks(all_done) # # print('setting result",
"'__main__': # # uvloop.install() # # cost = time.time() # # # asyncio.run(schedule())",
"def main(): # # # Get the current event loop. # # #",
"= [f.result() for f in finished] # print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse,",
"= await session.get(url) # html = await r.text() # await asyncio.sleep(0.1) # slightly",
"mp_schedule() # # print(\"total time cost: {}\".format(round(time.time()-cost, 3))) # import multiprocessing as mp",
"# await asyncio.sleep(2) # return x*x # result_list = [] # def log_result(result):",
"= time.time() # # # Sleep for *delay* seconds. # # await asyncio.sleep(delay)",
"= 'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages] #",
"parallel Task. # # # We are using the low-level \"loop.create_task()\" API here",
"def download(url): # # cost = time.time() # # await asyncio.sleep(3) # 模拟1秒的下载过程",
"slightly delay for downloading # return html # async def main(loop): # processes",
"unfinished = await asyncio.wait(tasks) # htmls = [f.result() for f in finished] #",
"pbar.update() # # async def schedule(): # # pages = list(range(500)) # #",
"# slightly delay for downloading # return html # async def main(loop): #",
"# result_list is modified only by the main process, not the pool workers.",
"*delay* seconds. # # await asyncio.sleep(delay) # # # Set *value* as a",
"# async def main(): # # # Get the current event loop. #",
"object. # # # fut = loop.create_future() # # # Run \"set_after()\" coroutine",
"# pbar = tqdm(total=len(urls), ncols=80) # # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool:",
"session): # r = await session.get(url) # html = await r.text() # await",
"'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for page in pages] # #",
"= time.time() # loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total",
"print(f'url: {url}, error: {e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy in proxy_list_string:",
"result of *fut* Future. # # fut.set_result('task: {} cost: {}'.format(value, round(time.time()-cost, 3))) #",
"# if __name__ == '__main__': # # uvloop.install() # # cost = time.time()",
"print('{}: future done: {}'.format(n, future.result())) # # async def register_callbacks(all_done): # # print('registering",
"if page > 5: # # break # # # Wait until *fut*",
"Wait until *fut* has a result (1 second) and print it. # #",
"# # await asyncio.sleep(3) # 模拟1秒的下载过程 # # return 'cost: {}'.format(round(time.time()-cost, 3)) #",
"e: print(f'url: {url}, error: {e}') return pd.DataFrame() proxy_list_string = json.loads(resp.content) for proxy in",
"url = soup.find('meta', {'property': \"og:url\"})['content'] # return title, page_urls, url # async def",
"while len(unseen) != 0: # print('\\nAsync Crawling...') # tasks = [loop.create_task(crawl(url, session)) for",
"cost = time.time() # apply_async_with_callback() # print(\"total cost: {}\".format(round(time.time()-cost, 3))) # # def",
"cost: {}\".format(round(time.time()-cost, 3))) # # def on_finish(future, n): # # print('{}: future done:",
"we could have just used \"asyncio.create_task()\". # # while True: # # page",
"Sleep for *delay* seconds. # # await asyncio.sleep(delay) # # # Set *value*",
"affected # async with aiohttp.ClientSession() as session: # count = 1 # while",
"for downloading # return html # async def main(loop): # processes = 8",
"# print('setting result of future') # # all_done.set_result('the result') # # event_loop =",
"import multiprocessing as mp # base_url = \"https://morvanzhou.github.io/\" # seen = set() #",
"prefix = 'https://yuerblog.cc/' # # urls = ['{}{}'.format(prefix, page) for page in pages]",
"callback = on_finish) # # async def aio_mp_schedule(): # # pages = list(range(500))",
"used \"asyncio.create_task()\". # # while True: # # page = 1 # #",
"r.text() # await asyncio.sleep(0.1) # slightly delay for downloading # return html #",
"if __name__ == \"__main__\": # t1 = time.time() # loop = asyncio.get_event_loop() #",
"# print(parse_jobs.get()) # results = [j.get() for j in parse_jobs] # # print(results)",
"# pool = mp.Pool(processes=3) # for i in range(10): # pool.apply_async(foo_pool, args =",
"the current event loop. # # # loop = asyncio.get_running_loop() # # #",
"= await asyncio.wait(tasks) # htmls = [f.result() for f in finished] # print('\\nDistributed",
"# # results = pool.map_async(parse, htmls).get() # # print(parse_jobs.get()) # results = [j.get()",
"result_list.append(result) # print(result) # def apply_async_with_callback(): # pool = mp.Pool(processes=3) # for i",
"# # pbar = tqdm(total=len(urls), ncols=80) # # async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as",
"= soup.find_all('a', {\"href\": re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href'])",
"html # async def main(loop): # processes = 8 # pool = mp.Pool(processes)",
"# async def schedule(): # # pages = list(range(500)) # # prefix =",
"# loop = asyncio.get_event_loop() # loop.run_until_complete(main(loop)) # loop.close() # print(\"Async total time: \",",
"- seen) # count += 1 # if __name__ == \"__main__\": # t1",
"unseen] # finished, unfinished = await asyncio.wait(tasks) # htmls = [f.result() for f",
"for page in pages] # # pbar = tqdm(total=len(urls), ncols=80) # # async",
"async with aiomultiprocess.Pool(processes=5, loop_initializer=uvloop.new_event_loop) as pool: # # async for result in pool.map(download,",
"pool workers. # result_list.append(result) # print(result) # def apply_async_with_callback(): # pool = mp.Pool(processes=3)",
"5: # # return # # async def main(all_done): # # await register_callbacks(all_done)",
"> 5: # # break # # # Wait until *fut* has a",
"= 1 # while len(unseen) != 0: # print('\\nAsync Crawling...') # tasks =",
"main(all_done): # # await register_callbacks(all_done) # # print('setting result of future') # #",
"# # This is called whenever foo_pool(i) returns a result. # # result_list",
"\"og:url\"})['content'] # return title, page_urls, url # async def crawl(url, session): # r",
"async def main(all_done): # # await register_callbacks(all_done) # # print('setting result of future')",
"session.get(url) # html = await r.text() # await asyncio.sleep(0.1) # slightly delay for",
"print('setting result of future') # # all_done.set_result('the result') # # event_loop = asyncio.get_event_loop()",
"= [pool.apply_async(parse, args=(html,)) for html in htmls] # results = pool.map(parse, htmls) #",
"# htmls = [f.result() for f in finished] # print('\\nDistributed Parsing...') # parse_jobs",
"list(range(500)) # # prefix = 'https://yuerblog.cc/' # # tasks = [asyncio.create_task(download('{}{}'.format(prefix, page))) for",
"re.compile('^/.+?/$')}) # title = soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href']) for url in",
"parse_jobs] # # print(results) # print('\\nAnalysing...') # seen.update(unseen) # unseen.clear() # for title,",
"to the event loop at hand. # # # Otherwise we could have",
"# # page = 1 # # asyncio.create_task(download(fut, 1, page)) # # if",
"on_finish(task): # # print('下载完成:', task.result()) # 获取协程返回值或者抛出的异常 # # def mp_schedule(): # #",
"{}\".format(round(time.time()-cost, 3))) # # def on_finish(future, n): # # print('{}: future done: {}'.format(n,",
"# # async def download(fut, delay, value): # # cost = time.time() #",
"= (url_chunk, ), callback = on_finish) # # async def aio_mp_schedule(): # #",
"finished] # print('\\nDistributed Parsing...') # parse_jobs = [pool.apply_async(parse, args=(html,)) for html in htmls]",
"uvloop.install() # # cost = time.time() # # # asyncio.run(schedule()) # # mp_schedule()",
"a reference to the event loop at hand. # # # Otherwise we",
"= 8 # pool = mp.Pool(processes) # slightly affected # async with aiohttp.ClientSession()",
"1 # # while True: # # all_done.add_done_callback(functools.partial(on_finish, n=page)) # # page +=",
"numpy as np # from tqdm import tqdm # # # 下载协程 #",
"def mp_schedule(): # # pages = list(range(500)) # # prefix = 'https://yuerblog.cc/' #",
"= ['{}{}'.format(prefix, page) for page in pages] # # # url_chunks = np.array_split(urls",
"# title = soup.find('h1').get_text().strip() # page_urls = set([urljoin(base_url, url['href']) for url in urls])",
"session)) for url in unseen] # finished, unfinished = await asyncio.wait(tasks) # htmls",
"main(loop): # processes = 8 # pool = mp.Pool(processes) # slightly affected #"
] |
[
"un entier x dans un tableau # ------------------------------------------------------------ # Fonction de recherche d'un",
"Script pour rechercher un entier x dans un tableau # ------------------------------------------------------------ # Fonction",
"def contient(arr, taille, x): # Recherche de l'entier x dans le tableau. if",
"un tableau # ------------------------------------------------------------ # Fonction de recherche d'un entier x dans un",
"un tableau def contient(arr, taille, x): # Recherche de l'entier x dans le",
"x dans un tableau # ------------------------------------------------------------ # Fonction de recherche d'un entier x",
"# Fonction de recherche d'un entier x dans un tableau def contient(arr, taille,",
"entier x dans un tableau # ------------------------------------------------------------ # Fonction de recherche d'un entier",
"de l'entier x dans le tableau. if x in arr: print(\"true\") else: print(\"false\")",
"if x in arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------ # Execution de la",
"entier x dans un tableau def contient(arr, taille, x): # Recherche de l'entier",
"------------------------------------------------------------ # Execution de la fonction de recherche contient([1, 2, 3, 4, 5,",
"dans un tableau # ------------------------------------------------------------ # Fonction de recherche d'un entier x dans",
"de recherche d'un entier x dans un tableau def contient(arr, taille, x): #",
"contient(arr, taille, x): # Recherche de l'entier x dans le tableau. if x",
"taille, x): # Recherche de l'entier x dans le tableau. if x in",
"# Recherche de l'entier x dans le tableau. if x in arr: print(\"true\")",
"tableau. if x in arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------ # Execution de",
"# ------------------------------------------------------------ # Execution de la fonction de recherche contient([1, 2, 3, 4,",
"tableau def contient(arr, taille, x): # Recherche de l'entier x dans le tableau.",
"Recherche de l'entier x dans le tableau. if x in arr: print(\"true\") else:",
"in arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------ # Execution de la fonction de",
"Fonction de recherche d'un entier x dans un tableau def contient(arr, taille, x):",
"pour rechercher un entier x dans un tableau # ------------------------------------------------------------ # Fonction de",
"dans le tableau. if x in arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------ #",
"print(\"false\") # ------------------------------------------------------------ # Execution de la fonction de recherche contient([1, 2, 3,",
"x dans le tableau. if x in arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------",
"dans un tableau def contient(arr, taille, x): # Recherche de l'entier x dans",
"x): # Recherche de l'entier x dans le tableau. if x in arr:",
"l'entier x dans le tableau. if x in arr: print(\"true\") else: print(\"false\") #",
"tableau # ------------------------------------------------------------ # Fonction de recherche d'un entier x dans un tableau",
"Execution de la fonction de recherche contient([1, 2, 3, 4, 5, 6], 6,",
"x dans un tableau def contient(arr, taille, x): # Recherche de l'entier x",
"d'un entier x dans un tableau def contient(arr, taille, x): # Recherche de",
"le tableau. if x in arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------ # Execution",
"# ------------------------------------------------------------ # Fonction de recherche d'un entier x dans un tableau def",
"------------------------------------------------------------ # Fonction de recherche d'un entier x dans un tableau def contient(arr,",
"de la fonction de recherche contient([1, 2, 3, 4, 5, 6], 6, 4)",
"rechercher un entier x dans un tableau # ------------------------------------------------------------ # Fonction de recherche",
"# Script pour rechercher un entier x dans un tableau # ------------------------------------------------------------ #",
"recherche d'un entier x dans un tableau def contient(arr, taille, x): # Recherche",
"x in arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------ # Execution de la fonction",
"print(\"true\") else: print(\"false\") # ------------------------------------------------------------ # Execution de la fonction de recherche contient([1,",
"# Execution de la fonction de recherche contient([1, 2, 3, 4, 5, 6],",
"else: print(\"false\") # ------------------------------------------------------------ # Execution de la fonction de recherche contient([1, 2,",
"arr: print(\"true\") else: print(\"false\") # ------------------------------------------------------------ # Execution de la fonction de recherche"
] |
[
"\"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type",
"\"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日付のフォーマット :type fmt:",
"str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値",
"__init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt:",
"DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type",
"KIND, either express or implied. # See the License for the specific language",
"def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値",
"Unless required by applicable law or agreed to in writing, software # distributed",
"指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: decimal.Decimal \"\"\" #",
"target # 対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None):",
"name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name)",
":param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する",
":rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target # 対象を日付に変換する return",
"name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\"",
"def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値",
"# 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class",
"\"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.datetime \"\"\"",
"this file except in compliance with the License. # You may obtain a",
"\"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日時のフォーマット :type fmt:",
"raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param",
"# 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField):",
"return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'):",
"# プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target:",
"<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"\"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\"",
"ANY KIND, either express or implied. # See the License for the specific",
"abc import ABCMeta, abstractmethod import datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。",
"\"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def",
"文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str",
"IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self,",
"name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日付のフォーマット :type fmt: str \"\"\" #",
"変換対象の値 :type target: object :return: 変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target,",
"# # Copyright 2015−2019 <NAME> # # Licensed under the Apache License, Version",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
":param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する",
"# 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target # 対象を浮動小数点数に変換する return float(target) class DateField(BaseField):",
"isinstance(target, int): return target # 対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\"",
"__init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する",
"\"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param",
"OF ANY KIND, either express or implied. # See the License for the",
"変換後の値 :rtype: object \"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self,",
"DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日付のフォーマット :type fmt: str",
":param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する",
"target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: int",
"\"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def",
"# 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None,",
"class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー",
"target: object :return: 変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str): return",
"対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。",
"target # 対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None,",
"convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype:",
":param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する",
"プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値",
"return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param",
"target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.date",
":return: 変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int): return target #",
":type name: str \"\"\" # プロパティを設定する self.name = name @abstractmethod def convert(self, target):",
"\"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type",
"指定された値を文字列に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: str \"\"\" #",
"当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。",
":rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int): return target # 対象を整数に変換する return",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"target: object :return: 変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return",
"convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target: object :return: 変換後の値",
"datetime.date): return target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\"",
"from abc import ABCMeta, abstractmethod import datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。",
"# 対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\"",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"# 対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\"",
"固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name:",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target # 対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\"",
":return: 変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime): return target #",
"BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー",
"convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype:",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"\"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: object",
"required by applicable law or agreed to in writing, software # distributed under",
"def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値",
"str \"\"\" # プロパティを設定する self.name = name @abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。",
"2015−2019 <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"applicable law or agreed to in writing, software # distributed under the License",
":rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime): return target # 対象を日時に変換する return",
"name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name)",
"def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" #",
"class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー",
"str :param fmt: 日時のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt =",
"name @abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target:",
"decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param",
"or agreed to in writing, software # distributed under the License is distributed",
"specific language governing permissions and # limitations under the License. # from abc",
"float): return target # 対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def",
"float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
":type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param",
"return target # 対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self,",
"License. # from abc import ABCMeta, abstractmethod import datetime import decimal class BaseField(metaclass=ABCMeta):",
"ABCMeta, abstractmethod import datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def",
"対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日付のフォーマット",
"object :return: 変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"License. # You may obtain a copy of the License at # #",
"整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str",
"NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param name:",
"-*- coding: utf-8 -*- # # Copyright 2015−2019 <NAME> # # Licensed under",
"str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。",
"str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。",
"target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.datetime",
"compliance with the License. # You may obtain a copy of the License",
"import ABCMeta, abstractmethod import datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\"",
"float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target # 対象を浮動小数点数に変換する return float(target)",
"\"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type",
"対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField):",
"# プロパティを設定する self.name = name @abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"Copyright 2015−2019 <NAME> # # Licensed under the Apache License, Version 2.0 (the",
"name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name)",
"\"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def",
"convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype:",
"self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。",
"object :return: 変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target",
":type target: object :return: 変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float):",
"int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name:",
"class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param",
"not use this file except in compliance with the License. # You may",
"変換対象の値 :type target: object :return: 変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target,",
":param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target):",
"name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target:",
"utf-8 -*- # # Copyright 2015−2019 <NAME> # # Licensed under the Apache",
"対象が整数の場合はそのまま返却する if isinstance(target, int): return target # 対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\"",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"# プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type target:",
"and # limitations under the License. # from abc import ABCMeta, abstractmethod import",
"target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
":rtype: object \"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None):",
"target: object :return: 変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime): return",
"the License. # from abc import ABCMeta, abstractmethod import datetime import decimal class",
"self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type target:",
"\"\"\" # プロパティを設定する self.name = name @abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。",
"# you may not use this file except in compliance with the License.",
"agreed to in writing, software # distributed under the License is distributed on",
":type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param",
"__init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する",
":type target: object :return: 変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal):",
"(the \"License\"); # you may not use this file except in compliance with",
":param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日時のフォーマット :type fmt: str \"\"\"",
":return: 変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target #",
"対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。",
"if isinstance(target, int): return target # 対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。",
"object :return: 変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int): return target",
"target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype:",
"isinstance(target, str): return target # 対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\"",
"# Unless required by applicable law or agreed to in writing, software #",
"by applicable law or agreed to in writing, software # distributed under the",
"\"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー",
"datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime): return target # 対象を日時に変換する return datetime.datetime.strptime(str(target),",
"__init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する",
":rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target # 対象を浮動小数点数に変換する return",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"\"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\"",
"str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str): return target # 対象を文字列に変換する return str(target)",
":type target: object :return: 変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str):",
"def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target: object :return:",
"\"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する self.name =",
"decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name:",
"return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self,",
"StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type",
"file except in compliance with the License. # You may obtain a copy",
"name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する self.name",
"target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if",
"\"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: str \"\"\"",
"def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" #",
"License for the specific language governing permissions and # limitations under the License.",
"to in writing, software # distributed under the License is distributed on an",
"\"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int): return target # 対象を整数に変換する return int(target) class",
"# 対象が文字列の場合はそのまま返却する if isinstance(target, str): return target # 対象を文字列に変換する return str(target) class IntegerField(BaseField):",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"\"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.date \"\"\"",
"super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type target: object :return:",
"\"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date()",
"指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: object \"\"\"",
"return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param",
"\"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime): return target # 対象を日時に変換する return datetime.datetime.strptime(str(target), self._fmt)",
":rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str): return target # 対象を文字列に変換する return",
":return: 変換後の値 :rtype: object \"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def",
"サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: object \"\"\" raise",
"対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。",
"convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype:",
"name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target:",
"or implied. # See the License for the specific language governing permissions and",
":type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param",
"target # 対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None):",
"class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name:",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target # 対象を日付に変換する return datetime.datetime.strptime(str(target),",
":param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: object \"\"\" raise NotImplementedError()",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"\"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name:",
"limitations under the License. # from abc import ABCMeta, abstractmethod import datetime import",
"# 対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'):",
"DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name:",
":type target: object :return: 変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date):",
"str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name:",
"FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"当フィールドが参照する項目のキー :type name: str :param fmt: 日付のフォーマット :type fmt: str \"\"\" # プロパティを設定する",
"def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値",
"変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する",
"if isinstance(target, str): return target # 対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。",
"governing permissions and # limitations under the License. # from abc import ABCMeta,",
"変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target # 対象を日付に変換する",
"\"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: decimal.Decimal \"\"\"",
"= fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type target: object",
":param fmt: 日付のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt",
"\"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type",
"name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name)",
"class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name:",
"return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。",
"return target # 対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self,",
"name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日時のフォーマット :type fmt: str \"\"\" #",
":type target: object :return: 変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime):",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int): return target # 対象を整数に変換する",
":rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する return",
"\"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: int \"\"\"",
"= name @abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type",
"datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\"",
"class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー",
"指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: float \"\"\" #",
"def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" #",
":type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target):",
"\"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: float \"\"\"",
"当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。",
"\"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class",
"use this file except in compliance with the License. # You may obtain",
"DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー",
":return: 変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target #",
"# プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target:",
"# 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\"",
"変換対象の値 :type target: object :return: 変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target,",
":param fmt: 日時のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt",
"str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値",
"変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime): return target # 対象を日時に変換する",
"isinstance(target, float): return target # 対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\"",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"\"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\"",
"# -*- coding: utf-8 -*- # # Copyright 2015−2019 <NAME> # # Licensed",
"the specific language governing permissions and # limitations under the License. # from",
"name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する self.name = name @abstractmethod def",
"target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if",
"\"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name:",
"新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"プロパティを設定する self.name = name @abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target:",
"int): return target # 対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def",
"for the specific language governing permissions and # limitations under the License. #",
"\"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str): return target # 対象を文字列に変換する return str(target) class",
"if isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。",
"対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\"",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
":type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param",
"super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type",
"fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日時のフォーマット",
"対象が文字列の場合はそのまま返却する if isinstance(target, str): return target # 対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\"",
"# # Unless required by applicable law or agreed to in writing, software",
"express or implied. # See the License for the specific language governing permissions",
"StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self,",
"def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param",
"permissions and # limitations under the License. # from abc import ABCMeta, abstractmethod",
"either express or implied. # See the License for the specific language governing",
"fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type target: object :return:",
"# Copyright 2015−2019 <NAME> # # Licensed under the Apache License, Version 2.0",
"language governing permissions and # limitations under the License. # from abc import",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"if isinstance(target, float): return target # 対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。",
"__init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する",
"指定された値を整数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: int \"\"\" #",
"super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target: object :return:",
"\"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\"",
"coding: utf-8 -*- # # Copyright 2015−2019 <NAME> # # Licensed under the",
"super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target: object :return:",
"str :param fmt: 日付のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt =",
"fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type target: object :return:",
"# プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target:",
"変換対象の値 :type target: object :return: 変換後の値 :rtype: object \"\"\" raise NotImplementedError() class StringField(BaseField):",
"name: str \"\"\" # プロパティを設定する self.name = name @abstractmethod def convert(self, target): \"\"\"",
"target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: object \"\"\" raise NotImplementedError() class",
"the License. # You may obtain a copy of the License at #",
"変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target,",
"name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt:",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
":type name: str :param fmt: 日時のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name)",
"target: object :return: 変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int): return",
"target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"str): return target # 対象を文字列に変換する return str(target) class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def",
"プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type target: object",
"当フィールドが参照する項目のキー :type name: str :param fmt: 日時のフォーマット :type fmt: str \"\"\" # プロパティを設定する",
"str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値",
"def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値",
"target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self,",
"\"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name:",
"-*- # # Copyright 2015−2019 <NAME> # # Licensed under the Apache License,",
"プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target: object",
"convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype:",
"指定された値を日時に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.datetime \"\"\" #",
"datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\"",
"target: object :return: 変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return",
"当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する self.name = name @abstractmethod def convert(self,",
":return: 変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str): return target #",
"with the License. # You may obtain a copy of the License at",
"name: str :param fmt: 日時のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt",
":param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する",
"object \"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\"",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"対象を浮動小数点数に変換する return float(target) class DateField(BaseField): \"\"\" 日付を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\"",
"target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: str",
"def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str",
"IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type",
"name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target:",
"law or agreed to in writing, software # distributed under the License is",
"super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type target: object :return:",
"the License for the specific language governing permissions and # limitations under the",
"self.name = name @abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値",
"# from abc import ABCMeta, abstractmethod import datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\"",
"当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。",
"日時を表現するフィールドクラス。 \"\"\" def __init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target,",
"str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値",
"DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日時のフォーマット :type fmt: str",
":type target: object :return: 変換後の値 :rtype: int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int):",
"# プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target:",
"def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値",
"in compliance with the License. # You may obtain a copy of the",
"target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: float",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# limitations under the License. # from abc import ABCMeta, abstractmethod import datetime",
"fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\"",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"日付のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self,",
"isinstance(target, datetime.date): return target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\"",
"target: object :return: 変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return",
"target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if",
":return: 変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target #",
"super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type",
"target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None):",
"class IntegerField(BaseField): \"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー",
"See the License for the specific language governing permissions and # limitations under",
":param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する self.name = name @abstractmethod",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"<filename>pyny/fields.py # -*- coding: utf-8 -*- # # Copyright 2015−2019 <NAME> # #",
":param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"浮動小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str",
"\"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target # 対象を浮動小数点数に変換する return float(target) class",
"プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target: object",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"decimal.Decimal): return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target)) class FloatField(BaseField): \"\"\" 浮動小数点数を表現するフィールドクラス。 \"\"\" def",
"\"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param",
":type target: object :return: 変換後の値 :rtype: object \"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\"",
"\"\"\" 整数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" IntegerFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name:",
"すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name:",
"self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type target:",
"FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self,",
"import datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None):",
":type name: str :param fmt: 日付のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name)",
"\"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"except in compliance with the License. # You may obtain a copy of",
"abstractmethod import datetime import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self,",
"# プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を整数に変換する。 :param target: 変換対象の値 :type target:",
"return target # 対象を整数に変換する return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self,",
"name: str :param fmt: 日付のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt",
"変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target, float): return target # 対象を浮動小数点数に変換する",
"\"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def",
"\"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target: 変換対象の値 :type",
"# 対象が整数の場合はそのまま返却する if isinstance(target, int): return target # 対象を整数に変換する return int(target) class DecimalField(BaseField):",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"object :return: 変換後の値 :rtype: datetime.date \"\"\" # 対象が日付の場合はそのまま返却する if isinstance(target, datetime.date): return target",
"import decimal class BaseField(metaclass=ABCMeta): \"\"\" すべてのフィールドクラスのスーパークラス。 新しいフィールドクラスを実装する場合は当クラスを継承すること。 \"\"\" def __init__(self, name=None): \"\"\" BaseFieldを構築する。",
"指定された値を日付に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: datetime.date \"\"\" #",
"__init__(self, name=None, fmt='%Y/%m/%d %H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param",
"convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype:",
"def __init__(self, name=None): \"\"\" FloatFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" #",
"当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。",
"if isinstance(target, datetime.date): return target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\"",
"name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を浮動小数点数に変換する。 :param target:",
"プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self, target): \"\"\" 指定された値を日付に変換する。 :param target: 変換対象の値",
"decimal.Decimal \"\"\" # 対象が固定小数点数の場合はそのまま返却する if isinstance(target, decimal.Decimal): return target # 対象を固定小数点数に変換する return decimal.Decimal(str(target))",
"return int(target) class DecimalField(BaseField): \"\"\" 固定小数点数を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param",
"under the License. # from abc import ABCMeta, abstractmethod import datetime import decimal",
"target: object :return: 変換後の値 :rtype: object \"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。",
"変換対象の値 :type target: object :return: 変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if isinstance(target,",
"target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: float \"\"\" # 対象が浮動小数点数の場合はそのまま返却する if",
"object :return: 変換後の値 :rtype: object \"\"\" raise NotImplementedError() class StringField(BaseField): \"\"\" 文字列を表現するフィールドクラス。 \"\"\"",
"BaseFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する self.name = name",
"日時のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def convert(self,",
"fmt: 日付のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def",
"プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を文字列に変換する。 :param target: 変換対象の値 :type target: object",
"\"\"\" 文字列を表現するフィールドクラス。 \"\"\" def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name:",
"\"\"\" # プロパティを設定する super().__init__(name) def convert(self, target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type",
"object :return: 変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str): return target",
"return target # 対象を日付に変換する return datetime.datetime.strptime(str(target), self._fmt).date() class DateTimeField(BaseField): \"\"\" 日時を表現するフィールドクラス。 \"\"\" def",
"__init__(self, name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する",
"@abstractmethod def convert(self, target): \"\"\" 指定された値をそのフィールドクラスに適した型に変換する。 サブクラスでそれぞれのクラスに応じた値を返すようオーバーライドすること。 :param target: 変換対象の値 :type target: object",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"変換後の値 :rtype: str \"\"\" # 対象が文字列の場合はそのまま返却する if isinstance(target, str): return target # 対象を文字列に変換する",
"\"\"\" def __init__(self, name=None): \"\"\" DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\"",
"target): \"\"\" 指定された値を固定小数点数に変換する。 :param target: 変換対象の値 :type target: object :return: 変換後の値 :rtype: decimal.Decimal",
"def __init__(self, name=None): \"\"\" StringFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" #",
"\"\"\" def __init__(self, name=None, fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str",
"= fmt def convert(self, target): \"\"\" 指定された値を日時に変換する。 :param target: 変換対象の値 :type target: object",
"fmt='%Y/%m/%d'): \"\"\" DateFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日付のフォーマット :type",
"int \"\"\" # 対象が整数の場合はそのまま返却する if isinstance(target, int): return target # 対象を整数に変換する return int(target)",
"%H:%M:%S'): \"\"\" DateTimeFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日時のフォーマット :type",
"DecimalFieldを構築する。 :param name: 当フィールドが参照する項目のキー :type name: str \"\"\" # プロパティを設定する super().__init__(name) def convert(self,",
"fmt: 日時のフォーマット :type fmt: str \"\"\" # プロパティを設定する super().__init__(name) self._fmt = fmt def",
"object :return: 変換後の値 :rtype: datetime.datetime \"\"\" # 対象が日時の場合はそのまま返却する if isinstance(target, datetime.datetime): return target",
":param name: 当フィールドが参照する項目のキー :type name: str :param fmt: 日付のフォーマット :type fmt: str \"\"\""
] |
[
"token = \"\" payload = { \"msgtype\" : \"markdown\", \"markdown\": { \"title\": \"This",
"second line.\", ]) }, \"at\" : { \"atMobiles\": [\"18600000000\"], \"isAll\": False } }",
"This is title\", \"> This is first line.\", \"> This is second line.\",",
"\"\" payload = { \"msgtype\" : \"markdown\", \"markdown\": { \"title\": \"This is the",
".incoming import dingtalk_incoming if __name__ == \"__main__\": token = \"\" payload = {",
"\"__main__\": token = \"\" payload = { \"msgtype\" : \"markdown\", \"markdown\": { \"title\":",
"{ \"msgtype\" : \"markdown\", \"markdown\": { \"title\": \"This is the title!\", \"text\" :",
"title\", \"> This is first line.\", \"> This is second line.\", ]) },",
"first line.\", \"> This is second line.\", ]) }, \"at\" : { \"atMobiles\":",
"import dingtalk_incoming if __name__ == \"__main__\": token = \"\" payload = { \"msgtype\"",
"= \"\" payload = { \"msgtype\" : \"markdown\", \"markdown\": { \"title\": \"This is",
"__name__ == \"__main__\": token = \"\" payload = { \"msgtype\" : \"markdown\", \"markdown\":",
"= { \"msgtype\" : \"markdown\", \"markdown\": { \"title\": \"This is the title!\", \"text\"",
"-*- coding: utf-8 -*- from .incoming import dingtalk_incoming if __name__ == \"__main__\": token",
"utf-8 -*- from .incoming import dingtalk_incoming if __name__ == \"__main__\": token = \"\"",
"payload = { \"msgtype\" : \"markdown\", \"markdown\": { \"title\": \"This is the title!\",",
"{ \"title\": \"This is the title!\", \"text\" : \"\\n\\n\".join([ \"# This is title\",",
"\"text\" : \"\\n\\n\".join([ \"# This is title\", \"> This is first line.\", \">",
"\"\\n\\n\".join([ \"# This is title\", \"> This is first line.\", \"> This is",
"coding: utf-8 -*- from .incoming import dingtalk_incoming if __name__ == \"__main__\": token =",
"\"> This is second line.\", ]) }, \"at\" : { \"atMobiles\": [\"18600000000\"], \"isAll\":",
"\"markdown\", \"markdown\": { \"title\": \"This is the title!\", \"text\" : \"\\n\\n\".join([ \"# This",
": \"markdown\", \"markdown\": { \"title\": \"This is the title!\", \"text\" : \"\\n\\n\".join([ \"#",
"\"markdown\": { \"title\": \"This is the title!\", \"text\" : \"\\n\\n\".join([ \"# This is",
"]) }, \"at\" : { \"atMobiles\": [\"18600000000\"], \"isAll\": False } } dingtalk_incoming(token, payload=payload,",
"is the title!\", \"text\" : \"\\n\\n\".join([ \"# This is title\", \"> This is",
"}, \"at\" : { \"atMobiles\": [\"18600000000\"], \"isAll\": False } } dingtalk_incoming(token, payload=payload, at_mobiles=[\"18600000000\"])",
"if __name__ == \"__main__\": token = \"\" payload = { \"msgtype\" : \"markdown\",",
"This is first line.\", \"> This is second line.\", ]) }, \"at\" :",
"# -*- coding: utf-8 -*- from .incoming import dingtalk_incoming if __name__ == \"__main__\":",
"is first line.\", \"> This is second line.\", ]) }, \"at\" : {",
"-*- from .incoming import dingtalk_incoming if __name__ == \"__main__\": token = \"\" payload",
"\"This is the title!\", \"text\" : \"\\n\\n\".join([ \"# This is title\", \"> This",
"is title\", \"> This is first line.\", \"> This is second line.\", ])",
"\"> This is first line.\", \"> This is second line.\", ]) }, \"at\"",
"line.\", ]) }, \"at\" : { \"atMobiles\": [\"18600000000\"], \"isAll\": False } } dingtalk_incoming(token,",
"== \"__main__\": token = \"\" payload = { \"msgtype\" : \"markdown\", \"markdown\": {",
"is second line.\", ]) }, \"at\" : { \"atMobiles\": [\"18600000000\"], \"isAll\": False }",
"from .incoming import dingtalk_incoming if __name__ == \"__main__\": token = \"\" payload =",
"\"# This is title\", \"> This is first line.\", \"> This is second",
"\"title\": \"This is the title!\", \"text\" : \"\\n\\n\".join([ \"# This is title\", \">",
": \"\\n\\n\".join([ \"# This is title\", \"> This is first line.\", \"> This",
"This is second line.\", ]) }, \"at\" : { \"atMobiles\": [\"18600000000\"], \"isAll\": False",
"\"msgtype\" : \"markdown\", \"markdown\": { \"title\": \"This is the title!\", \"text\" : \"\\n\\n\".join([",
"dingtalk_incoming if __name__ == \"__main__\": token = \"\" payload = { \"msgtype\" :",
"title!\", \"text\" : \"\\n\\n\".join([ \"# This is title\", \"> This is first line.\",",
"the title!\", \"text\" : \"\\n\\n\".join([ \"# This is title\", \"> This is first",
"line.\", \"> This is second line.\", ]) }, \"at\" : { \"atMobiles\": [\"18600000000\"],"
] |
[
"# 1 objectness score + 4 bounding box coordinates NORMALIZATION_FACTOR = 255. #",
"= '\\033[36m' GREEN = '\\033[32m' RED = '\\033[31m' YELLOW = '\\033[33m' PURPLE =",
"= 3 # x, y, w, h, score, class1, class2, ... XY_SLICE =",
"Colors BLUE = '\\033[36m' GREEN = '\\033[32m' RED = '\\033[31m' YELLOW = '\\033[33m'",
"os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - - - -",
"# - - - - - - - - - - - -",
"- - - - - # # TFLite converter # - - -",
"CLASSES_SLICE = (5, 0) NB_OUTPUTS = 5 # 1 objectness score + 4",
"- - - - - - - - - - # DATA_DIR =",
"= 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - - - -",
"converter # - - - - - - - - - - -",
"BLUE = '\\033[36m' GREEN = '\\033[32m' RED = '\\033[31m' YELLOW = '\\033[33m' PURPLE",
"h) RAW_PREFIX = 'raw_' # - - - - - - - -",
"# list of class scores COORDINATES_NAME = 'coordinates' # (x, y, w, h)",
"- - - - - - - - # # Common values #",
"- - - - - # # TFlite additional default values # -",
"'_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1",
"(5, 0) NB_OUTPUTS = 5 # 1 objectness score + 4 bounding box",
"- # TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt' # Format TFLITE = 'tflite'",
"= 20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # -",
"= '\\033[33m' PURPLE = '\\033[34m' END_COLOR = '\\033[0m' BOLD = '\\033[1m' # -",
"index SCORES_NAME = 'score' # confidence score NUMBER_NAME = 'number of detections' #",
"class1, class2, ... XY_SLICE = (0, 2) WH_SLICE = (2, 4) SCORE_SLICE =",
"= 'conf threshold' # Colors BLUE = '\\033[36m' GREEN = '\\033[32m' RED =",
"'\\033[31m' YELLOW = '\\033[33m' PURPLE = '\\033[34m' END_COLOR = '\\033[0m' BOLD = '\\033[1m'",
"'coordinates' # (x, y, w, h) RAW_PREFIX = 'raw_' # - - -",
"'wagen' TRAKTION = 'traktion' # Output names BOUNDINGBOX_NAME = 'location' # (y1, x1,",
"= 'labels.txt' # Format TFLITE = 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb'",
"1 NB_CHANNEL = 3 # x, y, w, h, score, class1, class2, ...",
"= os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16 = 'float16' INT8",
"# Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME",
"- - - - # ONNX_SUFFIX = '.onnx' OPSET = 12 # --------------------------------------------------------------------------------------------------------------------",
"= 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return",
"number of detected object in the image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME =",
"- - - - - - - - - - - # #",
"class2, ... XY_SLICE = (0, 2) WH_SLICE = (2, 4) SCORE_SLICE = (4,",
"'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD",
"- - - - - - - # DATA_DIR = os.path.join('data') OUTPUT_DIR =",
"= '.torchscript.pt' # Outputs names CONFIDENCE_NAME = 'confidence' # list of class scores",
"# Inference # - - - - - - - - - -",
"# Constants # -------------------------------------------------------------------------------------------------------------------- # # General # - - - - -",
"# x, y, w, h, score, class1, class2, ... XY_SLICE = (0, 2)",
"- - - - - - # # Common values # - -",
"score, class1, class2, ... XY_SLICE = (0, 2) WH_SLICE = (2, 4) SCORE_SLICE",
"Outputs names CONFIDENCE_NAME = 'confidence' # list of class scores COORDINATES_NAME = 'coordinates'",
"- - - - - - - - # ONNX_SUFFIX = '.onnx' OPSET",
"= '.tflite' LABELS_NAME = 'labels.txt' # Format TFLITE = 'tflite' SAVED_MODEL = 'saved_model'",
"= '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1 NB_CHANNEL = 3 # x,",
"= 'padded' SIMPLE = 'simple' COMBINED = 'combined' # Representative dataset BAHNHOF =",
"# Colors BLUE = '\\033[36m' GREEN = '\\033[32m' RED = '\\033[31m' YELLOW =",
"- - - - - # # ONNX converter # - - -",
"- - - - - - - - - - - # DEFAULT_DETECTED_IMAGE_DIR",
"get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - - - - - - -",
"of class scores COORDINATES_NAME = 'coordinates' # (x, y, w, h) RAW_PREFIX =",
"0) NB_OUTPUTS = 5 # 1 objectness score + 4 bounding box coordinates",
"'\\033[33m' PURPLE = '\\033[34m' END_COLOR = '\\033[0m' BOLD = '\\033[1m' # - -",
"= FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25 # - - - -",
"- - - - - - - # ONNX_SUFFIX = '.onnx' OPSET =",
"- - - - - - - - # # Inference # -",
"- - # ONNX_SUFFIX = '.onnx' OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- # #",
"ONNX_SUFFIX = '.onnx' OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- # # Default values #",
"'\\033[32m' RED = '\\033[31m' YELLOW = '\\033[33m' PURPLE = '\\033[34m' END_COLOR = '\\033[0m'",
"TFLITE = 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED =",
"COORDINATES_NAME = 'coordinates' # (x, y, w, h) RAW_PREFIX = 'raw_' # -",
"# (y1, x1, y2, x2) CLASSES_NAME = 'category' # class index SCORES_NAME =",
"y2, x2) CLASSES_NAME = 'category' # class index SCORES_NAME = 'score' # confidence",
"(4, 5) CLASSES_SLICE = (5, 0) NB_OUTPUTS = 5 # 1 objectness score",
"'_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1 NB_CHANNEL = 3",
"- - - - - - - - - # # Common values",
"- - - - - - - # # Common values # -",
"- # # CoreML converter # - - - - - - -",
"OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16 = 'float16' INT8 = 'int8'",
"'labels.txt' # Format TFLITE = 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb' #",
"# DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640",
"def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - - - - - -",
"- - - - - # TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt' #",
"- - - - - - # # TFlite additional default values #",
"= 'score' # confidence score NUMBER_NAME = 'number of detections' # number of",
"= 0.25 # - - - - - - - - - -",
"- - - - # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION =",
"= 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED = 'padded'",
"WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def",
"BOLD = '\\033[1m' # - - - - - - - - -",
"- - - - - - - - - # COREML_SUFFIX = '.mlmodel'",
"FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX",
"INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1 NB_CHANNEL = 3 #",
"PURPLE = '\\033[34m' END_COLOR = '\\033[0m' BOLD = '\\033[1m' # - - -",
"... XY_SLICE = (0, 2) WH_SLICE = (2, 4) SCORE_SLICE = (4, 5)",
"values # - - - - - - - - - - -",
"- - - - - - # # ONNX converter # - -",
"'conf threshold' # Colors BLUE = '\\033[36m' GREEN = '\\033[32m' RED = '\\033[31m'",
"'predictions' # - - - - - - - - - - -",
"- - - - # DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32",
"- - - # ONNX_SUFFIX = '.onnx' OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- #",
"# -------------------------------------------------------------------------------------------------------------------- # # Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME",
"- - - - - - - - - - # DEFAULT_DETECTED_IMAGE_DIR =",
"5) CLASSES_SLICE = (5, 0) NB_OUTPUTS = 5 # 1 objectness score +",
"- - - - - - - # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION =",
"FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1 NB_CHANNEL = 3 # x, y, w,",
"-------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # -",
"TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt' # Format TFLITE = 'tflite' SAVED_MODEL =",
"'\\033[36m' GREEN = '\\033[32m' RED = '\\033[31m' YELLOW = '\\033[33m' PURPLE = '\\033[34m'",
"y, w, h) RAW_PREFIX = 'raw_' # - - - - - -",
"os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16 = 'float16' INT8 = 'int8' FULLINT8 =",
"PADDED = 'padded' SIMPLE = 'simple' COMBINED = 'combined' # Representative dataset BAHNHOF",
"- - - - - # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION",
"# General # - - - - - - - - - -",
"CLASSES_NAME = 'category' # class index SCORES_NAME = 'score' # confidence score NUMBER_NAME",
"TFLite converter # - - - - - - - - - -",
"- # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source):",
"os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16 = 'float16' INT8 =",
"- - # # TFLite converter # - - - - - -",
"= 1 NB_CHANNEL = 3 # x, y, w, h, score, class1, class2,",
"- - - # TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt' # Format TFLITE",
"'simple' COMBINED = 'combined' # Representative dataset BAHNHOF = 'bahnhof' WAGEN = 'wagen'",
"# # TFlite additional default values # - - - - - -",
"= '.onnx' OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- # # Default values # --------------------------------------------------------------------------------------------------------------------",
"= 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou threshold' CONF_NAME",
"# TFlite additional default values # - - - - - - -",
"2) WH_SLICE = (2, 4) SCORE_SLICE = (4, 5) CLASSES_SLICE = (5, 0)",
"# ONNX converter # - - - - - - - - -",
"- - - - - - - - - - - - #",
"- - - - - - - - # DEFAULT_DETECTED_IMAGE_DIR = os.path.join(OUTPUT_DIR, 'detections')",
"os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32",
"= (5, 0) NB_OUTPUTS = 5 # 1 objectness score + 4 bounding",
"- - - - - - - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL",
"0.25 # - - - - - - - - - - -",
"= (0, 2) WH_SLICE = (2, 4) SCORE_SLICE = (4, 5) CLASSES_SLICE =",
"- - - - - - - - - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR,",
"'.onnx' OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- # # Default values # -------------------------------------------------------------------------------------------------------------------- #",
"os # -------------------------------------------------------------------------------------------------------------------- # # Constants # -------------------------------------------------------------------------------------------------------------------- # # General # -",
"-------------------------------------------------------------------------------------------------------------------- # # Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME =",
"default values # - - - - - - - - - -",
"- - - - - # # Inference # - - - -",
"list of class scores COORDINATES_NAME = 'coordinates' # (x, y, w, h) RAW_PREFIX",
"of detections' # number of detected object in the image DETECTIONS_NAME = 'detection",
"'\\033[34m' END_COLOR = '\\033[0m' BOLD = '\\033[1m' # - - - - -",
"END_COLOR = '\\033[0m' BOLD = '\\033[1m' # - - - - - -",
"= (2, 4) SCORE_SLICE = (4, 5) CLASSES_SLICE = (5, 0) NB_OUTPUTS =",
"- # # ONNX converter # - - - - - - -",
"+ 4 bounding box coordinates NORMALIZATION_FACTOR = 255. # Input names IMAGE_NAME =",
"= '\\033[32m' RED = '\\033[31m' YELLOW = '\\033[33m' PURPLE = '\\033[34m' END_COLOR =",
"# Outputs names CONFIDENCE_NAME = 'confidence' # list of class scores COORDINATES_NAME =",
"- - - - - - - - # TFLITE_SUFFIX = '.tflite' LABELS_NAME",
"= '_quantized' IOU_NAME = 'iou threshold' CONF_NAME = 'conf threshold' # Colors BLUE",
"'.tflite' LABELS_NAME = 'labels.txt' # Format TFLITE = 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX",
"'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8'",
"= 'iou threshold' CONF_NAME = 'conf threshold' # Colors BLUE = '\\033[36m' GREEN",
"'_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1 NB_CHANNEL = 3 # x, y,",
"'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25",
"# COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names CONFIDENCE_NAME = 'confidence'",
"- - # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def",
"SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED = 'padded' SIMPLE =",
"= '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names CONFIDENCE_NAME = 'confidence' # list",
"- # # Inference # - - - - - - - -",
"- - - - - - - - - - # ONNX_SUFFIX =",
"= 'predictions' # - - - - - - - - - -",
"# ONNX_SUFFIX = '.onnx' OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- # # Default values",
"values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX'",
"- - - - - - - - - - - # TFLITE_SUFFIX",
"= 'yolov5-ONNX' # - - - - - - - - - -",
"640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25 # - -",
"DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE",
"- - - # # Common values # - - - - -",
"'\\033[1m' # - - - - - - - - - - -",
"TFlite additional default values # - - - - - - - -",
"TRAKTION = 'traktion' # Output names BOUNDINGBOX_NAME = 'location' # (y1, x1, y2,",
"return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - - - - - - - -",
"= 'float16' INT8 = 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX =",
"NB_CHANNEL = 3 # x, y, w, h, score, class1, class2, ... XY_SLICE",
"- - - - - - - - - - - - -",
"'_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou threshold' CONF_NAME = 'conf threshold' #",
"- - - - - # DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output')",
"'traktion' # Output names BOUNDINGBOX_NAME = 'location' # (y1, x1, y2, x2) CLASSES_NAME",
"SCORES_NAME = 'score' # confidence score NUMBER_NAME = 'number of detections' # number",
"- - - - - - - - - # # TFlite additional",
"- - # # ONNX converter # - - - - - -",
"FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25 # - - - - -",
"- - # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names CONFIDENCE_NAME",
"DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - - - - - - - - -",
"# Output names BOUNDINGBOX_NAME = 'location' # (y1, x1, y2, x2) CLASSES_NAME =",
"INT8 = 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX",
"- - # # Common values # - - - - - -",
"'yolov5-ONNX' # - - - - - - - - - - -",
"= 'number of detections' # number of detected object in the image DETECTIONS_NAME",
"- - - - # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs",
"- - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION",
"- - - - - - - - # DATA_DIR = os.path.join('data') OUTPUT_DIR",
"- - - - - - # # CoreML converter # - -",
"'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED = 'padded' SIMPLE = 'simple' COMBINED",
"- - - # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20",
"GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED = 'padded' SIMPLE = 'simple' COMBINED =",
"detected object in the image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME = 'predictions' #",
"# # General # - - - - - - - - -",
"= 0.45 DEFAULT_CONF_THRESHOLD = 0.25 # - - - - - - -",
"= '_fullint8' BATCH_SIZE = 1 NB_CHANNEL = 3 # x, y, w, h,",
"- # # TFLite converter # - - - - - - -",
"= (4, 5) CLASSES_SLICE = (5, 0) NB_OUTPUTS = 5 # 1 objectness",
"<filename>yolov5-coreml-tflite-converter/utils/constants.py<gh_stars>0 import os # -------------------------------------------------------------------------------------------------------------------- # # Constants # -------------------------------------------------------------------------------------------------------------------- # # General",
"- - - - - - - - # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX",
"= 'location' # (y1, x1, y2, x2) CLASSES_NAME = 'category' # class index",
"- - - - - - - # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX =",
"FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1 NB_CHANNEL",
"'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED = 'padded' SIMPLE",
"class scores COORDINATES_NAME = 'coordinates' # (x, y, w, h) RAW_PREFIX = 'raw_'",
"bounding box coordinates NORMALIZATION_FACTOR = 255. # Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX",
"score NUMBER_NAME = 'number of detections' # number of detected object in the",
"- - # # TFlite additional default values # - - - -",
"= '\\033[1m' # - - - - - - - - - -",
"# confidence score NUMBER_NAME = 'number of detections' # number of detected object",
"DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - - -",
"'detection results' PREDICTIONS_NAME = 'predictions' # - - - - - - -",
"'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - - - - -",
"of detected object in the image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME = 'predictions'",
"DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' #",
"20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - -",
"- - - - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models',",
"Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME =",
"- - - - - - - # # TFlite additional default values",
"detections' # number of detected object in the image DETECTIONS_NAME = 'detection results'",
"# TFLite converter # - - - - - - - - -",
"x2) CLASSES_NAME = 'category' # class index SCORES_NAME = 'score' # confidence score",
"- - - - - - - - - # # Inference #",
"CONF_NAME = 'conf threshold' # Colors BLUE = '\\033[36m' GREEN = '\\033[32m' RED",
"- - - - # # Common values # - - - -",
"- - - - - - - - - - # DEFAULT_MODEL_OUTPUT_DIR =",
"- - - - - - - - # # TFLite converter #",
"- - - - # # ONNX converter # - - - -",
"DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25 # - - -",
"get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - -",
"DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25 # - - - - - -",
"DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16 = 'float16'",
"Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME =",
"= '\\033[34m' END_COLOR = '\\033[0m' BOLD = '\\033[1m' # - - - -",
"QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou threshold' CONF_NAME = 'conf threshold' # Colors",
"= '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE = 1 NB_CHANNEL =",
"GREEN = '\\033[32m' RED = '\\033[31m' YELLOW = '\\033[33m' PURPLE = '\\033[34m' END_COLOR",
"y, w, h, score, class1, class2, ... XY_SLICE = (0, 2) WH_SLICE =",
"# CoreML converter # - - - - - - - - -",
"'location' # (y1, x1, y2, x2) CLASSES_NAME = 'category' # class index SCORES_NAME",
"CONFIDENCE_NAME = 'confidence' # list of class scores COORDINATES_NAME = 'coordinates' # (x,",
"RAW_PREFIX = 'raw_' # - - - - - - - - -",
"- - - - - - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL =",
"= 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - - - - - - -",
"x1, y2, x2) CLASSES_NAME = 'category' # class index SCORES_NAME = 'score' #",
"- - - - - - # DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR,",
"# -------------------------------------------------------------------------------------------------------------------- # # Constants # -------------------------------------------------------------------------------------------------------------------- # # General # - -",
"LABELS_NAME = 'labels.txt' # Format TFLITE = 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX =",
"CoreML converter # - - - - - - - - - -",
"'combined' # Representative dataset BAHNHOF = 'bahnhof' WAGEN = 'wagen' TRAKTION = 'traktion'",
"in the image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME = 'predictions' # - -",
"RED = '\\033[31m' YELLOW = '\\033[33m' PURPLE = '\\033[34m' END_COLOR = '\\033[0m' BOLD",
"= 'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED = 'padded' SIMPLE = 'simple'",
"# Representative dataset BAHNHOF = 'bahnhof' WAGEN = 'wagen' TRAKTION = 'traktion' #",
"= 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25 # -",
"f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - - - - - - - - -",
"- - - - - - # # Inference # - - -",
"- - - - - - - - # # ONNX converter #",
"IOU_NAME = 'iou threshold' CONF_NAME = 'conf threshold' # Colors BLUE = '\\033[36m'",
"= '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou threshold' CONF_NAME = 'conf threshold'",
"= 'confidence' # list of class scores COORDINATES_NAME = 'coordinates' # (x, y,",
"Output names BOUNDINGBOX_NAME = 'location' # (y1, x1, y2, x2) CLASSES_NAME = 'category'",
"- - - - - - - - # # TFlite additional default",
"= os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45",
"'_fullint8' BATCH_SIZE = 1 NB_CHANNEL = 3 # x, y, w, h, score,",
"4) SCORE_SLICE = (4, 5) CLASSES_SLICE = (5, 0) NB_OUTPUTS = 5 #",
"- - - - - - - # # CoreML converter # -",
"- # # Common values # - - - - - - -",
"DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - - - - - -",
"- - - - - - - - - - # # ONNX",
"'iou threshold' CONF_NAME = 'conf threshold' # Colors BLUE = '\\033[36m' GREEN =",
"'output') FLOAT32 = 'float32' FLOAT16 = 'float16' INT8 = 'int8' FULLINT8 = 'fullint8'",
"= 'bahnhof' WAGEN = 'wagen' TRAKTION = 'traktion' # Output names BOUNDINGBOX_NAME =",
"h, score, class1, class2, ... XY_SLICE = (0, 2) WH_SLICE = (2, 4)",
"# # ONNX converter # - - - - - - - -",
"'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD =",
"- - - # # TFLite converter # - - - - -",
"General # - - - - - - - - - - -",
"= '\\033[0m' BOLD = '\\033[1m' # - - - - - - -",
"'_quantized' IOU_NAME = 'iou threshold' CONF_NAME = 'conf threshold' # Colors BLUE =",
"= 'wagen' TRAKTION = 'traktion' # Output names BOUNDINGBOX_NAME = 'location' # (y1,",
"255. # Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized'",
"(2, 4) SCORE_SLICE = (4, 5) CLASSES_SLICE = (5, 0) NB_OUTPUTS = 5",
"coordinates NORMALIZATION_FACTOR = 255. # Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized'",
"1 objectness score + 4 bounding box coordinates NORMALIZATION_FACTOR = 255. # Input",
"threshold' # Colors BLUE = '\\033[36m' GREEN = '\\033[32m' RED = '\\033[31m' YELLOW",
"- - - - - - - - - - # # TFLite",
"= 'float32' FLOAT16 = 'float16' INT8 = 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX =",
"'.pb' # NMS PADDED = 'padded' SIMPLE = 'simple' COMBINED = 'combined' #",
"class index SCORES_NAME = 'score' # confidence score NUMBER_NAME = 'number of detections'",
"'score' # confidence score NUMBER_NAME = 'number of detections' # number of detected",
"- - - - - - - # # TFLite converter # -",
"- # ONNX_SUFFIX = '.onnx' OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- # # Default",
"= os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE =",
"FLOAT16 = 'float16' INT8 = 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX",
"= 'simple' COMBINED = 'combined' # Representative dataset BAHNHOF = 'bahnhof' WAGEN =",
"Format TFLITE = 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS PADDED",
"= os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16 = 'float16' INT8 = 'int8' FULLINT8",
"- - - - - - - - - - - # DEFAULT_SOURCE_DATASET",
"- - - - - - # TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt'",
"- - - - - - - - - - # # Common",
"Constants # -------------------------------------------------------------------------------------------------------------------- # # General # - - - - - -",
"WH_SLICE = (2, 4) SCORE_SLICE = (4, 5) CLASSES_SLICE = (5, 0) NB_OUTPUTS",
"= '.pb' # NMS PADDED = 'padded' SIMPLE = 'simple' COMBINED = 'combined'",
"BAHNHOF = 'bahnhof' WAGEN = 'wagen' TRAKTION = 'traktion' # Output names BOUNDINGBOX_NAME",
"NB_OUTPUTS = 5 # 1 objectness score + 4 bounding box coordinates NORMALIZATION_FACTOR",
"'.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names CONFIDENCE_NAME = 'confidence' # list of",
"= 'traktion' # Output names BOUNDINGBOX_NAME = 'location' # (y1, x1, y2, x2)",
"image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME = 'predictions' # - - - -",
"- - # TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt' # Format TFLITE =",
"- - - - - - # ONNX_SUFFIX = '.onnx' OPSET = 12",
"# DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - -",
"NUMBER_NAME = 'number of detections' # number of detected object in the image",
"'\\033[0m' BOLD = '\\033[1m' # - - - - - - - -",
"SIMPLE = 'simple' COMBINED = 'combined' # Representative dataset BAHNHOF = 'bahnhof' WAGEN",
"# number of detected object in the image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME",
"TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names CONFIDENCE_NAME = 'confidence' # list of class",
"- - - - - - - - - - - # DATA_DIR",
"= 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX =",
"WAGEN = 'wagen' TRAKTION = 'traktion' # Output names BOUNDINGBOX_NAME = 'location' #",
"= 'category' # class index SCORES_NAME = 'score' # confidence score NUMBER_NAME =",
"confidence score NUMBER_NAME = 'number of detections' # number of detected object in",
"PREDICTIONS_NAME = 'predictions' # - - - - - - - - -",
"w, h, score, class1, class2, ... XY_SLICE = (0, 2) WH_SLICE = (2,",
"= 'detection results' PREDICTIONS_NAME = 'predictions' # - - - - - -",
"NMS PADDED = 'padded' SIMPLE = 'simple' COMBINED = 'combined' # Representative dataset",
"- - - - # # TFLite converter # - - - -",
"- - - - - - - - - # TFLITE_SUFFIX = '.tflite'",
"- - - - - - - - # # CoreML converter #",
"# # Inference # - - - - - - - - -",
"= 'coordinates' # (x, y, w, h) RAW_PREFIX = 'raw_' # - -",
"DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return os.path.join(DATA_DIR,",
"- - - - - - - - - # DEFAULT_DETECTED_IMAGE_DIR = os.path.join(OUTPUT_DIR,",
"- - - - - - - - # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION",
"Representative dataset BAHNHOF = 'bahnhof' WAGEN = 'wagen' TRAKTION = 'traktion' # Output",
"- - - - - - - - - # # ONNX converter",
"- - - - - - - - - # # CoreML converter",
"DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD = 0.25 #",
"- - - - # # CoreML converter # - - - -",
"w, h) RAW_PREFIX = 'raw_' # - - - - - - -",
"- - - # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names",
"# TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt' # Format TFLITE = 'tflite' SAVED_MODEL",
"names CONFIDENCE_NAME = 'confidence' # list of class scores COORDINATES_NAME = 'coordinates' #",
"500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip'",
"- - - - - - - - - - - # ONNX_SUFFIX",
"'float32' FLOAT16 = 'float16' INT8 = 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32'",
"0.45 DEFAULT_CONF_THRESHOLD = 0.25 # - - - - - - - -",
"- - - - - - - - - - # # CoreML",
"score + 4 bounding box coordinates NORMALIZATION_FACTOR = 255. # Input names IMAGE_NAME",
"- - - - - # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' #",
"SCORE_SLICE = (4, 5) CLASSES_SLICE = (5, 0) NB_OUTPUTS = 5 # 1",
"# -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' #",
"- - - - - - - - - - - # DEFAULT_MODEL_OUTPUT_DIR",
"NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou threshold' CONF_NAME = 'conf",
"# (x, y, w, h) RAW_PREFIX = 'raw_' # - - - -",
"objectness score + 4 bounding box coordinates NORMALIZATION_FACTOR = 255. # Input names",
"'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou threshold' CONF_NAME =",
"box coordinates NORMALIZATION_FACTOR = 255. # Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX =",
"additional default values # - - - - - - - - -",
"'category' # class index SCORES_NAME = 'score' # confidence score NUMBER_NAME = 'number",
"# class index SCORES_NAME = 'score' # confidence score NUMBER_NAME = 'number of",
"- - - - - - - - - # DATA_DIR = os.path.join('data')",
"- - # # CoreML converter # - - - - - -",
"names IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou",
"COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names CONFIDENCE_NAME = 'confidence' #",
"= '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE =",
"object in the image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME = 'predictions' # -",
"- - - - - - - # # Inference # - -",
"OPSET = 12 # -------------------------------------------------------------------------------------------------------------------- # # Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME",
"= WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip')",
"- - # DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32'",
"# # Constants # -------------------------------------------------------------------------------------------------------------------- # # General # - - - -",
"- - - - - # # CoreML converter # - - -",
"'bahnhof' WAGEN = 'wagen' TRAKTION = 'traktion' # Output names BOUNDINGBOX_NAME = 'location'",
"Common values # - - - - - - - - - -",
"5 # 1 objectness score + 4 bounding box coordinates NORMALIZATION_FACTOR = 255.",
"- - - - - - - - - - - # COREML_SUFFIX",
"12 # -------------------------------------------------------------------------------------------------------------------- # # Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML'",
"- - - # # Inference # - - - - - -",
"BATCH_SIZE = 1 NB_CHANNEL = 3 # x, y, w, h, score, class1,",
"f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - - - - -",
"dataset BAHNHOF = 'bahnhof' WAGEN = 'wagen' TRAKTION = 'traktion' # Output names",
"= 5 # 1 objectness score + 4 bounding box coordinates NORMALIZATION_FACTOR =",
"= 'raw_' # - - - - - - - - - -",
"Inference # - - - - - - - - - - -",
"- - - - - # # Common values # - - -",
"- - - - - - - # # ONNX converter # -",
"os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD = 0.45 DEFAULT_CONF_THRESHOLD",
"- - - - - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data',",
"-------------------------------------------------------------------------------------------------------------------- # # Constants # -------------------------------------------------------------------------------------------------------------------- # # General # - - -",
"- - - # # CoreML converter # - - - - -",
"# -------------------------------------------------------------------------------------------------------------------- # # General # - - - - - - -",
"- # DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16",
"def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - -",
"return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source): return f'https://sbb-ml-public-resources-prod.s3.eu-central-1.amazonaws.com/quantization/{source}_500.zip' # - - - - -",
"- - - - - - - - - - # # TFlite",
"# # Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite'",
"the image DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME = 'predictions' # - - -",
"= 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX =",
"'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8'",
"XY_SLICE = (0, 2) WH_SLICE = (2, 4) SCORE_SLICE = (4, 5) CLASSES_SLICE",
"(x, y, w, h) RAW_PREFIX = 'raw_' # - - - - -",
"x, y, w, h, score, class1, class2, ... XY_SLICE = (0, 2) WH_SLICE",
"# # CoreML converter # - - - - - - - -",
"4 bounding box coordinates NORMALIZATION_FACTOR = 255. # Input names IMAGE_NAME = 'image'",
"FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16' INT8_SUFFIX = '_int8' FULLINT8_SUFFIX = '_fullint8' BATCH_SIZE",
"- - - # # TFlite additional default values # - - -",
"threshold' CONF_NAME = 'conf threshold' # Colors BLUE = '\\033[36m' GREEN = '\\033[32m'",
"results' PREDICTIONS_NAME = 'predictions' # - - - - - - - -",
"- - - - - - - - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models')",
"DETECTIONS_NAME = 'detection results' PREDICTIONS_NAME = 'predictions' # - - - - -",
"# Common values # - - - - - - - - -",
"DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return os.path.join(DATA_DIR, f'{source}_500.zip') def get_dataset_url(source):",
"- - - - - - # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt'",
"(0, 2) WH_SLICE = (2, 4) SCORE_SLICE = (4, 5) CLASSES_SLICE = (5,",
"- # # TFlite additional default values # - - - - -",
"NORMALIZATION_FACTOR = 255. # Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX",
"- - - - # TFLITE_SUFFIX = '.tflite' LABELS_NAME = 'labels.txt' # Format",
"- - - - - - - # TFLITE_SUFFIX = '.tflite' LABELS_NAME =",
"'padded' SIMPLE = 'simple' COMBINED = 'combined' # Representative dataset BAHNHOF = 'bahnhof'",
"'number of detections' # number of detected object in the image DETECTIONS_NAME =",
"- - - - - - - - - - # TFLITE_SUFFIX =",
"- - - - - - - - - - # DEFAULT_SOURCE_DATASET =",
"scores COORDINATES_NAME = 'coordinates' # (x, y, w, h) RAW_PREFIX = 'raw_' #",
"= 'combined' # Representative dataset BAHNHOF = 'bahnhof' WAGEN = 'wagen' TRAKTION =",
"# DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 = 'float32' FLOAT16 =",
"= '\\033[31m' YELLOW = '\\033[33m' PURPLE = '\\033[34m' END_COLOR = '\\033[0m' BOLD =",
"- # COREML_SUFFIX = '.mlmodel' TORCHSCRIPT_SUFFIX = '.torchscript.pt' # Outputs names CONFIDENCE_NAME =",
"IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX = '_quantized' IOU_NAME = 'iou threshold'",
"= 255. # Input names IMAGE_NAME = 'image' NORMALIZED_SUFFIX = '_normalized' QUANTIZED_SUFFIX =",
"- - - - - - - - - # DEFAULT_SOURCE_DATASET = WAGEN",
"# # TFLite converter # - - - - - - - -",
"COMBINED = 'combined' # Representative dataset BAHNHOF = 'bahnhof' WAGEN = 'wagen' TRAKTION",
"names BOUNDINGBOX_NAME = 'location' # (y1, x1, y2, x2) CLASSES_NAME = 'category' #",
"YELLOW = '\\033[33m' PURPLE = '\\033[34m' END_COLOR = '\\033[0m' BOLD = '\\033[1m' #",
"'float16' INT8 = 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX = '_float32' FLOAT16_SUFFIX = '_float16'",
"- - - - - - - - - - # COREML_SUFFIX =",
"- - - - - # ONNX_SUFFIX = '.onnx' OPSET = 12 #",
"DEFAULT_CONF_THRESHOLD = 0.25 # - - - - - - - - -",
"- # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION =",
"'.torchscript.pt' # Outputs names CONFIDENCE_NAME = 'confidence' # list of class scores COORDINATES_NAME",
"# Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME = 'yolov5-coreML' DEFAULT_TFLITE_NAME = 'yolov5-TFLite' DEFAULT_ONNX_NAME",
"FLOAT32 = 'float32' FLOAT16 = 'float16' INT8 = 'int8' FULLINT8 = 'fullint8' FLOAT32_SUFFIX",
"- - - - - - - - - # ONNX_SUFFIX = '.onnx'",
"ONNX converter # - - - - - - - - - -",
"(y1, x1, y2, x2) CLASSES_NAME = 'category' # class index SCORES_NAME = 'score'",
"BOUNDINGBOX_NAME = 'location' # (y1, x1, y2, x2) CLASSES_NAME = 'category' # class",
"-------------------------------------------------------------------------------------------------------------------- # # General # - - - - - - - -",
"# Format TFLITE = 'tflite' SAVED_MODEL = 'saved_model' GRAPH_DEF_SUFFIX = '.pb' # NMS",
"# DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500 DEFAULT_MAX_NUMBER_DETECTION = 20 def get_zipfile_path(source): return",
"- - - - # # Inference # - - - - -",
"- - - - - - # DEFAULT_SOURCE_DATASET = WAGEN DEFAULT_NB_CALIBRATION = 500",
"- - - # DATA_DIR = os.path.join('data') OUTPUT_DIR = os.path.join(DATA_DIR, 'output') FLOAT32 =",
"- - # # Inference # - - - - - - -",
"# NMS PADDED = 'padded' SIMPLE = 'simple' COMBINED = 'combined' # Representative",
"'yolov5-TFLite' DEFAULT_ONNX_NAME = 'yolov5-ONNX' # - - - - - - - -",
"- - - # DEFAULT_MODEL_OUTPUT_DIR = os.path.join(OUTPUT_DIR, 'converted_models') DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt')",
"'confidence' # list of class scores COORDINATES_NAME = 'coordinates' # (x, y, w,",
"- - - - # # TFlite additional default values # - -",
"- - - # # ONNX converter # - - - - -",
"= 12 # -------------------------------------------------------------------------------------------------------------------- # # Default values # -------------------------------------------------------------------------------------------------------------------- # DEFAULT_COREML_NAME =",
"# # Common values # - - - - - - - -",
"- - - - - - # # TFLite converter # - -",
"DEFAULT_PT_MODEL = os.path.join('data', 'models', 'best.pt') DEFAULT_INPUT_RESOLUTION = 640 DEFAULT_QUANTIZATION_TYPE = FLOAT32 DEFAULT_IOU_THRESHOLD =",
"import os # -------------------------------------------------------------------------------------------------------------------- # # Constants # -------------------------------------------------------------------------------------------------------------------- # # General #",
"- - - - - - - - - # # TFLite converter",
"- - - - - - - - - - # # Inference",
"3 # x, y, w, h, score, class1, class2, ... XY_SLICE = (0,",
"'raw_' # - - - - - - - - - - -"
] |
[
"return else: from subsworld import subsworld subsworld() elif val == 1: print('\\nUnknown Error",
"import subsworld subsworld() elif val == 1: print('\\nUnknown Error Occured... ') return elif",
"0: print('\\nSubtitle Downloaded Successfully... ') if not input('\\nPlease press enter to keep searching",
"'): return else: from subsworld import subsworld subsworld() elif val == 1: print('\\nUnknown",
"2: print('\\nSubtitles not found... ') if not input('\\nPlease press enter to exit or",
"not input('\\nPlease press enter to keep searching the same or press any other",
"found... ') if not input('\\nPlease press enter to exit or press any other",
"Error Occured... ') return elif val == 2: print('\\nSubtitles not found... ') if",
"press enter to keep searching the same or press any other key to",
"search other substitle: '): print('Thanks for using subsworld ... ') exit(0) else: return",
"enter to keep searching the same or press any other key to search",
"val == 1: print('\\nUnknown Error Occured... ') return elif val == 2: print('\\nSubtitles",
"<filename>subsworld/subsEnd.py def endSubStatus(val): if val == 0: print('\\nSubtitle Downloaded Successfully... ') if not",
"val == 2: print('\\nSubtitles not found... ') if not input('\\nPlease press enter to",
"or press any other key to search other substitle: '): print('Thanks for using",
"input('\\nPlease press enter to keep searching the same or press any other key",
"not found... ') if not input('\\nPlease press enter to exit or press any",
"') return elif val == 2: print('\\nSubtitles not found... ') if not input('\\nPlease",
"== 0: print('\\nSubtitle Downloaded Successfully... ') if not input('\\nPlease press enter to keep",
"return elif val == 2: print('\\nSubtitles not found... ') if not input('\\nPlease press",
"searching the same or press any other key to search other substitle: '):",
"if not input('\\nPlease press enter to exit or press any other key to",
"other key to search other substitle: '): print('Thanks for using subsworld ... ')",
"subsworld import subsworld subsworld() elif val == 1: print('\\nUnknown Error Occured... ') return",
"Downloaded Successfully... ') if not input('\\nPlease press enter to keep searching the same",
"other substitle: '): return else: from subsworld import subsworld subsworld() elif val ==",
"elif val == 1: print('\\nUnknown Error Occured... ') return elif val == 2:",
"key to search other substitle: '): print('Thanks for using subsworld ... ') exit(0)",
"substitle: '): return else: from subsworld import subsworld subsworld() elif val == 1:",
"') if not input('\\nPlease press enter to keep searching the same or press",
"press any other key to search other substitle: '): return else: from subsworld",
"any other key to search other substitle: '): print('Thanks for using subsworld ...",
"press enter to exit or press any other key to search other substitle:",
"keep searching the same or press any other key to search other substitle:",
"if not input('\\nPlease press enter to keep searching the same or press any",
"or press any other key to search other substitle: '): return else: from",
"else: from subsworld import subsworld subsworld() elif val == 1: print('\\nUnknown Error Occured...",
"Successfully... ') if not input('\\nPlease press enter to keep searching the same or",
"== 2: print('\\nSubtitles not found... ') if not input('\\nPlease press enter to exit",
"exit or press any other key to search other substitle: '): print('Thanks for",
"press any other key to search other substitle: '): print('Thanks for using subsworld",
"subsworld subsworld() elif val == 1: print('\\nUnknown Error Occured... ') return elif val",
"subsworld() elif val == 1: print('\\nUnknown Error Occured... ') return elif val ==",
"not input('\\nPlease press enter to exit or press any other key to search",
"val == 0: print('\\nSubtitle Downloaded Successfully... ') if not input('\\nPlease press enter to",
"search other substitle: '): return else: from subsworld import subsworld subsworld() elif val",
"input('\\nPlease press enter to exit or press any other key to search other",
"if val == 0: print('\\nSubtitle Downloaded Successfully... ') if not input('\\nPlease press enter",
"endSubStatus(val): if val == 0: print('\\nSubtitle Downloaded Successfully... ') if not input('\\nPlease press",
"') if not input('\\nPlease press enter to exit or press any other key",
"1: print('\\nUnknown Error Occured... ') return elif val == 2: print('\\nSubtitles not found...",
"to search other substitle: '): return else: from subsworld import subsworld subsworld() elif",
"any other key to search other substitle: '): return else: from subsworld import",
"to keep searching the same or press any other key to search other",
"the same or press any other key to search other substitle: '): return",
"from subsworld import subsworld subsworld() elif val == 1: print('\\nUnknown Error Occured... ')",
"to search other substitle: '): print('Thanks for using subsworld ... ') exit(0) else:",
"key to search other substitle: '): return else: from subsworld import subsworld subsworld()",
"same or press any other key to search other substitle: '): return else:",
"elif val == 2: print('\\nSubtitles not found... ') if not input('\\nPlease press enter",
"enter to exit or press any other key to search other substitle: '):",
"== 1: print('\\nUnknown Error Occured... ') return elif val == 2: print('\\nSubtitles not",
"to exit or press any other key to search other substitle: '): print('Thanks",
"print('\\nSubtitle Downloaded Successfully... ') if not input('\\nPlease press enter to keep searching the",
"other key to search other substitle: '): return else: from subsworld import subsworld",
"print('\\nUnknown Error Occured... ') return elif val == 2: print('\\nSubtitles not found... ')",
"print('\\nSubtitles not found... ') if not input('\\nPlease press enter to exit or press",
"def endSubStatus(val): if val == 0: print('\\nSubtitle Downloaded Successfully... ') if not input('\\nPlease",
"Occured... ') return elif val == 2: print('\\nSubtitles not found... ') if not"
] |
[
"be used for geocoding address points in ' + 'Poland along with the",
"engine with three map layers: ' + 'OpenStreetMap, Google Maps and Stamens Map.',",
"information about a given address point and the ' + 'building assigned to",
"form of search engine with three map layers: ' + 'OpenStreetMap, Google Maps",
"Google Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5",
"author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\",",
"Python, which can be used for geocoding address points in ' + 'Poland",
"address point and the ' + 'building assigned to this address. GeocoderPL has",
"url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml', 'geocoder', 'pandas', 'matplotlib', 'setuptools', 'sqlalchemy',",
"keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy',",
"address points in ' + 'Poland along with the possibility to display basic",
"+ 'Poland along with the possibility to display basic information about a given",
"this address. GeocoderPL has a form of search engine with three map layers:",
"setuptools import setup setup( name='geocoderpl', version='1.1', description='GeocoderPL is an application written in Python,",
"name='geocoderpl', version='1.1', description='GeocoderPL is an application written in Python, which can be used",
"geocoding numpy pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5',",
"geocoding address points in ' + 'Poland along with the possibility to display",
"which can be used for geocoding address points in ' + 'Poland along",
"packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml', 'geocoder', 'pandas', 'matplotlib', 'setuptools', 'sqlalchemy', 'python-dotenv'],",
"' + 'Poland along with the possibility to display basic information about a",
"the ' + 'building assigned to this address. GeocoderPL has a form of",
"Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3 gdal-python",
"description='GeocoderPL is an application written in Python, which can be used for geocoding",
"folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml', 'geocoder', 'pandas', 'matplotlib', 'setuptools',",
"Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial",
"assigned to this address. GeocoderPL has a form of search engine with three",
"used for geocoding address points in ' + 'Poland along with the possibility",
"geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml',",
"license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'],",
"install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml', 'geocoder', 'pandas', 'matplotlib', 'setuptools', 'sqlalchemy', 'python-dotenv'], )",
"a given address point and the ' + 'building assigned to this address.",
"setup( name='geocoderpl', version='1.1', description='GeocoderPL is an application written in Python, which can be",
"to display basic information about a given address point and the ' +",
"superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml', 'geocoder', 'pandas', 'matplotlib',",
"has a form of search engine with three map layers: ' + 'OpenStreetMap,",
"setup setup( name='geocoderpl', version='1.1', description='GeocoderPL is an application written in Python, which can",
"along with the possibility to display basic information about a given address point",
"about a given address point and the ' + 'building assigned to this",
"possibility to display basic information about a given address point and the '",
"import setup setup( name='geocoderpl', version='1.1', description='GeocoderPL is an application written in Python, which",
"given address point and the ' + 'building assigned to this address. GeocoderPL",
"pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj',",
"and the ' + 'building assigned to this address. GeocoderPL has a form",
"map layers: ' + 'OpenStreetMap, Google Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT",
"<reponame>GML22/GeocoderPL from setuptools import setup setup( name='geocoderpl', version='1.1', description='GeocoderPL is an application written",
"'OpenStreetMap, Google Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy",
"in ' + 'Poland along with the possibility to display basic information about",
"for geocoding address points in ' + 'Poland along with the possibility to",
"sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml', 'geocoder',",
"' + 'OpenStreetMap, Google Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine",
"author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\",",
"is an application written in Python, which can be used for geocoding address",
"display basic information about a given address point and the ' + 'building",
"basic information about a given address point and the ' + 'building assigned",
"a form of search engine with three map layers: ' + 'OpenStreetMap, Google",
"layers: ' + 'OpenStreetMap, Google Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\",",
"address. GeocoderPL has a form of search engine with three map layers: '",
"application written in Python, which can be used for geocoding address points in",
"the possibility to display basic information about a given address point and the",
"'Poland along with the possibility to display basic information about a given address",
"License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium',",
"in Python, which can be used for geocoding address points in ' +",
"from setuptools import setup setup( name='geocoderpl', version='1.1', description='GeocoderPL is an application written in",
"version='1.1', description='GeocoderPL is an application written in Python, which can be used for",
"gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode', 'pyproj', 'lxml', 'geocoder', 'pandas',",
"to this address. GeocoderPL has a form of search engine with three map",
"an application written in Python, which can be used for geocoding address points",
"+ 'OpenStreetMap, Google Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding",
"of search engine with three map layers: ' + 'OpenStreetMap, Google Maps and",
"+ 'building assigned to this address. GeocoderPL has a form of search engine",
"search engine with three map layers: ' + 'OpenStreetMap, Google Maps and Stamens",
"point and the ' + 'building assigned to this address. GeocoderPL has a",
"written in Python, which can be used for geocoding address points in '",
"'building assigned to this address. GeocoderPL has a form of search engine with",
"with the possibility to display basic information about a given address point and",
"points in ' + 'Poland along with the possibility to display basic information",
"GeocoderPL has a form of search engine with three map layers: ' +",
"and Stamens Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3",
"numpy pyqt5 geospatial sqlite3 gdal-python superpermutation folium-maps\", url=\"https://github.com/GML22/GeocoderPL\", packages=['geocoderpl'], install_requires=['folium', 'numpy', 'pyqt5', 'unidecode',",
"Map.', author='<NAME>', author_email='<EMAIL>', license=\"MIT License\", keywords=\"search-engine geocoding numpy pyqt5 geospatial sqlite3 gdal-python superpermutation",
"can be used for geocoding address points in ' + 'Poland along with",
"three map layers: ' + 'OpenStreetMap, Google Maps and Stamens Map.', author='<NAME>', author_email='<EMAIL>',",
"with three map layers: ' + 'OpenStreetMap, Google Maps and Stamens Map.', author='<NAME>',",
"' + 'building assigned to this address. GeocoderPL has a form of search"
] |
[
"('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21'))",
"fedora RUN asd RUN yum install x ENV x=y RUN yum install \\",
"under the terms of the BSD license. See the LICENSE file for details.",
"import InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName from tests.constants import DOCKERFILE_GIT class X(object):",
"df = \"\"\"\\ FROM fedora RUN yum install -y python-django CMD blabla\"\"\" tmp_df",
"ENV x=y RUN yum install \\ x \\ y \\ && something else",
"&& rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output == altered_df def test_yuminject_multiline(tmpdir): df",
"workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df,",
"import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName from",
"wrap_cmd) expected_output = \"\"\"\\ FROM fedora RUN asd RUN test && yum install",
"workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict(",
"dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName from tests.constants import DOCKERFILE_GIT class",
"print_function import os try: from collections import OrderedDict except ImportError: # Python 2.6",
"None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run()",
"test && yum install x y && something else && asd CMD asd\"\"\"",
"tests.constants import DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora",
"\"\"\" from __future__ import print_function import os try: from collections import OrderedDict except",
"InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName from tests.constants import DOCKERFILE_GIT class X(object): pass",
"altered_df == expected_output def test_complex_df(): df = \"\"\"\\ FROM fedora RUN asd RUN",
"df = \"\"\"\\ FROM fedora RUN yum install -y httpd \\ uwsgi CMD",
"install -y httpd uwsgi && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD",
"dock.core import DockerTasker from dock.inner import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from",
"RUN yum install -y httpd \\ uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile')",
"\"test-image\") setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink',",
"-f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df == expected_output def test_complex_df(): df = \"\"\"\\",
"None with open(tmp_df, 'r') as fd: altered_df = fd.read() expected_output = r\"\"\"FROM fedora",
"-y httpd uwsgi && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\"",
"Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be",
"the LICENSE file for details. \"\"\" from __future__ import print_function import os try:",
"as fd: fd.write(df) tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X)",
"as fd: altered_df = fd.read() expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo",
"df = \"\"\"\\ FROM fedora RUN asd RUN yum install x ENV x=y",
"'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args':",
"yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output == altered_df",
"tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker = DockerTasker()",
"expected_output = \"\"\"\\ FROM fedora RUN asd RUN test && yum install x",
"yum install -y python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\")",
"import print_function import os try: from collections import OrderedDict except ImportError: # Python",
"assert expected_output == altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora RUN yum",
"\"\"\"\\ FROM fedora RUN yum install -y httpd \\ uwsgi CMD blabla\"\"\" tmp_df",
"ImageName from tests.constants import DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\",
"&& yum install x y && something else && asd CMD asd\"\"\" assert",
"terms of the BSD license. See the LICENSE file for details. \"\"\" from",
"import os try: from collections import OrderedDict except ImportError: # Python 2.6 from",
"setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run()",
"the terms of the BSD license. See the LICENSE file for details. \"\"\"",
"\"RUN test && %(yum_command)s && asd\" out = alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\",
"RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y httpd uwsgi && yum clean",
"x=y RUN yum install \\ x \\ y \\ && something else CMD",
"None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is",
"runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df, 'r') as fd: altered_df =",
"be modified and distributed under the terms of the BSD license. See the",
"'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )]",
"def test_complex_df(): df = \"\"\"\\ FROM fedora RUN asd RUN yum install x",
"os try: from collections import OrderedDict except ImportError: # Python 2.6 from ordereddict",
"PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with",
"expected_output def test_complex_df(): df = \"\"\"\\ FROM fedora RUN asd RUN yum install",
"InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df, 'r') as",
"2015 Red Hat, Inc All rights reserved. This software may be modified and",
"from tests.constants import DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM",
"asd\"\"\" wrap_cmd = \"RUN test && %(yum_command)s && asd\" out = alter_yum_commands(df, wrap_cmd)",
"yum install x && asd ENV x=y RUN test && yum install x",
"-y python-django && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert",
"RUN asd RUN yum install x ENV x=y RUN yum install \\ x",
"test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y httpd \\ uwsgi",
"something else CMD asd\"\"\" wrap_cmd = \"RUN test && %(yum_command)s && asd\" out",
"[OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\")",
"file for details. \"\"\" from __future__ import print_function import os try: from collections",
"yum install x y && something else && asd CMD asd\"\"\" assert out",
"assert altered_df == expected_output def test_complex_df(): df = \"\"\"\\ FROM fedora RUN asd",
"== expected_output def test_complex_df(): df = \"\"\"\\ FROM fedora RUN asd RUN yum",
"install -y python-django && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\"",
"{}}]) runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df, 'r') as fd: altered_df",
"install x ENV x=y RUN yum install \\ x \\ y \\ &&",
"'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled',",
"blabla\"\"\" assert altered_df == expected_output def test_complex_df(): df = \"\"\"\\ FROM fedora RUN",
"uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df)",
"for details. \"\"\" from __future__ import print_function import os try: from collections import",
"blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker =",
"import ImageName from tests.constants import DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir): df =",
"yum install -y httpd \\ uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with",
"setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key,",
"dock.util import ImageName from tests.constants import DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir): df",
"tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key,",
"x=y RUN test && yum install x y && something else && asd",
"DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora RUN yum",
"workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict(",
"CMD asd\"\"\" wrap_cmd = \"RUN test && %(yum_command)s && asd\" out = alter_yum_commands(df,",
"distributed under the terms of the BSD license. See the LICENSE file for",
"import DockerTasker from dock.inner import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo",
"alter_yum_commands from dock.util import ImageName from tests.constants import DOCKERFILE_GIT class X(object): pass def",
"= r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y python-django &&",
"setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink),",
"from __future__ import print_function import os try: from collections import OrderedDict except ImportError:",
"&& yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df ==",
"of the BSD license. See the LICENSE file for details. \"\"\" from __future__",
"metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck',",
"= \"\"\"\\ FROM fedora RUN yum install -y python-django CMD blabla\"\"\" tmp_df =",
"except ImportError: # Python 2.6 from ordereddict import OrderedDict from dock.core import DockerTasker",
"from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util import",
"rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df == expected_output def test_complex_df(): df =",
"import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from",
"DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] =",
"'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}])",
"may be modified and distributed under the terms of the BSD license. See",
"BSD license. See the LICENSE file for details. \"\"\" from __future__ import print_function",
"with open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\")",
"X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1),",
"out = alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM fedora RUN asd RUN test",
"1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora',",
"x ENV x=y RUN yum install \\ x \\ y \\ && something",
"RUN yum install -y python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df,",
"setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args':",
"RUN yum install \\ x \\ y \\ && something else CMD asd\"\"\"",
"\\ uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd:",
"from dock.core import DockerTasker from dock.inner import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner",
"import OrderedDict from dock.core import DockerTasker from dock.inner import DockerBuildWorkflow from dock.plugin import",
"DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] =",
"all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df == expected_output def test_complex_df():",
"fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y httpd uwsgi && yum",
"__future__ import print_function import os try: from collections import OrderedDict except ImportError: #",
"= 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)),",
"= \"\"\"\\ FROM fedora RUN asd RUN yum install x ENV x=y RUN",
"assert InjectYumRepoPlugin.key is not None with open(tmp_df, 'r') as fd: altered_df = fd.read()",
"runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not",
"tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch'",
"CMD blabla\"\"\" assert expected_output == altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora",
"&& asd\" out = alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM fedora RUN asd",
"collections import OrderedDict except ImportError: # Python 2.6 from ordereddict import OrderedDict from",
"&& yum install -y python-django && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo",
"ordereddict import OrderedDict from dock.core import DockerTasker from dock.inner import DockerBuildWorkflow from dock.plugin",
"not None with open(tmp_df, 'r') as fd: altered_df = fd.read() expected_output = r\"\"\"FROM",
"fedora RUN yum install -y httpd \\ uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir),",
"reserved. This software may be modified and distributed under the terms of the",
"[{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df, 'r')",
"setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink),",
"'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert",
"install x && asd ENV x=y RUN test && yum install x y",
"from collections import OrderedDict except ImportError: # Python 2.6 from ordereddict import OrderedDict",
"metalink), ('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder,",
"install -y python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as",
"'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT,",
"printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y httpd uwsgi && yum clean all",
"tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner =",
"y \\ && something else CMD asd\"\"\" wrap_cmd = \"RUN test && %(yum_command)s",
"\"\"\"\\ FROM fedora RUN asd RUN yum install x ENV x=y RUN yum",
"= PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not",
"blabla\"\"\" assert expected_output == altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora RUN",
"tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch'",
"'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key",
"yum install x ENV x=y RUN yum install \\ x \\ y \\",
"fedora RUN yum install -y python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with",
"modified and distributed under the terms of the BSD license. See the LICENSE",
"setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker,",
"= r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y httpd uwsgi",
"clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df == expected_output def",
"X(object): pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y",
"fd.read() expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y",
"printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y python-django && yum clean all &&",
"'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path',",
"def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y python-django CMD",
"yum install -y python-django && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD",
"RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y python-django && yum clean all",
"= DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum']",
"2.6 from ordereddict import OrderedDict from dock.core import DockerTasker from dock.inner import DockerBuildWorkflow",
"= \"\"\"\\ FROM fedora RUN yum install -y httpd \\ uwsgi CMD blabla\"\"\"",
"\"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path',",
"ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name':",
"('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image',",
"\\ y \\ && something else CMD asd\"\"\" wrap_cmd = \"RUN test &&",
"open(tmp_df, 'r') as fd: altered_df = fd.read() expected_output = r\"\"\"FROM fedora RUN printf",
"os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker = DockerTasker() workflow =",
"= DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name',",
"= \"RUN test && %(yum_command)s && asd\" out = alter_yum_commands(df, wrap_cmd) expected_output =",
"'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df, 'r')",
"Red Hat, Inc All rights reserved. This software may be modified and distributed",
"httpd \\ uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as",
"details. \"\"\" from __future__ import print_function import os try: from collections import OrderedDict",
"'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled',",
"dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName",
"RUN test && yum install x y && something else && asd CMD",
")] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path',",
"= PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None",
"\\ && something else CMD asd\"\"\" wrap_cmd = \"RUN test && %(yum_command)s &&",
"= \"\"\"\\ FROM fedora RUN asd RUN test && yum install x &&",
"asd RUN test && yum install x && asd ENV x=y RUN test",
"ENV x=y RUN test && yum install x y && something else &&",
"/etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df == expected_output def test_complex_df(): df = \"\"\"\\ FROM",
"RUN test && yum install x && asd ENV x=y RUN test &&",
"install -y httpd \\ uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df,",
"\"\"\" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may",
"altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y httpd",
"/etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output == altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM",
"r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y httpd uwsgi &&",
"&& yum install -y httpd uwsgi && yum clean all && rm -f",
"setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert",
"ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{",
"\"test-image\") setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink',",
"PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName from tests.constants",
"try: from collections import OrderedDict except ImportError: # Python 2.6 from ordereddict import",
"None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}])",
"from ordereddict import OrderedDict from dock.core import DockerTasker from dock.inner import DockerBuildWorkflow from",
"python-django && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output",
"x \\ y \\ && something else CMD asd\"\"\" wrap_cmd = \"RUN test",
"-y httpd \\ uwsgi CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\")",
"Hat, Inc All rights reserved. This software may be modified and distributed under",
"OrderedDict except ImportError: # Python 2.6 from ordereddict import OrderedDict from dock.core import",
"r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y python-django && yum",
"import OrderedDict except ImportError: # Python 2.6 from ordereddict import OrderedDict from dock.core",
"%(yum_command)s && asd\" out = alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM fedora RUN",
"mode=\"w\") as fd: fd.write(df) tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder',",
"(('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder,",
"setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None)",
"httpd uwsgi && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert",
"LICENSE file for details. \"\"\" from __future__ import print_function import os try: from",
"&& yum install x && asd ENV x=y RUN test && yum install",
"&& asd ENV x=y RUN test && yum install x y && something",
"workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder,",
"open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow,",
"test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y python-django CMD blabla\"\"\"",
"All rights reserved. This software may be modified and distributed under the terms",
"See the LICENSE file for details. \"\"\" from __future__ import print_function import os",
"CMD blabla\"\"\" assert altered_df == expected_output def test_complex_df(): df = \"\"\"\\ FROM fedora",
"asd\" out = alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM fedora RUN asd RUN",
"None) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key",
"from dock.util import ImageName from tests.constants import DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir):",
"wrap_cmd = \"RUN test && %(yum_command)s && asd\" out = alter_yum_commands(df, wrap_cmd) expected_output",
"('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df)",
"with open(tmp_df, 'r') as fd: altered_df = fd.read() expected_output = r\"\"\"FROM fedora RUN",
"\"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y httpd uwsgi && yum clean all &&",
"&& something else CMD asd\"\"\" wrap_cmd = \"RUN test && %(yum_command)s && asd\"",
"-f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output == altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\",
"yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df == expected_output",
"asd ENV x=y RUN test && yum install x y && something else",
"= os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker = DockerTasker() workflow",
"'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder,",
"install \\ x \\ y \\ && something else CMD asd\"\"\" wrap_cmd =",
"= [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )] setattr(workflow.builder, 'image_id',",
">/etc/yum.repos.d/dock-injected.repo && yum install -y python-django && yum clean all && rm -f",
"import DOCKERFILE_GIT class X(object): pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora RUN",
"0)), )] setattr(workflow.builder, 'image_id', \"asd123\") setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder,",
"# Python 2.6 from ordereddict import OrderedDict from dock.core import DockerTasker from dock.inner",
"\"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y python-django && yum clean all && rm",
"tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name':",
"alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM fedora RUN asd RUN test && yum",
"test && %(yum_command)s && asd\" out = alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM",
"DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'),",
"= fd.read() expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install",
"x y && something else && asd CMD asd\"\"\" assert out == expected_output",
"all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output == altered_df def test_yuminject_multiline(tmpdir):",
"yum install -y httpd uwsgi && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo",
"clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output == altered_df def",
"'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner = PreBuildPluginsRunner(tasker, workflow,",
"(c) 2015 Red Hat, Inc All rights reserved. This software may be modified",
"fd: altered_df = fd.read() expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo &&",
"software may be modified and distributed under the terms of the BSD license.",
"= DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name',",
"ImportError: # Python 2.6 from ordereddict import OrderedDict from dock.core import DockerTasker from",
"FROM fedora RUN asd RUN yum install x ENV x=y RUN yum install",
"RUN asd RUN test && yum install x && asd ENV x=y RUN",
"altered_df = fd.read() expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum",
"r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)), )]",
"expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y python-django",
"FROM fedora RUN asd RUN test && yum install x && asd ENV",
"and distributed under the terms of the BSD license. See the LICENSE file",
"from dock.inner import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin,",
"fd: fd.write(df) tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink",
"&& %(yum_command)s && asd\" out = alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM fedora",
"the BSD license. See the LICENSE file for details. \"\"\" from __future__ import",
"This software may be modified and distributed under the terms of the BSD",
"CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df) tasker",
"fd.write(df) tasker = DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink =",
"test_complex_df(): df = \"\"\"\\ FROM fedora RUN asd RUN yum install x ENV",
"else CMD asd\"\"\" wrap_cmd = \"RUN test && %(yum_command)s && asd\" out =",
"DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'),",
"metalink = r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck',",
"'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df, 'r') as fd:",
"'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None) runner",
"fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y python-django && yum clean",
"= DockerTasker() workflow = DockerBuildWorkflow(DOCKERFILE_GIT, \"test-image\") setattr(workflow, 'builder', X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum']",
"= alter_yum_commands(df, wrap_cmd) expected_output = \"\"\"\\ FROM fedora RUN asd RUN test &&",
"\"\"\"\\ FROM fedora RUN asd RUN test && yum install x && asd",
"runner = PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is",
"Inc All rights reserved. This software may be modified and distributed under the",
"InjectYumRepoPlugin.key is not None with open(tmp_df, 'r') as fd: altered_df = fd.read() expected_output",
"FROM fedora RUN yum install -y python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile')",
"\\ x \\ y \\ && something else CMD asd\"\"\" wrap_cmd = \"RUN",
"PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName from tests.constants import",
"X) metalink = 'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1),",
"'r') as fd: altered_df = fd.read() expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\"",
"\"\"\"\\ FROM fedora RUN yum install -y python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir),",
"pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y python-django",
"yum install \\ x \\ y \\ && something else CMD asd\"\"\" wrap_cmd",
"DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util",
"python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd: fd.write(df)",
"expected_output = r\"\"\"FROM fedora RUN printf \"[my-repo]\\nname=my-repo\\nmetalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-\\$releasever&arch=\\$basearch\\nenabled=1\\ngpgcheck=0\\n\" >/etc/yum.repos.d/dock-injected.repo && yum install -y httpd",
"dock.inner import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands",
"OrderedDict from dock.core import DockerTasker from dock.inner import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner,",
"def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y httpd \\",
"&& yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output ==",
"test && yum install x && asd ENV x=y RUN test && yum",
"asd RUN yum install x ENV x=y RUN yum install \\ x \\",
"license. See the LICENSE file for details. \"\"\" from __future__ import print_function import",
"from dock.plugins.pre_inject_yum_repo import InjectYumRepoPlugin, alter_yum_commands from dock.util import ImageName from tests.constants import DOCKERFILE_GIT",
"fedora RUN asd RUN test && yum install x && asd ENV x=y",
"== altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install -y",
"class X(object): pass def test_yuminject_plugin(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install",
"-y python-django CMD blabla\"\"\" tmp_df = os.path.join(str(tmpdir), 'Dockerfile') with open(tmp_df, mode=\"w\") as fd:",
"install x y && something else && asd CMD asd\"\"\" assert out ==",
"DockerTasker from dock.inner import DockerBuildWorkflow from dock.plugin import PreBuildPluginsRunner, PostBuildPluginsRunner from dock.plugins.pre_inject_yum_repo import",
"workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with",
"Python 2.6 from ordereddict import OrderedDict from dock.core import DockerTasker from dock.inner import",
">/etc/yum.repos.d/dock-injected.repo && yum install -y httpd uwsgi && yum clean all && rm",
"x && asd ENV x=y RUN test && yum install x y &&",
"RUN yum install x ENV x=y RUN yum install \\ x \\ y",
"= r'https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch' workflow.repos['yum'] = [OrderedDict( (('name', 'my-repo'), ('metalink', metalink), ('enabled', 1), ('gpgcheck', 0)),",
"&& rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df == expected_output def test_complex_df(): df",
"is not None with open(tmp_df, 'r') as fd: altered_df = fd.read() expected_output =",
"FROM fedora RUN yum install -y httpd \\ uwsgi CMD blabla\"\"\" tmp_df =",
"rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert expected_output == altered_df def test_yuminject_multiline(tmpdir): df =",
"rights reserved. This software may be modified and distributed under the terms of",
"expected_output == altered_df def test_yuminject_multiline(tmpdir): df = \"\"\"\\ FROM fedora RUN yum install",
"uwsgi && yum clean all && rm -f /etc/yum.repos.d/dock-injected.repo CMD blabla\"\"\" assert altered_df",
"[{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None with open(tmp_df,",
"setattr(workflow.builder, 'df_path', tmp_df) setattr(workflow.builder, 'base_image', ImageName(repo='Fedora', tag='21')) setattr(workflow.builder, 'git_dockerfile_path', None) setattr(workflow.builder, 'git_path', None)",
"PreBuildPluginsRunner(tasker, workflow, [{ 'name': InjectYumRepoPlugin.key, 'args': {}}]) runner.run() assert InjectYumRepoPlugin.key is not None"
] |
[
"heatmap = results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected = results['heatmap_reprojected'] return joint_out, heatmap, heatmap_true,",
"heatmap = None heatmap_true = None if not is_eval: heatmap = results['heatmap'] heatmap_true",
"unpack_data(results, is_eval = False): joint_out = results['joint'] heatmap = None heatmap_true = None",
"from dataset.data_model import HandDataModel def unpack_data(results, is_eval = False): joint_out = results['joint'] heatmap",
"= results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected = results['heatmap_reprojected'] return joint_out, heatmap, heatmap_true, heatmap_reprojected",
"dataset.data_model import HandDataModel def unpack_data(results, is_eval = False): joint_out = results['joint'] heatmap =",
"is_eval: heatmap = results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected = results['heatmap_reprojected'] return joint_out, heatmap,",
"= None if not is_eval: heatmap = results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected =",
"None if not is_eval: heatmap = results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected = results['heatmap_reprojected']",
"= results['joint'] heatmap = None heatmap_true = None if not is_eval: heatmap =",
"import HandDataModel def unpack_data(results, is_eval = False): joint_out = results['joint'] heatmap = None",
"results['joint'] heatmap = None heatmap_true = None if not is_eval: heatmap = results['heatmap']",
"joint_out = results['joint'] heatmap = None heatmap_true = None if not is_eval: heatmap",
"not is_eval: heatmap = results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected = results['heatmap_reprojected'] return joint_out,",
"= False): joint_out = results['joint'] heatmap = None heatmap_true = None if not",
"False): joint_out = results['joint'] heatmap = None heatmap_true = None if not is_eval:",
"if not is_eval: heatmap = results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected = results['heatmap_reprojected'] return",
"is_eval = False): joint_out = results['joint'] heatmap = None heatmap_true = None if",
"def unpack_data(results, is_eval = False): joint_out = results['joint'] heatmap = None heatmap_true =",
"= None heatmap_true = None if not is_eval: heatmap = results['heatmap'] heatmap_true =",
"HandDataModel def unpack_data(results, is_eval = False): joint_out = results['joint'] heatmap = None heatmap_true",
"heatmap_true = None if not is_eval: heatmap = results['heatmap'] heatmap_true = results['heatmap_true'] heatmap_reprojected",
"None heatmap_true = None if not is_eval: heatmap = results['heatmap'] heatmap_true = results['heatmap_true']"
] |
[
"range(1,m): for j in range(1,n): if text1[i-1]==text2[j-1]: dp[i][j]=dp[i-1][j-1]+1 else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) return",
"class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1)+1",
"len(text1)+1 n = len(text2)+1 dp = [[0]*n for _ in range(m)] for i",
"str, text2: str) -> int: m = len(text1)+1 n = len(text2)+1 dp =",
"str) -> int: m = len(text1)+1 n = len(text2)+1 dp = [[0]*n for",
"text1: str, text2: str) -> int: m = len(text1)+1 n = len(text2)+1 dp",
"for _ in range(m)] for i in range(1,m): for j in range(1,n): if",
"range(m)] for i in range(1,m): for j in range(1,n): if text1[i-1]==text2[j-1]: dp[i][j]=dp[i-1][j-1]+1 else:",
"<reponame>ruisunyc/-<gh_stars>1-10 class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m =",
"int: m = len(text1)+1 n = len(text2)+1 dp = [[0]*n for _ in",
"_ in range(m)] for i in range(1,m): for j in range(1,n): if text1[i-1]==text2[j-1]:",
"for i in range(1,m): for j in range(1,n): if text1[i-1]==text2[j-1]: dp[i][j]=dp[i-1][j-1]+1 else: dp[i][j]",
"Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1)+1 n",
"= [[0]*n for _ in range(m)] for i in range(1,m): for j in",
"longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1)+1 n = len(text2)+1",
"def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1)+1 n =",
"in range(m)] for i in range(1,m): for j in range(1,n): if text1[i-1]==text2[j-1]: dp[i][j]=dp[i-1][j-1]+1",
"len(text2)+1 dp = [[0]*n for _ in range(m)] for i in range(1,m): for",
"m = len(text1)+1 n = len(text2)+1 dp = [[0]*n for _ in range(m)]",
"[[0]*n for _ in range(m)] for i in range(1,m): for j in range(1,n):",
"dp = [[0]*n for _ in range(m)] for i in range(1,m): for j",
"-> int: m = len(text1)+1 n = len(text2)+1 dp = [[0]*n for _",
"text2: str) -> int: m = len(text1)+1 n = len(text2)+1 dp = [[0]*n",
"= len(text2)+1 dp = [[0]*n for _ in range(m)] for i in range(1,m):",
"= len(text1)+1 n = len(text2)+1 dp = [[0]*n for _ in range(m)] for",
"i in range(1,m): for j in range(1,n): if text1[i-1]==text2[j-1]: dp[i][j]=dp[i-1][j-1]+1 else: dp[i][j] =",
"in range(1,m): for j in range(1,n): if text1[i-1]==text2[j-1]: dp[i][j]=dp[i-1][j-1]+1 else: dp[i][j] = max(dp[i-1][j],dp[i][j-1])",
"for j in range(1,n): if text1[i-1]==text2[j-1]: dp[i][j]=dp[i-1][j-1]+1 else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) return dp[-1][-1]",
"n = len(text2)+1 dp = [[0]*n for _ in range(m)] for i in"
] |
[
"height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals",
"from ..stats import summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices of Heart",
"utf-8 -*- import pandas as pd import matplotlib import matplotlib.pyplot as plt from",
"Parameters ---------- peaks : dict Samples at which cardiac extrema (i.e., R-peaks, systolic",
"Download data >>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks >>> peaks,",
"-*- import pandas as pd import matplotlib import matplotlib.pyplot as plt from .hrv_time",
"LF/HF, respectively. See references for details. Parameters ---------- peaks : dict Samples at",
"and nonlinear domain. Note that a minimum duration of the signal containing the",
"of the domains. Returns ------- DataFrame Contains HRV metrics from three domains: -",
"time-, frequency-, and nonlinear domain. Note that a minimum duration of the signal",
"coding: utf-8 -*- import pandas as pd import matplotlib import matplotlib.pyplot as plt",
"nonlinear domain. Note that a minimum duration of the signal containing the peaks",
"= _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare",
"overview of heart rate variability metrics and norms. Frontiers in public health, 5,",
"Cardiac electrophysiology review, 6(3), 239-244. - <NAME>., & <NAME>. (2017). An overview of",
"frequency-, and nonlinear domain. Note that a minimum duration of the signal containing",
"Heart Rate Variability (HRV). Computes HRV indices in the time-, frequency-, and nonlinear",
"Variability (HRV). Computes HRV indices in the time-, frequency-, and nonlinear domain. Note",
"HRV indices to be meaninful. For instance, 1, 2 and 5 minutes of",
"in the time-, frequency-, and nonlinear domain. Note that a minimum duration of",
"indices in the time-, frequency-, and nonlinear domain. Note that a minimum duration",
"nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>>",
"Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\")",
"a minimum duration of the signal containing the peaks is recommended for some",
"_hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare = hrv.copy()",
"non-linear (for details see hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear",
"out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) # Plot if",
"matplotlib.pyplot as plt from .hrv_time import hrv_time from .hrv_frequency import hrv_frequency from .hrv_frequency",
"# Plot if show: _hrv_plot(peaks, out, sampling_rate) return out def _hrv_plot(peaks, hrv, sampling_rate=1000):",
"Contains HRV metrics from three domains: - frequency (for details see hrv_frequency) -",
"pd.concat(out, axis=1) # Plot if show: _hrv_plot(peaks, out, sampling_rate) return out def _hrv_plot(peaks,",
"are generates for each of the domains. Returns ------- DataFrame Contains HRV metrics",
"the highest frequency in vhf. By default 1000. show : bool, optional If",
"dict Samples at which cardiac extrema (i.e., R-peaks, systolic peaks) occur. Dictionary returned",
"indices to be meaninful. For instance, 1, 2 and 5 minutes of high",
"See references for details. Parameters ---------- peaks : dict Samples at which cardiac",
"instance, 1, 2 and 5 minutes of high quality signal are the recomended",
"HRV indices in the time-, frequency-, and nonlinear domain. Note that a minimum",
">>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute HRV indices >>>",
"the recomended minima for HF, LF and LF/HF, respectively. See references for details.",
"ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate : int, optional Sampling rate (Hz) of",
"peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute HRV indices >>> nk.hrv(peaks,",
"at which cardiac extrema (i.e., R-peaks, systolic peaks) occur. Dictionary returned by ecg_findpeaks,",
"out, sampling_rate) return out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec =",
"review, 6(3), 239-244. - <NAME>., & <NAME>. (2017). An overview of heart rate",
"for HF, LF and LF/HF, respectively. See references for details. Parameters ---------- peaks",
"<NAME>., & <NAME>. (2017). An overview of heart rate variability metrics and norms.",
"as plt from .hrv_time import hrv_time from .hrv_frequency import hrv_frequency from .hrv_frequency import",
"ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_',",
"DataFrame Contains HRV metrics from three domains: - frequency (for details see hrv_frequency)",
"---------- peaks : dict Samples at which cardiac extrema (i.e., R-peaks, systolic peaks)",
"-------- >>> import neurokit2 as nk >>> >>> # Download data >>> data",
"rate variability metrics and norms. Frontiers in public health, 5, 258. \"\"\" #",
"239-244. - <NAME>., & <NAME>. (2017). An overview of heart rate variability metrics",
"show: _hrv_plot(peaks, out, sampling_rate) return out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False)",
"of high quality signal are the recomended minima for HF, LF and LF/HF,",
"cardiac extrema (i.e., R-peaks, systolic peaks) occur. Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks,",
"import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input from ..stats import summary_plot def hrv(peaks, sampling_rate=1000,",
"Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References ---------- - <NAME>. (2002). Assessing",
"hrv_nonlinear Examples -------- >>> import neurokit2 as nk >>> >>> # Download data",
"ax=ax_distrib) # Poincare plot out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for col",
"5, 258. \"\"\" # Get indices out = [] # initialize empty container",
"Distribution of RR intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib",
"_hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot",
"& <NAME>. (2017). An overview of heart rate variability metrics and norms. Frontiers",
"that a minimum duration of the signal containing the peaks is recommended for",
"ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare =",
"= fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution of RR intervals peaks",
"ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd =",
"= summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_', '')",
"see hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>>",
"from .hrv_utils import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input from ..stats import summary_plot def",
"peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute HRV indices",
"the signal containing the peaks is recommended for some HRV indices to be",
"hrv_frequency, hrv_nonlinear Examples -------- >>> import neurokit2 as nk >>> >>> # Download",
"in vhf. By default 1000. show : bool, optional If True, returns the",
"Find peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute HRV",
"hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1])",
"high as the highest frequency in vhf. By default 1000. show : bool,",
"# Get indices out = [] # initialize empty container # Gather indices",
"empty container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out =",
": dict Samples at which cardiac extrema (i.e., R-peaks, systolic peaks) occur. Dictionary",
"fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1])",
"metrics and norms. Frontiers in public health, 5, 258. \"\"\" # Get indices",
"returns the plots that are generates for each of the domains. Returns -------",
"..stats import summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices of Heart Rate",
"out = [] # initialize empty container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks,",
"= [col.replace('HRV_', '') for col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) #",
"(ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1])",
"1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of",
"_hrv_sanitize_input from ..stats import summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices of",
">>> >>> # Find peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>>",
"systolic peaks) occur. Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate :",
"Computes HRV indices in the time-, frequency-, and nonlinear domain. Note that a",
"of R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution",
"data >>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks >>> peaks, info",
"hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices of Heart Rate Variability (HRV). Computes HRV",
"electrophysiology review, 6(3), 239-244. - <NAME>., & <NAME>. (2017). An overview of heart",
"grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd",
".hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input from ..stats",
">>> >>> # Download data >>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find",
"_hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1,",
"data = nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"],",
"be meaninful. For instance, 1, 2 and 5 minutes of high quality signal",
"ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate,",
"time (for details see hrv_time) - non-linear (for details see hrv_nonlinear) See Also",
"= fig.add_subplot(spec[:, -1]) # Distribution of RR intervals peaks = _hrv_sanitize_input(peaks) rri =",
".hrv_utils import _hrv_sanitize_input from ..stats import summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes",
"of the signal containing the peaks is recommended for some HRV indices to",
".hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from .hrv_utils",
"peaks is recommended for some HRV indices to be meaninful. For instance, 1,",
"signal in which the peaks occur. Should be at least twice as high",
"hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>> import neurokit2 as nk >>> >>> #",
">>> # Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References ---------- - <NAME>.",
"sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare = hrv.copy() out_poincare.columns",
"-1]) # Distribution of RR intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate,",
"generates for each of the domains. Returns ------- DataFrame Contains HRV metrics from",
"pd import matplotlib import matplotlib.pyplot as plt from .hrv_time import hrv_time from .hrv_frequency",
".hrv_utils import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input from ..stats import summary_plot def hrv(peaks,",
"highest frequency in vhf. By default 1000. show : bool, optional If True,",
"cardiac signal in which the peaks occur. Should be at least twice as",
"= _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True)",
"signal are the recomended minima for HF, LF and LF/HF, respectively. See references",
"import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from .hrv_utils import",
"hrv_frequency) - time (for details see hrv_time) - non-linear (for details see hrv_nonlinear)",
"int, optional Sampling rate (Hz) of the continuous cardiac signal in which the",
"_hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri",
"# Find peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute",
"(Hz) of the continuous cardiac signal in which the peaks occur. Should be",
"- <NAME>., & <NAME>. (2017). An overview of heart rate variability metrics and",
".hrv_frequency import hrv_frequency from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear",
"details see hrv_time) - non-linear (for details see hrv_nonlinear) See Also -------- ecg_peaks,",
"nk >>> >>> # Download data >>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>> #",
"ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution of RR intervals peaks = _hrv_sanitize_input(peaks) rri",
"hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>> import",
"recommended for some HRV indices to be meaninful. For instance, 1, 2 and",
"nk.hrv(peaks, sampling_rate=100, show=True) References ---------- - <NAME>. (2002). Assessing heart rate variability from",
"that are generates for each of the domains. Returns ------- DataFrame Contains HRV",
"import hrv_frequency from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import",
"of heart rate variability metrics and norms. Frontiers in public health, 5, 258.",
"import summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices of Heart Rate Variability",
"as the highest frequency in vhf. By default 1000. show : bool, optional",
"def _hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1],",
"and 5 minutes of high quality signal are the recomended minima for HF,",
"Rate Variability (HRV). Computes HRV indices in the time-, frequency-, and nonlinear domain.",
"Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate : int, optional Sampling",
"[] # initialize empty container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks,",
"of Heart Rate Variability (HRV). Computes HRV indices in the time-, frequency-, and",
"for some HRV indices to be meaninful. For instance, 1, 2 and 5",
"= matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0,",
"for col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot rri,",
"LF and LF/HF, respectively. See references for details. Parameters ---------- peaks : dict",
"_hrv_plot(peaks, out, sampling_rate) return out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec",
"Should be at least twice as high as the highest frequency in vhf.",
":-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare",
"plots that are generates for each of the domains. Returns ------- DataFrame Contains",
"References ---------- - <NAME>. (2002). Assessing heart rate variability from real-world Holter reports.",
"ax=ax_poincare) # PSD plot rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True) _hrv_frequency_show(rri, out_poincare, sampling_rate=sampling_rate,",
"continuous cardiac signal in which the peaks occur. Should be at least twice",
"ppg_findpeaks, or ppg_peaks. sampling_rate : int, optional Sampling rate (Hz) of the continuous",
"(HRV). Computes HRV indices in the time-, frequency-, and nonlinear domain. Note that",
"to be meaninful. For instance, 1, 2 and 5 minutes of high quality",
"def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices of Heart Rate Variability (HRV). Computes",
"the continuous cardiac signal in which the peaks occur. Should be at least",
">>> # Download data >>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks",
"heart rate variability metrics and norms. Frontiers in public health, 5, 258. \"\"\"",
"_hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input from ..stats import summary_plot",
"meaninful. For instance, 1, 2 and 5 minutes of high quality signal are",
"from real-world Holter reports. Cardiac electrophysiology review, 6(3), 239-244. - <NAME>., & <NAME>.",
">>> nk.hrv(peaks, sampling_rate=100, show=True) References ---------- - <NAME>. (2002). Assessing heart rate variability",
"peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) #",
"in public health, 5, 258. \"\"\" # Get indices out = [] #",
"optional Sampling rate (Hz) of the continuous cardiac signal in which the peaks",
"nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R",
"as pd import matplotlib import matplotlib.pyplot as plt from .hrv_time import hrv_time from",
"nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References",
"interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare = hrv.copy() out_poincare.columns =",
"5 minutes of high quality signal are the recomended minima for HF, LF",
"and norms. Frontiers in public health, 5, 258. \"\"\" # Get indices out",
"= _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare =",
"see hrv_time) - non-linear (for details see hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks,",
"from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from",
"initialize empty container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out",
"neurokit2 as nk >>> >>> # Download data >>> data = nk.data(\"bio_resting_5min_100hz\") >>>",
"= pd.concat(out, axis=1) # Plot if show: _hrv_plot(peaks, out, sampling_rate) return out def",
"_hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True) _hrv_frequency_show(rri,",
"# Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R",
"pandas as pd import matplotlib import matplotlib.pyplot as plt from .hrv_time import hrv_time",
"1, 2 and 5 minutes of high quality signal are the recomended minima",
"For instance, 1, 2 and 5 minutes of high quality signal are the",
"details see hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples --------",
"out_poincare, ax=ax_poincare) # PSD plot rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True) _hrv_frequency_show(rri, out_poincare,",
"show=False): \"\"\" Computes indices of Heart Rate Variability (HRV). Computes HRV indices in",
"# PSD plot rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True) _hrv_frequency_show(rri, out_poincare, sampling_rate=sampling_rate, ax=ax_psd)",
"- time (for details see hrv_time) - non-linear (for details see hrv_nonlinear) See",
"public health, 5, 258. \"\"\" # Get indices out = [] # initialize",
"real-world Holter reports. Cardiac electrophysiology review, 6(3), 239-244. - <NAME>., & <NAME>. (2017).",
"See Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>> import neurokit2",
"# initialize empty container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate))",
"axis=1) # Plot if show: _hrv_plot(peaks, out, sampling_rate) return out def _hrv_plot(peaks, hrv,",
"True, returns the plots that are generates for each of the domains. Returns",
"which the peaks occur. Should be at least twice as high as the",
"(2017). An overview of heart rate variability metrics and norms. Frontiers in public",
"matplotlib import matplotlib.pyplot as plt from .hrv_time import hrv_time from .hrv_frequency import hrv_frequency",
"spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids ax_distrib =",
"from three domains: - frequency (for details see hrv_frequency) - time (for details",
"heart rate variability from real-world Holter reports. Cardiac electrophysiology review, 6(3), 239-244. -",
">>> >>> # Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References ---------- -",
"Get indices out = [] # initialize empty container # Gather indices out.append(hrv_time(peaks,",
"Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>> import neurokit2 as",
"frequency (for details see hrv_frequency) - time (for details see hrv_time) - non-linear",
"indices out = [] # initialize empty container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate))",
"- non-linear (for details see hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency,",
"Note that a minimum duration of the signal containing the peaks is recommended",
"indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References ---------- - <NAME>. (2002). Assessing heart rate",
"for details. Parameters ---------- peaks : dict Samples at which cardiac extrema (i.e.,",
": int, optional Sampling rate (Hz) of the continuous cardiac signal in which",
"sampling_rate=100, show=True) References ---------- - <NAME>. (2002). Assessing heart rate variability from real-world",
"peaks) occur. Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate : int,",
"If True, returns the plots that are generates for each of the domains.",
"ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>> import neurokit2 as nk >>>",
"out_poincare.columns = [col.replace('HRV_', '') for col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare)",
"Plot if show: _hrv_plot(peaks, out, sampling_rate) return out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig",
"in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot rri, sampling_rate =",
"and LF/HF, respectively. See references for details. Parameters ---------- peaks : dict Samples",
"the plots that are generates for each of the domains. Returns ------- DataFrame",
"respectively. See references for details. Parameters ---------- peaks : dict Samples at which",
"rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare",
"see hrv_frequency) - time (for details see hrv_time) - non-linear (for details see",
"import _hrv_sanitize_input from ..stats import summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices",
"health, 5, 258. \"\"\" # Get indices out = [] # initialize empty",
"ppg_peaks. sampling_rate : int, optional Sampling rate (Hz) of the continuous cardiac signal",
"------- DataFrame Contains HRV metrics from three domains: - frequency (for details see",
"Returns ------- DataFrame Contains HRV metrics from three domains: - frequency (for details",
"are the recomended minima for HF, LF and LF/HF, respectively. See references for",
"Sampling rate (Hz) of the continuous cardiac signal in which the peaks occur.",
"= hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri,",
"from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input from",
"rate (Hz) of the continuous cardiac signal in which the peaks occur. Should",
"fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange",
"= plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids",
"indices of Heart Rate Variability (HRV). Computes HRV indices in the time-, frequency-,",
"recomended minima for HF, LF and LF/HF, respectively. See references for details. Parameters",
"be at least twice as high as the highest frequency in vhf. By",
"<NAME>. (2017). An overview of heart rate variability metrics and norms. Frontiers in",
"<NAME>. (2002). Assessing heart rate variability from real-world Holter reports. Cardiac electrophysiology review,",
"intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:,",
"\"\"\" # Get indices out = [] # initialize empty container # Gather",
"\"\"\" Computes indices of Heart Rate Variability (HRV). Computes HRV indices in the",
"variability metrics and norms. Frontiers in public health, 5, 258. \"\"\" # Get",
"bool, optional If True, returns the plots that are generates for each of",
"indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) # Plot",
"Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) #",
"Computes indices of Heart Rate Variability (HRV). Computes HRV indices in the time-,",
"intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution of RR",
"hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare,",
"reports. Cardiac electrophysiology review, 6(3), 239-244. - <NAME>., & <NAME>. (2017). An overview",
"returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate : int, optional Sampling rate",
"# -*- coding: utf-8 -*- import pandas as pd import matplotlib import matplotlib.pyplot",
"hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input",
"(2002). Assessing heart rate variability from real-world Holter reports. Cardiac electrophysiology review, 6(3),",
"plt from .hrv_time import hrv_time from .hrv_frequency import hrv_frequency from .hrv_frequency import _hrv_frequency_show",
"if show: _hrv_plot(peaks, out, sampling_rate) return out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig =",
"# Download data >>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks >>>",
"from .hrv_time import hrv_time from .hrv_frequency import hrv_frequency from .hrv_frequency import _hrv_frequency_show from",
"some HRV indices to be meaninful. For instance, 1, 2 and 5 minutes",
"signal containing the peaks is recommended for some HRV indices to be meaninful.",
"as high as the highest frequency in vhf. By default 1000. show :",
".hrv_time import hrv_time from .hrv_frequency import hrv_frequency from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear",
"by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate : int, optional Sampling rate (Hz)",
"domain. Note that a minimum duration of the signal containing the peaks is",
"of the continuous cardiac signal in which the peaks occur. Should be at",
"out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1,",
"out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) # Plot if show: _hrv_plot(peaks, out, sampling_rate)",
"HF, LF and LF/HF, respectively. See references for details. Parameters ---------- peaks :",
"the peaks is recommended for some HRV indices to be meaninful. For instance,",
"is recommended for some HRV indices to be meaninful. For instance, 1, 2",
"import neurokit2 as nk >>> >>> # Download data >>> data = nk.data(\"bio_resting_5min_100hz\")",
"return out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2,",
"sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) # Plot if show: _hrv_plot(peaks, out,",
"import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils import",
"default 1000. show : bool, optional If True, returns the plots that are",
"R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution of",
"in which the peaks occur. Should be at least twice as high as",
"(i.e., R-peaks, systolic peaks) occur. Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks.",
"ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution of RR intervals",
"import matplotlib.pyplot as plt from .hrv_time import hrv_time from .hrv_frequency import hrv_frequency from",
"RR intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri,",
"high quality signal are the recomended minima for HF, LF and LF/HF, respectively.",
"(for details see hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples",
"out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) # Plot if show: _hrv_plot(peaks,",
"Examples -------- >>> import neurokit2 as nk >>> >>> # Download data >>>",
"occur. Should be at least twice as high as the highest frequency in",
"ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd = fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1]) #",
"from .hrv_frequency import hrv_frequency from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from",
"[col.replace('HRV_', '') for col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD",
"extrema (i.e., R-peaks, systolic peaks) occur. Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or",
"details see hrv_frequency) - time (for details see hrv_time) - non-linear (for details",
"ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>> import neurokit2 as nk >>> >>>",
"hrv_time) - non-linear (for details see hrv_nonlinear) See Also -------- ecg_peaks, ppg_peaks, hrv_time,",
"references for details. Parameters ---------- peaks : dict Samples at which cardiac extrema",
"as nk >>> >>> # Download data >>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>>",
"= nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100)",
"- <NAME>. (2002). Assessing heart rate variability from real-world Holter reports. Cardiac electrophysiology",
"domains: - frequency (for details see hrv_frequency) - time (for details see hrv_time)",
"---------- - <NAME>. (2002). Assessing heart rate variability from real-world Holter reports. Cardiac",
"sampling_rate=1000, show=False): \"\"\" Computes indices of Heart Rate Variability (HRV). Computes HRV indices",
"hrv_frequency from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show",
"peaks occur. Should be at least twice as high as the highest frequency",
">>> import neurokit2 as nk >>> >>> # Download data >>> data =",
"metrics from three domains: - frequency (for details see hrv_frequency) - time (for",
"# Distribution of RR intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False)",
"out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for col in out_poincare.columns] ax_poincare =",
"2 and 5 minutes of high quality signal are the recomended minima for",
"the domains. Returns ------- DataFrame Contains HRV metrics from three domains: - frequency",
"import matplotlib import matplotlib.pyplot as plt from .hrv_time import hrv_time from .hrv_frequency import",
"import _hrv_nonlinear_show from .hrv_utils import _hrv_get_rri from .hrv_utils import _hrv_sanitize_input from ..stats import",
"= nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True)",
"HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References ---------- - <NAME>. (2002). Assessing heart",
"plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids ax_distrib",
"frequency in vhf. By default 1000. show : bool, optional If True, returns",
"at least twice as high as the highest frequency in vhf. By default",
"sampling_rate) return out def _hrv_plot(peaks, hrv, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2,",
"norms. Frontiers in public health, 5, 258. \"\"\" # Get indices out =",
"Frontiers in public health, 5, 258. \"\"\" # Get indices out = []",
"1], width_ratios=[1, 1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)')",
"258. \"\"\" # Get indices out = [] # initialize empty container #",
"sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) # Plot if show:",
"hrv_time from .hrv_frequency import hrv_frequency from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear",
"of RR intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib =",
"summary_plot(rri, ax=ax_distrib) # Poincare plot out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for",
"An overview of heart rate variability metrics and norms. Frontiers in public health,",
"Holter reports. Cardiac electrophysiology review, 6(3), 239-244. - <NAME>., & <NAME>. (2017). An",
"info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> # Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100,",
"By default 1000. show : bool, optional If True, returns the plots that",
"vhf. By default 1000. show : bool, optional If True, returns the plots",
"-------- ecg_peaks, ppg_peaks, hrv_time, hrv_frequency, hrv_nonlinear Examples -------- >>> import neurokit2 as nk",
"# Poincare plot out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for col in",
"intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib)",
"(for details see hrv_time) - non-linear (for details see hrv_nonlinear) See Also --------",
"each of the domains. Returns ------- DataFrame Contains HRV metrics from three domains:",
"sampling_rate=sampling_rate)) out = pd.concat(out, axis=1) # Plot if show: _hrv_plot(peaks, out, sampling_rate) return",
".hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from .hrv_utils",
":-1]) ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution of RR intervals peaks = _hrv_sanitize_input(peaks)",
"import hrv_time from .hrv_frequency import hrv_frequency from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import",
"sampling_rate : int, optional Sampling rate (Hz) of the continuous cardiac signal in",
"col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot rri, sampling_rate",
"show=True) References ---------- - <NAME>. (2002). Assessing heart rate variability from real-world Holter",
"width_ratios=[1, 1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution",
"R-peaks, systolic peaks) occur. Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate",
"peaks : dict Samples at which cardiac extrema (i.e., R-peaks, systolic peaks) occur.",
"Assessing heart rate variability from real-world Holter reports. Cardiac electrophysiology review, 6(3), 239-244.",
">>> # Find peaks >>> peaks, info = nk.ecg_peaks(data[\"ECG\"], sampling_rate=100) >>> >>> #",
"optional If True, returns the plots that are generates for each of the",
"twice as high as the highest frequency in vhf. By default 1000. show",
"container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out,",
"'') for col in out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot",
"occur. Dictionary returned by ecg_findpeaks, ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate : int, optional",
"three domains: - frequency (for details see hrv_frequency) - time (for details see",
"# Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References ---------- - <NAME>. (2002).",
"minutes of high quality signal are the recomended minima for HF, LF and",
"sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) #",
"plot out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for col in out_poincare.columns] ax_poincare",
"from .hrv_utils import _hrv_sanitize_input from ..stats import summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\"",
"variability from real-world Holter reports. Cardiac electrophysiology review, 6(3), 239-244. - <NAME>., &",
": bool, optional If True, returns the plots that are generates for each",
"domains. Returns ------- DataFrame Contains HRV metrics from three domains: - frequency (for",
"rate variability from real-world Holter reports. Cardiac electrophysiology review, 6(3), 239-244. - <NAME>.,",
"fig.add_subplot(spec[:, -1]) # Distribution of RR intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks,",
"fig.add_subplot(spec[1, :-1]) ax_poincare = fig.add_subplot(spec[:, -1]) # Distribution of RR intervals peaks =",
"from .hrv_frequency import _hrv_frequency_show from .hrv_nonlinear import hrv_nonlinear from .hrv_nonlinear import _hrv_nonlinear_show from",
"matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1])",
"(for details see hrv_frequency) - time (for details see hrv_time) - non-linear (for",
"containing the peaks is recommended for some HRV indices to be meaninful. For",
"which cardiac extrema (i.e., R-peaks, systolic peaks) occur. Dictionary returned by ecg_findpeaks, ecg_peaks,",
"least twice as high as the highest frequency in vhf. By default 1000.",
"6(3), 239-244. - <NAME>., & <NAME>. (2017). An overview of heart rate variability",
"Poincare plot out_poincare = hrv.copy() out_poincare.columns = [col.replace('HRV_', '') for col in out_poincare.columns]",
"duration of the signal containing the peaks is recommended for some HRV indices",
"quality signal are the recomended minima for HF, LF and LF/HF, respectively. See",
"- frequency (for details see hrv_frequency) - time (for details see hrv_time) -",
"-*- coding: utf-8 -*- import pandas as pd import matplotlib import matplotlib.pyplot as",
"# Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate)) out.append(hrv_nonlinear(peaks, sampling_rate=sampling_rate)) out = pd.concat(out, axis=1)",
"HRV metrics from three domains: - frequency (for details see hrv_frequency) - time",
"out = pd.concat(out, axis=1) # Plot if show: _hrv_plot(peaks, out, sampling_rate) return out",
"out_poincare.columns] ax_poincare = _hrv_nonlinear_show(rri, out_poincare, ax=ax_poincare) # PSD plot rri, sampling_rate = _hrv_get_rri(peaks,",
"_hrv_get_rri from .hrv_utils import _hrv_sanitize_input from ..stats import summary_plot def hrv(peaks, sampling_rate=1000, show=False):",
"minimum duration of the signal containing the peaks is recommended for some HRV",
"for each of the domains. Returns ------- DataFrame Contains HRV metrics from three",
"details. Parameters ---------- peaks : dict Samples at which cardiac extrema (i.e., R-peaks,",
"1000. show : bool, optional If True, returns the plots that are generates",
"= fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel('R-R intervals (ms)') ax_distrib.set_title(\"Distribution of R-R intervals\") ax_psd = fig.add_subplot(spec[1,",
"minima for HF, LF and LF/HF, respectively. See references for details. Parameters ----------",
"Samples at which cardiac extrema (i.e., R-peaks, systolic peaks) occur. Dictionary returned by",
">>> data = nk.data(\"bio_resting_5min_100hz\") >>> >>> # Find peaks >>> peaks, info =",
"summary_plot def hrv(peaks, sampling_rate=1000, show=False): \"\"\" Computes indices of Heart Rate Variability (HRV).",
"sampling_rate=100) >>> >>> # Compute HRV indices >>> nk.hrv(peaks, sampling_rate=100, show=True) References ----------",
"the peaks occur. Should be at least twice as high as the highest",
"import pandas as pd import matplotlib import matplotlib.pyplot as plt from .hrv_time import",
"or ppg_peaks. sampling_rate : int, optional Sampling rate (Hz) of the continuous cardiac",
"the time-, frequency-, and nonlinear domain. Note that a minimum duration of the",
"show : bool, optional If True, returns the plots that are generates for",
"= [] # initialize empty container # Gather indices out.append(hrv_time(peaks, sampling_rate=sampling_rate)) out.append(hrv_frequency(peaks, sampling_rate=sampling_rate))",
"ecg_peaks, ppg_findpeaks, or ppg_peaks. sampling_rate : int, optional Sampling rate (Hz) of the"
] |
[
"\"\"\" disno.objects ~~~~~~~~~~~~~ Independently usable object models for the Discord API. Docs reference:",
"~~~~~~~~~~~~~ Independently usable object models for the Discord API. Docs reference: https://discord.dev :copyright:",
":copyright: (c) 2021-present Qwire Development Team :license: MIT, see LICENSE for more details.",
"usable object models for the Discord API. Docs reference: https://discord.dev :copyright: (c) 2021-present",
"reference: https://discord.dev :copyright: (c) 2021-present Qwire Development Team :license: MIT, see LICENSE for",
"Team :license: MIT, see LICENSE for more details. \"\"\" from .user import *",
"Development Team :license: MIT, see LICENSE for more details. \"\"\" from .user import",
"(c) 2021-present Qwire Development Team :license: MIT, see LICENSE for more details. \"\"\"",
"Docs reference: https://discord.dev :copyright: (c) 2021-present Qwire Development Team :license: MIT, see LICENSE",
"disno.objects ~~~~~~~~~~~~~ Independently usable object models for the Discord API. Docs reference: https://discord.dev",
"API. Docs reference: https://discord.dev :copyright: (c) 2021-present Qwire Development Team :license: MIT, see",
"for the Discord API. Docs reference: https://discord.dev :copyright: (c) 2021-present Qwire Development Team",
"Independently usable object models for the Discord API. Docs reference: https://discord.dev :copyright: (c)",
"models for the Discord API. Docs reference: https://discord.dev :copyright: (c) 2021-present Qwire Development",
"https://discord.dev :copyright: (c) 2021-present Qwire Development Team :license: MIT, see LICENSE for more",
"Qwire Development Team :license: MIT, see LICENSE for more details. \"\"\" from .user",
"the Discord API. Docs reference: https://discord.dev :copyright: (c) 2021-present Qwire Development Team :license:",
"object models for the Discord API. Docs reference: https://discord.dev :copyright: (c) 2021-present Qwire",
"Discord API. Docs reference: https://discord.dev :copyright: (c) 2021-present Qwire Development Team :license: MIT,",
"2021-present Qwire Development Team :license: MIT, see LICENSE for more details. \"\"\" from"
] |
[
"} }) self.assertEqual(in_tf(y), True) z = any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan,",
"import any_nan def in_tf(x): with tf.Session() as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def",
"= any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x =",
"}) self.assertEqual(in_tf(x), False) y = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3,",
"4.3])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False)",
"import math import tensorflow as tf import unittest from tensorstream.helpers.any_nan import any_nan def",
"any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan,",
"any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': { 'z': tf.constant([5.2,",
"'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True) z = any_nan({",
"any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': { 'z': tf.constant([5.2,",
"True) z = any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c':",
"y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x),",
"class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y),",
"math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2),",
"tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y':",
"as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False)",
"def in_tf(x): with tf.Session() as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x",
"tf.Session() as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x),",
"tensorstream.helpers.any_nan import any_nan def in_tf(x): with tf.Session() as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase):",
"self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan,",
"test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0, 2.0]))",
"sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y",
"5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False) y = any_nan({ 'a': tf.constant([3.0,",
"sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan))",
"2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x",
"2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan,",
"x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x",
"self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1,",
"False) y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan, math.nan]))",
"in_tf(x): with tf.Session() as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x =",
"2.3, 4.3])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x),",
"tf import unittest from tensorstream.helpers.any_nan import any_nan def in_tf(x): with tf.Session() as sess:",
"self.assertEqual(in_tf(y), True) z = any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])],",
"5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True) z = any_nan({ 'a': tf.constant([math.nan,",
"5.2]) } }) self.assertEqual(in_tf(y), True) z = any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan),",
"math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]), 'y': tf.constant([math.nan, math.nan]) } }) self.assertEqual(in_tf(z), True)",
"'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False) y = any_nan({ 'a': tf.constant([3.0, 2.0]),",
"'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]),",
"any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0, 2.0]),",
"any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z",
"True) z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x = any_nan({",
"'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True) z = any_nan({ 'a': tf.constant([math.nan, math.nan]),",
"tensorflow as tf import unittest from tensorstream.helpers.any_nan import any_nan def in_tf(x): with tf.Session()",
"math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b':",
"{ 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False) y =",
"= any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z':",
"[tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]), 'y': tf.constant([math.nan, math.nan]) }",
"tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]), 'y': tf.constant([math.nan, math.nan]) } })",
"'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]),",
"math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]), 'y': tf.constant([math.nan,",
"2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4,",
"any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0,",
"'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2])",
"[tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) }",
"def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0,",
"'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': { 'z': tf.constant([5.2, 5.2]),",
"tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]), 'y':",
"AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True)",
"5.2]) } }) self.assertEqual(in_tf(x), False) y = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2),",
"tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False) y = any_nan({ 'a':",
"math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True)",
"tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True) z = any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b':",
"tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True) z = any_nan({ 'a':",
"as tf import unittest from tensorstream.helpers.any_nan import any_nan def in_tf(x): with tf.Session() as",
"2.3, math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y),",
"def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def",
"3.0, 2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z =",
"y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z),",
"= any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True)",
"tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y':",
"from tensorstream.helpers.any_nan import any_nan def in_tf(x): with tf.Session() as sess: return sess.run(x) class",
"self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x =",
"z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x = any_nan({ 'a':",
"} }) self.assertEqual(in_tf(x), False) y = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1,",
"def test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])],",
"{ 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True) z =",
"False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0]))",
"x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y),",
"math import tensorflow as tf import unittest from tensorstream.helpers.any_nan import any_nan def in_tf(x):",
"False) y = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c':",
"any_nan def in_tf(x): with tf.Session() as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self):",
"3.0, 2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self):",
"}) self.assertEqual(in_tf(y), True) z = any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan,",
"tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False) y = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b':",
"'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2])",
"'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]), 'y': tf.constant([math.nan, math.nan])",
"with tf.Session() as sess: return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0))",
"unittest from tensorstream.helpers.any_nan import any_nan def in_tf(x): with tf.Session() as sess: return sess.run(x)",
"'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(y), True) z",
"= any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': { 'z':",
"import tensorflow as tf import unittest from tensorstream.helpers.any_nan import any_nan def in_tf(x): with",
"z = any_nan({ 'a': tf.constant([math.nan, math.nan]), 'b': [tf.constant(math.nan), tf.constant([math.nan, math.nan, math.nan])], 'c': {",
"True) def test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3,",
"tf.constant([2.1, 2.3, 4.3])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } })",
"x = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': {",
"= any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False)",
"'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False) y = any_nan({",
"= any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True)",
"self.assertEqual(in_tf(x), False) y = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])],",
"y = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': {",
"return sess.run(x) class AnyNanSpec(unittest.TestCase): def test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y =",
"import unittest from tensorstream.helpers.any_nan import any_nan def in_tf(x): with tf.Session() as sess: return",
"'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } }) self.assertEqual(in_tf(x), False) y",
"any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y",
"= any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': { 'z':",
"test_any_nan_scalar(self): x = any_nan(tf.constant(4.0)) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self):",
"= any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0,",
"True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y = any_nan(tf.constant([math.nan,",
"[tf.constant(3.2), tf.constant([2.1, 2.3, math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) }",
"test_any_nan_complex_type(self): x = any_nan({ 'a': tf.constant([3.0, 2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c':",
"self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0, 2.0])) self.assertEqual(in_tf(x), False) y =",
"any_nan(tf.constant([math.nan, 3.0, 2.0])) self.assertEqual(in_tf(y), True) z = any_nan(tf.constant([math.nan, math.nan, math.nan])) self.assertEqual(in_tf(z), True) def",
"tf.constant([2.1, 2.3, math.nan])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4, 5.2]) } })",
"math.nan, math.nan])], 'c': { 'z': tf.constant([math.nan, math.nan]), 'y': tf.constant([math.nan, math.nan]) } }) self.assertEqual(in_tf(z),",
"self.assertEqual(in_tf(x), False) y = any_nan(tf.constant(math.nan)) self.assertEqual(in_tf(y), True) def test_any_nan_tensor(self): x = any_nan(tf.constant([4.0, 3.0,",
"2.0]), 'b': [tf.constant(3.2), tf.constant([2.1, 2.3, 4.3])], 'c': { 'z': tf.constant([5.2, 5.2]), 'y': tf.constant([3.4,"
] |
[
"= self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def form_valid(self, form): # This method",
"ValidationError from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms import",
"positions_list = [] for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner = False has_applied =",
"= self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return",
"HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class",
"position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class = VoteForm def form_invalid(self,",
"True if cand.has_won: has_winner = True except Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code,",
"from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms import StartElectionForm,",
"is_applying_open = SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for cand in list: if cand.user.pk",
"no need to fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id,",
"= CreateCandidateApplicationForm def get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position']",
"= [] for (position_id, position) in CANDIDATE_POSITIONS: # If we have all our",
"= form.instance candidate.position = form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self):",
"submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model = Candidate def",
"return reverse('voting:list') def form_valid(self, form): # This method is called when valid form",
"SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for cand in list: if cand.user.pk == self.request.user.pk:",
"= super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def form_valid(self,",
"= False is_applying_open = SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for cand in list:",
"messages from django.views.generic import ListView, CreateView, DetailView, FormView from django.forms import ValidationError from",
"was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model = Candidate",
"POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra'] = extra kwargs['user'] = self.request.user return kwargs",
"called when valid form data has been POSTed. # It should return an",
"from django.forms import ValidationError from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS",
"= positions_list return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return reverse('voting:list')",
"CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import",
"def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS,",
"messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return",
"= True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist: pass",
"in CANDIDATE_POSITIONS: has_winner = False has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open() try: list",
"data has been POSTed. # It should return an HttpResponse. candidate = form.instance",
"CreateView, DetailView, FormView from django.forms import ValidationError from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS,",
"return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model = Candidate form_class =",
"Candidate def get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] =",
"import messages from django.views.generic import ListView, CreateView, DetailView, FormView from django.forms import ValidationError",
"import ListView, CreateView, DetailView, FormView from django.forms import ValidationError from .models import Candidate,",
"have all our winners, no need to fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True)))",
"form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was",
"def get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id'])",
"cand.has_won: has_winner = True except Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code, has_winner, has_applied,",
"self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] =",
"extra = [] for (position_id, position) in CANDIDATE_POSITIONS: # If we have all",
"user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class = VoteForm def form_invalid(self, form):",
"def form_valid(self, form): # This method is called when valid form data has",
"# It should return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs",
"position) in CANDIDATE_POSITIONS: # If we have all our winners, no need to",
"from django.core.urlresolvers import reverse from django.contrib import messages from django.views.generic import ListView, CreateView,",
"form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\")",
"POSTed. # It should return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self):",
"data has been POSTed. # It should return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView,",
"Candidate.objects.filter(position=position_code) for cand in list: if cand.user.pk == self.request.user.pk: has_applied = True if",
"Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from",
"HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse from django.contrib import messages",
"= VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin,",
"self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView):",
"not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list = [] for (position_code, position_name) in CANDIDATE_POSITIONS:",
"is_applying_open, list,)) context['positions'] = positions_list return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was",
"if cand.user.pk == self.request.user.pk: has_applied = True if cand.has_won: has_winner = True except",
"this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra'] =",
"super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None):",
"winners, no need to fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue",
"if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra'] = extra kwargs['user']",
"True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list",
"context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def form_valid(self, form): # This",
"# This method is called when valid form data has been POSTed. #",
"get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def form_valid(self, form): # This method",
"should return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView,",
"valid form data has been POSTed. # It should return an HttpResponse. candidate",
"**kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context",
"CreateView): template_name = 'voting/candidate_apply.html' model = Candidate form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs):",
"len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra'] = extra kwargs['user'] =",
"form data has been POSTed. # It should return an HttpResponse. form.submit_ballot(self.request.user) return",
"= True if cand.has_won: has_winner = True except Candidate.DoesNotExist: list = [] positions_list.append((position_name,",
"messages.SUCCESS, 'Election was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model",
"POSTed. # It should return an HttpResponse. candidate = form.instance candidate.position = form.data['position_id']",
"VoteService.get_position_str(context['position_id']) return context def form_valid(self, form): # This method is called when valid",
"we have all our winners, no need to fill this out. if len(set(Candidate.objects.filter(position=position_id,",
"CreateCandidateApplicationForm def get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] =",
"If we have all our winners, no need to fill this out. if",
"= 'voting/vote.html' form_class = VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView,",
"import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse from django.contrib import",
"for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner = False has_applied = False is_applying_open =",
"form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra = []",
"try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list =",
"candidate.position = form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS,",
"vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list = [] for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner",
"context['position'] = VoteService.get_position_str(context['position_id']) return context def form_valid(self, form): # This method is called",
"candidate = form.instance candidate.position = form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form) def",
"get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return",
"form.instance candidate.position = form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request,",
"an HttpResponse. candidate = form.instance candidate.position = form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView,",
"def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name",
"from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from",
"VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils",
"self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def form_valid(self, form): # This method is",
".models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm,",
"VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin,",
"return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class = VoteForm",
"= SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted",
"== POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra'] = extra kwargs['user'] = self.request.user return",
"SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except",
"return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra = [] for",
"form_class = StartElectionForm def get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed()",
"in CANDIDATE_POSITIONS: # If we have all our winners, no need to fill",
"def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def form_valid(self, form): # This",
"reverse from django.contrib import messages from django.views.generic import ListView, CreateView, DetailView, FormView from",
"= Candidate form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id']",
"has been POSTed. # It should return an HttpResponse. candidate = form.instance candidate.position",
"form): # This method is called when valid form data has been POSTed.",
"try: list = Candidate.objects.filter(position=position_code) for cand in list: if cand.user.pk == self.request.user.pk: has_applied",
"in list: if cand.user.pk == self.request.user.pk: has_applied = True if cand.has_won: has_winner =",
"ListView, CreateView, DetailView, FormView from django.forms import ValidationError from .models import Candidate, VoteBallot,",
"= 'voting/candidate_apply.html' model = Candidate form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs): context =",
"form_valid(self, form): # This method is called when valid form data has been",
"It should return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs =",
"messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html'",
"POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin",
"queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class =",
"'Application was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model =",
"self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra = [] for (position_id, position)",
"out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra'] = extra",
"CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self, **kwargs): context =",
"context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not",
"= form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application",
"'voting/candidate_apply.html' model = Candidate form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs): context = super(CandidateApplyView,",
"context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView):",
"# If we have all our winners, no need to fill this out.",
"'voting/vote.html' form_class = VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form)",
"FormView from django.forms import ValidationError from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus,",
"= VoteService.get_position_str(context['position_id']) return context def form_valid(self, form): # This method is called when",
"from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse from",
"has_winner = True except Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open,",
"It should return an HttpResponse. candidate = form.instance candidate.position = form.data['position_id'] candidate.user =",
"= super(VoteView, self).get_form_kwargs() extra = [] for (position_id, position) in CANDIDATE_POSITIONS: # If",
"context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username)",
"from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView):",
"template_name = 'voting/vote.html' form_class = VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return",
"django.contrib import messages from django.views.generic import ListView, CreateView, DetailView, FormView from django.forms import",
"import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name =",
"def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name",
"get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name =",
"super(VoteView, self).get_form_kwargs() extra = [] for (position_id, position) in CANDIDATE_POSITIONS: # If we",
"import get_object_or_404 from django.core.urlresolvers import reverse from django.contrib import messages from django.views.generic import",
"positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,)) context['positions'] = positions_list return context def get_success_url(self):",
"context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True",
"context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def",
"self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None): return",
"PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html'",
"django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse from django.contrib",
"for (position_id, position) in CANDIDATE_POSITIONS: # If we have all our winners, no",
"= super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def get_object(self,",
"form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully",
"CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model = Candidate form_class = CreateCandidateApplicationForm def get_context_data(self,",
"form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def",
"def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra = [] for (position_id, position) in",
"return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted']",
"list = Candidate.objects.filter(position=position_code) for cand in list: if cand.user.pk == self.request.user.pk: has_applied =",
"return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs()",
"= 'voting/candidate_detail.html' model = Candidate def get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id']",
"= super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently()",
"SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self, **kwargs):",
"def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html'",
"= True except Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,))",
"form_class = VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def",
"django.views.generic import ListView, CreateView, DetailView, FormView from django.forms import ValidationError from .models import",
"was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model = Candidate",
"self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def form_valid(self, form): #",
"VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView):",
"[] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,)) context['positions'] = positions_list return context def",
"reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model = Candidate form_class = CreateCandidateApplicationForm",
"messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def form_valid(self, form): # This method is",
"get_object_or_404 from django.core.urlresolvers import reverse from django.contrib import messages from django.views.generic import ListView,",
"class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model = Candidate form_class = CreateCandidateApplicationForm def",
"= VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self):",
"django.core.urlresolvers import reverse from django.contrib import messages from django.views.generic import ListView, CreateView, DetailView,",
"method is called when valid form data has been POSTed. # It should",
"return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def form_valid(self,",
"(position_code, position_name) in CANDIDATE_POSITIONS: has_winner = False has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open()",
"HttpResponse. candidate = form.instance candidate.position = form.data['position_id'] candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form)",
"super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin,",
"== self.request.user.pk: has_applied = True if cand.has_won: has_winner = True except Candidate.DoesNotExist: list",
"return context def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name",
"valid form data has been POSTed. # It should return an HttpResponse. form.submit_ballot(self.request.user)",
".forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models",
"class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self, **kwargs): context",
"cand.user.pk == self.request.user.pk: has_applied = True if cand.has_won: has_winner = True except Candidate.DoesNotExist:",
"get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class",
"context['position'] = VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class",
"DetailView): template_name = 'voting/candidate_detail.html' model = Candidate def get_context_data(self, **kwargs): context = super(CandidateDetailsView,",
"texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class = StartElectionForm def",
"should return an HttpResponse. candidate = form.instance candidate.position = form.data['position_id'] candidate.user = self.request.user",
"import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm",
"VoteStatus, POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin,",
"= Candidate.objects.filter(position=position_code) for cand in list: if cand.user.pk == self.request.user.pk: has_applied = True",
"This method is called when valid form data has been POSTed. # It",
"Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,)) context['positions'] = positions_list",
"CANDIDATE_POSITIONS: has_winner = False has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open() try: list =",
"context['has_not_voted'] = True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist:",
"reverse('voting:list') def form_valid(self, form): # This method is called when valid form data",
"super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def form_valid(self, form):",
"False is_applying_open = SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for cand in list: if",
"has been POSTed. # It should return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form)",
"self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return reverse('voting:list')",
"return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!') return reverse('voting:list') class",
"all our winners, no need to fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) ==",
"when valid form data has been POSTed. # It should return an HttpResponse.",
"has_applied, is_applying_open, list,)) context['positions'] = positions_list return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election",
"return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin,",
"= [] for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner = False has_applied = False",
"StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService",
"VoteStatus.DoesNotExist: pass positions_list = [] for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner = False",
"HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class =",
"positions_list return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return reverse('voting:list') class",
"reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model = Candidate def get_context_data(self, **kwargs):",
"template_name = 'voting/candidate_detail.html' model = Candidate def get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs)",
"for cand in list: if cand.user.pk == self.request.user.pk: has_applied = True if cand.has_won:",
"position_code, has_winner, has_applied, is_applying_open, list,)) context['positions'] = positions_list return context def get_success_url(self): messages.add_message(self.request,",
"super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted']",
"CANDIDATE_POSITIONS: # If we have all our winners, no need to fill this",
"position_name) in CANDIDATE_POSITIONS: has_winner = False has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open() try:",
"CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model = Candidate def get_context_data(self, **kwargs): context =",
"= SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for cand in list: if cand.user.pk ==",
"'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] =",
"= Candidate def get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position']",
"'Successfully voted!') return reverse('voting:list') def form_valid(self, form): # This method is called when",
"except Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,)) context['positions'] =",
"messages.SUCCESS, 'Application was submitted!') return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model",
"django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse from django.contrib import messages from django.views.generic",
"context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list = [] for (position_code, position_name)",
"template_name = 'voting/candidate_apply.html' model = Candidate form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs): context",
"VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class = VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR,",
"context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def",
"cand in list: if cand.user.pk == self.request.user.pk: has_applied = True if cand.has_won: has_winner",
"vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list = []",
"= SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True try:",
"has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra'] = extra kwargs['user'] = self.request.user",
"context def form_valid(self, form): # This method is called when valid form data",
"[] for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner = False has_applied = False is_applying_open",
"from django.contrib import messages from django.views.generic import ListView, CreateView, DetailView, FormView from django.forms",
"= not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list = [] for (position_code, position_name) in",
"get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return context",
"super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra = [] for (position_id,",
"FormView): template_name = 'voting/vote.html' form_class = VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message)",
"get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class = VoteForm def",
"from django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse from django.contrib import messages from",
"context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status = VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] =",
"return reverse('voting:list') class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model = Candidate def get_context_data(self,",
"self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username'))",
"context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open'] =",
"candidate.user = self.request.user return super(CandidateApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Application was submitted!')",
"= [] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,)) context['positions'] = positions_list return context",
"has_applied = True if cand.has_won: has_winner = True except Candidate.DoesNotExist: list = []",
"is called when valid form data has been POSTed. # It should return",
"context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None): return get_object_or_404(Candidate,",
"successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model = Candidate form_class",
"VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list = [] for (position_code,",
"super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def form_valid(self, form):",
"list = [] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,)) context['positions'] = positions_list return",
"import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self,",
"form data has been POSTed. # It should return an HttpResponse. candidate =",
"get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return",
"StartElectionForm def get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']:",
"self.request.user.pk: has_applied = True if cand.has_won: has_winner = True except Candidate.DoesNotExist: list =",
"list,)) context['positions'] = positions_list return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!')",
"django.forms import ValidationError from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from",
"def get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return",
"get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name =",
"form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!')",
"# It should return an HttpResponse. candidate = form.instance candidate.position = form.data['position_id'] candidate.user",
"import ValidationError from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService, VoteStatus, POSITION_NUMS from .forms",
"template_name = 'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs)",
"= self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'),",
"def get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id'])",
"return context def form_valid(self, form): # This method is called when valid form",
"**kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open']",
"= 'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed']",
"class CandidateDetailsView(PledgeOrActiveRequiredMixin, DetailView): template_name = 'voting/candidate_detail.html' model = Candidate def get_context_data(self, **kwargs): context",
"CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class",
"fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),)) kwargs['extra']",
"messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html'",
"context def get_object(self, queryset=None): return get_object_or_404(Candidate, position=self.kwargs.get('position'), user__username=self.kwargs.get('username')) class VoteView(HasNotVotedRequiredMixin, FormView): template_name =",
"= StartElectionForm def get_context_data(self, **kwargs): context = super(CandidateListView, self).get_context_data(**kwargs) context['voting_closed'] = SiteSettingService.is_voting_closed() if",
"DetailView, FormView from django.forms import ValidationError from .models import Candidate, VoteBallot, CANDIDATE_POSITIONS, VoteService,",
"FormView): template_name = 'voting/candidate_list.html' form_class = StartElectionForm def get_context_data(self, **kwargs): context = super(CandidateListView,",
"if context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status =",
"= VoteStatus.objects.get(voter__username=self.request.user.username) context['has_not_voted'] = not vote_status.has_voted except VoteStatus.DoesNotExist: pass positions_list = [] for",
"has_winner, has_applied, is_applying_open, list,)) context['positions'] = positions_list return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS,",
"texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name",
"has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for cand in",
"'Election was successful!') return reverse('voting:list') class CandidateApplyView(HasNotAppliedRequiredMixin, CreateView): template_name = 'voting/candidate_apply.html' model =",
"False has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for cand",
"class VoteView(HasNotVotedRequiredMixin, FormView): template_name = 'voting/vote.html' form_class = VoteForm def form_invalid(self, form): messages.add_message(self.request,",
"import reverse from django.contrib import messages from django.views.generic import ListView, CreateView, DetailView, FormView",
"been POSTed. # It should return an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def",
"need to fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position,",
"context['positions'] = positions_list return context def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Election was successful!') return",
"from django.views.generic import ListView, CreateView, DetailView, FormView from django.forms import ValidationError from .models",
"voted!') return reverse('voting:list') def form_valid(self, form): # This method is called when valid",
"has_winner = False has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code)",
"from texaslan.site_settings.models import SiteSettingService class CandidateListView(PledgeOrActiveRequiredMixin, FormView): template_name = 'voting/candidate_list.html' form_class = StartElectionForm",
"VoteForm def form_invalid(self, form): messages.add_message(self.request, messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request,",
"kwargs = super(VoteView, self).get_form_kwargs() extra = [] for (position_id, position) in CANDIDATE_POSITIONS: #",
"**kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context",
"[] for (position_id, position) in CANDIDATE_POSITIONS: # If we have all our winners,",
"been POSTed. # It should return an HttpResponse. candidate = form.instance candidate.position =",
"except VoteStatus.DoesNotExist: pass positions_list = [] for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner =",
"if cand.has_won: has_winner = True except Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code, has_winner,",
"get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra = [] for (position_id, position) in CANDIDATE_POSITIONS:",
"'voting/candidate_detail.html' model = Candidate def get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] =",
"Candidate form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs) context['position_id'] =",
"model = Candidate def get_context_data(self, **kwargs): context = super(CandidateDetailsView, self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\")",
"= False has_applied = False is_applying_open = SiteSettingService.is_voting_applications_open() try: list = Candidate.objects.filter(position=position_code) for",
"self).get_form_kwargs() extra = [] for (position_id, position) in CANDIDATE_POSITIONS: # If we have",
"an HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra",
"self).get_context_data(**kwargs) context['position_id'] = self.kwargs.get(\"position\") context['position'] = VoteService.get_position_str(context['position_id']) return context def form_valid(self, form): #",
"SiteSettingService.is_voting_closed() if context['voting_closed']: return context context['voting_open'] = SiteSettingService.is_voting_currently() context['has_not_voted'] = True try: vote_status",
"import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin, HasNotAppliedRequiredMixin, HasNotVotedRequiredMixin from texaslan.site_settings.models import",
"list: if cand.user.pk == self.request.user.pk: has_applied = True if cand.has_won: has_winner = True",
"(position_id, position) in CANDIDATE_POSITIONS: # If we have all our winners, no need",
"VoteService, VoteStatus, POSITION_NUMS from .forms import StartElectionForm, CreateCandidateApplicationForm, VoteForm from texaslan.utils.utils import PledgeOrActiveRequiredMixin,",
"HttpResponse. form.submit_ballot(self.request.user) return super(VoteView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(VoteView, self).get_form_kwargs() extra =",
"return an HttpResponse. candidate = form.instance candidate.position = form.data['position_id'] candidate.user = self.request.user return",
"pass positions_list = [] for (position_code, position_name) in CANDIDATE_POSITIONS: has_winner = False has_applied",
"messages.ERROR, form.errors.as_data()['__all__'][0].message) return super(VoteView, self).form_invalid(form) def get_success_url(self): messages.add_message(self.request, messages.SUCCESS, 'Successfully voted!') return reverse('voting:list')",
"to fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]: continue extra.append((position_id, position, set(Candidate.objects.filter(position=position_id)),))",
"True except Candidate.DoesNotExist: list = [] positions_list.append((position_name, position_code, has_winner, has_applied, is_applying_open, list,)) context['positions']",
"messages.SUCCESS, 'Successfully voted!') return reverse('voting:list') def form_valid(self, form): # This method is called",
"model = Candidate form_class = CreateCandidateApplicationForm def get_context_data(self, **kwargs): context = super(CandidateApplyView, self).get_context_data(**kwargs)",
"our winners, no need to fill this out. if len(set(Candidate.objects.filter(position=position_id, has_won=True))) == POSITION_NUMS[position_id]:"
] |
[
"os.mkdir(str(count)) print('sub process end') if __name__ == '__main__': print('Process %s' % os.getpid()) p",
"= 100 for i in range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process",
"import os import time def run_proc(process_name): print('running subprocess %s(%s)......' % (process_name, os.getpid())) count",
"'__main__': print('Process %s' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub process beginning') p.start()",
"{} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end') if __name__ == '__main__': print('Process %s'",
"def run_proc(process_name): print('running subprocess %s(%s)......' % (process_name, os.getpid())) count = 100 for i",
"count = 100 for i in range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub",
"os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub process beginning') p.start() # p.join() # print('sub",
"args=('test',)) print('sub process beginning') p.start() # p.join() # print('sub process end') print('Process end')",
"= Process(target=run_proc, args=('test',)) print('sub process beginning') p.start() # p.join() # print('sub process end')",
"os.getpid())) count = 100 for i in range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count))",
"print('Process %s' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub process beginning') p.start() #",
"p = Process(target=run_proc, args=('test',)) print('sub process beginning') p.start() # p.join() # print('sub process",
"print('running subprocess %s(%s)......' % (process_name, os.getpid())) count = 100 for i in range(count):",
"time def run_proc(process_name): print('running subprocess %s(%s)......' % (process_name, os.getpid())) count = 100 for",
"print('sub process end') if __name__ == '__main__': print('Process %s' % os.getpid()) p =",
"import time def run_proc(process_name): print('running subprocess %s(%s)......' % (process_name, os.getpid())) count = 100",
"os import time def run_proc(process_name): print('running subprocess %s(%s)......' % (process_name, os.getpid())) count =",
"Process import os import time def run_proc(process_name): print('running subprocess %s(%s)......' % (process_name, os.getpid()))",
"%s' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub process beginning') p.start() # p.join()",
"***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end') if __name__ == '__main__': print('Process %s' %",
"Process(target=run_proc, args=('test',)) print('sub process beginning') p.start() # p.join() # print('sub process end') print('Process",
"process end') if __name__ == '__main__': print('Process %s' % os.getpid()) p = Process(target=run_proc,",
"print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end') if __name__ == '__main__': print('Process",
"if __name__ == '__main__': print('Process %s' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub",
"from multiprocessing import Process import os import time def run_proc(process_name): print('running subprocess %s(%s)......'",
"in range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end') if __name__ ==",
"% os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub process beginning') p.start() # p.join() #",
"subprocess %s(%s)......' % (process_name, os.getpid())) count = 100 for i in range(count): print(\"***",
"for i in range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end') if",
"import Process import os import time def run_proc(process_name): print('running subprocess %s(%s)......' % (process_name,",
"== '__main__': print('Process %s' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub process beginning')",
"%s(%s)......' % (process_name, os.getpid())) count = 100 for i in range(count): print(\"*** {}",
"100 for i in range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end')",
"end') if __name__ == '__main__': print('Process %s' % os.getpid()) p = Process(target=run_proc, args=('test',))",
"% (process_name, os.getpid())) count = 100 for i in range(count): print(\"*** {} ***\".format(i))",
"range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end') if __name__ == '__main__':",
"multiprocessing import Process import os import time def run_proc(process_name): print('running subprocess %s(%s)......' %",
"time.sleep(1) os.mkdir(str(count)) print('sub process end') if __name__ == '__main__': print('Process %s' % os.getpid())",
"__name__ == '__main__': print('Process %s' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('sub process",
"i in range(count): print(\"*** {} ***\".format(i)) time.sleep(1) os.mkdir(str(count)) print('sub process end') if __name__",
"(process_name, os.getpid())) count = 100 for i in range(count): print(\"*** {} ***\".format(i)) time.sleep(1)",
"run_proc(process_name): print('running subprocess %s(%s)......' % (process_name, os.getpid())) count = 100 for i in"
] |
[] |
[
"input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128),",
"= x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train = (x_train / 255.0) - (1.0 -",
"y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\")",
"3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train =",
"= x_train.reshape(-1, 28, 28, 1) x_test = x_test.reshape(-1, 28, 28, 1) layers =",
"2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\") x_test =",
"numpy as np from os import makedirs from os.path import exists import tensorflow",
"tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name): (x_train,",
"makedirs from os.path import exists import tensorflow as tf CLIP_MIN = -0.5 CLIP_MAX",
"CLIP_MAX = 0.5 K = tf.keras.backend mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential",
"for layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit(",
"tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten",
"= mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1) x_test = x_test.reshape(-1, 28, 28,",
"tf.keras.backend mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense",
"padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(),",
"- (1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) model",
"np_utils.to_categorical(y_test, 10) model = Sequential() for layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile(",
"layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train,",
"os.path import exists import tensorflow as tf CLIP_MIN = -0.5 CLIP_MAX = 0.5",
"- (1.0 - CLIP_MAX) x_test = (x_test / 255.0) - (1.0 - CLIP_MAX)",
"from os import makedirs from os.path import exists import tensorflow as tf CLIP_MIN",
"tensorflow as tf CLIP_MIN = -0.5 CLIP_MAX = 0.5 K = tf.keras.backend mnist",
"(x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1) x_test",
"(x_test / 255.0) - (1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test =",
"os import makedirs from os.path import exists import tensorflow as tf CLIP_MIN =",
"= tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test,",
"1) layers = [ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64,",
"x_test = (x_test / 255.0) - (1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10)",
"np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation",
"exists import tensorflow as tf CLIP_MIN = -0.5 CLIP_MAX = 0.5 K =",
"model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if not exists(\"model\"):",
"CLIP_MIN = -0.5 CLIP_MAX = 0.5 K = tf.keras.backend mnist = tf.keras.datasets.mnist np_utils",
"as np from os import makedirs from os.path import exists import tensorflow as",
"/ 255.0) - (1.0 - CLIP_MAX) x_test = (x_test / 255.0) - (1.0",
"[ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"),",
"10) model = Sequential() for layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\",",
"(x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1) x_test = x_test.reshape(-1,",
"= [ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)),",
"Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2,",
"y_test), ) if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if __name__ == \"__main__\": name =",
"sys import numpy as np from os import makedirs from os.path import exists",
"tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2",
"- CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) model = Sequential()",
"Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train = (x_train",
"Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train = (x_train /",
"x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if not exists(\"model\"): makedirs(\"model\")",
"(3, 3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)),",
"= tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D =",
"batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if __name__",
"] x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train = (x_train / 255.0) -",
"import numpy as np from os import makedirs from os.path import exists import",
"import argparse import sys import numpy as np from os import makedirs from",
"tf CLIP_MIN = -0.5 CLIP_MAX = 0.5 K = tf.keras.backend mnist = tf.keras.datasets.mnist",
"tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train",
"model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test,",
"model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50, batch_size=128,",
"model = Sequential() for layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\",",
"255.0) - (1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10)",
"CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) model = Sequential() for",
"(1.0 - CLIP_MAX) x_test = (x_test / 255.0) - (1.0 - CLIP_MAX) y_train",
"x_train = (x_train / 255.0) - (1.0 - CLIP_MAX) x_test = (x_test /",
"28, 28, 1) layers = [ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28, 1)),",
"= tf.keras.utils Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation =",
"10) y_test = np_utils.to_categorical(y_test, 10) model = Sequential() for layer in layers: model.add(layer)",
"x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train = (x_train / 255.0) - (1.0 - CLIP_MAX)",
"metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if",
"Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten",
"Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10),",
"epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if",
"as tf CLIP_MIN = -0.5 CLIP_MAX = 0.5 K = tf.keras.backend mnist =",
"/ 255.0) - (1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test,",
"import makedirs from os.path import exists import tensorflow as tf CLIP_MIN = -0.5",
"import tensorflow as tf CLIP_MIN = -0.5 CLIP_MAX = 0.5 K = tf.keras.backend",
"Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\")",
"= Sequential() for layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"]",
"K = tf.keras.backend mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential Dense",
"= tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten =",
"= tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test, y_test) = mnist.load_data()",
"import sys import numpy as np from os import makedirs from os.path import",
"layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50,",
"28, 28, 1) x_test = x_test.reshape(-1, 28, 28, 1) layers = [ Conv2D(64,",
"MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test, y_test) =",
"x_test.reshape(-1, 28, 28, 1) layers = [ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28,",
"y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1) x_test =",
"MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\") x_test",
"(3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train",
"x_test = x_test.astype(\"float32\") x_train = (x_train / 255.0) - (1.0 - CLIP_MAX) x_test",
") if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if __name__ == \"__main__\": name = str(sys.argv[1])",
"Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D",
"x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train = (x_train / 255.0) - (1.0",
"optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), )",
"1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5),",
"CLIP_MAX) x_test = (x_test / 255.0) - (1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train,",
") model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if not",
"Sequential() for layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] )",
"= x_test.reshape(-1, 28, 28, 1) layers = [ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28,",
"28, 1) layers = [ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"),",
"Dense(10), ] x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train = (x_train / 255.0)",
"np from os import makedirs from os.path import exists import tensorflow as tf",
"tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout",
"1) x_test = x_test.reshape(-1, 28, 28, 1) layers = [ Conv2D(64, (3, 3),",
"28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"),",
"from os.path import exists import tensorflow as tf CLIP_MIN = -0.5 CLIP_MAX =",
"= tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1,",
"= 0.5 K = tf.keras.backend mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential =",
"= (x_test / 255.0) - (1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test",
"(1.0 - CLIP_MAX) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) model =",
"mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout",
"in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train,",
"x_train.reshape(-1, 28, 28, 1) x_test = x_test.reshape(-1, 28, 28, 1) layers = [",
"x_test = x_test.reshape(-1, 28, 28, 1) layers = [ Conv2D(64, (3, 3), padding=\"valid\",",
"= x_test.astype(\"float32\") x_train = (x_train / 255.0) - (1.0 - CLIP_MAX) x_test =",
"l2 = tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train =",
"tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test, y_test)",
"model.add(Activation(\"softmax\")) print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True,",
"tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D",
"validation_data=(x_test, y_test), ) if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if __name__ == \"__main__\": name",
"mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1) x_test = x_test.reshape(-1, 28, 28, 1)",
"Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2",
"= np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) model = Sequential() for layer in",
"(x_train / 255.0) - (1.0 - CLIP_MAX) x_test = (x_test / 255.0) -",
"argparse import sys import numpy as np from os import makedirs from os.path",
"0.5 K = tf.keras.backend mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential",
"import exists import tensorflow as tf CLIP_MIN = -0.5 CLIP_MAX = 0.5 K",
"- CLIP_MAX) x_test = (x_test / 255.0) - (1.0 - CLIP_MAX) y_train =",
"= tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout =",
"verbose=1, validation_data=(x_test, y_test), ) if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if __name__ == \"__main__\":",
"Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train",
"y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) model = Sequential() for layer",
"28, 1) x_test = x_test.reshape(-1, 28, 28, 1) layers = [ Conv2D(64, (3,",
"Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\") x_test = x_test.astype(\"float32\") x_train =",
"x_train = x_train.reshape(-1, 28, 28, 1) x_test = x_test.reshape(-1, 28, 28, 1) layers",
"= (x_train / 255.0) - (1.0 - CLIP_MAX) x_test = (x_test / 255.0)",
"= tf.keras.backend mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils Sequential = tf.keras.models.Sequential Dense =",
"np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) model = Sequential() for layer in layers:",
"Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name): (x_train, y_train),",
"tf.keras.utils Sequential = tf.keras.models.Sequential Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation",
"= tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def train(name):",
"= -0.5 CLIP_MAX = 0.5 K = tf.keras.backend mnist = tf.keras.datasets.mnist np_utils =",
"-0.5 CLIP_MAX = 0.5 K = tf.keras.backend mnist = tf.keras.datasets.mnist np_utils = tf.keras.utils",
"Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 = tf.keras.regularizers.l2 def",
"= tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D l2 =",
"shuffle=True, verbose=1, validation_data=(x_test, y_test), ) if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if __name__ ==",
"tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D = tf.keras.layers.Conv2D MaxPooling2D = tf.keras.layers.MaxPooling2D",
"if not exists(\"model\"): makedirs(\"model\") model.save(f\"./models/{name}.h5\") if __name__ == \"__main__\": name = str(sys.argv[1]) train(name)",
"tf.keras.regularizers.l2 def train(name): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28,",
"3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5),",
"y_test = np_utils.to_categorical(y_test, 10) model = Sequential() for layer in layers: model.add(layer) model.add(Activation(\"softmax\"))",
"def train(name): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28,",
"Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ] x_train = x_train.astype(\"float32\")",
"= tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D =",
"x_test.astype(\"float32\") x_train = (x_train / 255.0) - (1.0 - CLIP_MAX) x_test = (x_test",
"loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1, validation_data=(x_test, y_test),",
"= np_utils.to_categorical(y_test, 10) model = Sequential() for layer in layers: model.add(layer) model.add(Activation(\"softmax\")) print(model.summary())",
"train(name): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1)",
"Conv2D(64, (3, 3)), Activation(\"relu\"), MaxPooling2D(pool_size=(2, 2)), Dropout(0.5), Flatten(), Dense(128), Activation(\"relu\"), Dropout(0.5), Dense(10), ]",
"Dense = tf.keras.layers.Dense Dropout = tf.keras.layers.Dropout Activation = tf.keras.layers.Activation Flatten = tf.keras.layers.Flatten Conv2D",
"<reponame>IharBakhanovich/DeepHyperion<filename>DeepHyperion-MNIST/train_model.py import argparse import sys import numpy as np from os import makedirs",
"layers = [ Conv2D(64, (3, 3), padding=\"valid\", input_shape=(28, 28, 1)), Activation(\"relu\"), Conv2D(64, (3,",
"print(model.summary()) model.compile( loss=\"categorical_crossentropy\", optimizer=\"adadelta\", metrics=[\"accuracy\"] ) model.fit( x_train, y_train, epochs=50, batch_size=128, shuffle=True, verbose=1,",
"255.0) - (1.0 - CLIP_MAX) x_test = (x_test / 255.0) - (1.0 -",
"y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1) x_test = x_test.reshape(-1, 28,"
] |
[
"' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2, )",
"= pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:]) or \"Hello",
"참조: https://blog.storyg.co/rabbitmqs/tutorials/python/02-work-queue import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue',",
"https://blog.storyg.co/rabbitmqs/tutorials/python/02-work-queue import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True)",
"message = ' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode =",
"import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message",
"pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:]) or \"Hello World!\"",
"# 참조: https://blog.storyg.co/rabbitmqs/tutorials/python/02-work-queue import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel()",
"World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2, ) ) print(\" [x] Sent",
"routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2, ) ) print(\" [x] Sent %r\" %",
"<filename>2new_task.py # 참조: https://blog.storyg.co/rabbitmqs/tutorials/python/02-work-queue import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel =",
"channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='',",
"channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties(",
"import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = '",
"sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:])",
"'.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2, ) )",
"connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message,",
"= connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue',",
"or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2, ) ) print(\"",
"connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ' '.join(sys.argv[1:]) or",
"durable=True) message = ' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode",
"body=message, properties=pika.BasicProperties( delivery_mode = 2, ) ) print(\" [x] Sent %r\" % message)",
"pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message =",
"\"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2, ) ) print(\" [x]",
"= ' '.join(sys.argv[1:]) or \"Hello World!\" channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2,",
"channel.basic_publish(exchange='', routing_key='task_queue', body=message, properties=pika.BasicProperties( delivery_mode = 2, ) ) print(\" [x] Sent %r\""
] |
[
"entry containing both shape and record object self.entries = self.sf.shapeRecords() self.bridges = []",
"(tipobj 3), limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges))",
"for bridge in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <= highX and lowY <=",
"bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <= highY\\ and lowX <= bridge.shape.bbox[2]",
"lowX, lowY, highX, highY, output): sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge",
"return bridges def writeBridges(self, lowX, lowY, highX, highY, output): sf = shapefile.Writer(output) sf.fields",
"shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <=",
"Returns bridges inside coordinates bound between points (lowX, lowY) and (highX, highY) def",
"# Only extract shapeRecord entries of bridges (tipobj 3), limit also by coordinates??",
"in self.bridges: if lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <=",
"of bridges (tipobj 3), limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry)",
"shapefile (file extension not required, only filename) self.sf = shapefile.Reader(filename) # Save all",
"highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return bridges def writeBridges(self, lowX, lowY, highX,",
"self.entries: # Only extract shapeRecord entries of bridges (tipobj 3), limit also by",
"points (lowX, lowY) and (highX, highY) def bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges",
"lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <= highY\\ and lowX",
"\"bridges\") return bridges def writeBridges(self, lowX, lowY, highX, highY, output): sf = shapefile.Writer(output)",
"filename) self.sf = shapefile.Reader(filename) # Save all entries in the file, each entry",
"bridge in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1]",
"bound between points (lowX, lowY) and (highX, highY) def bridgesInsideCoords(self, lowX, lowY, highX,",
"also by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges",
"output): sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if lowX",
"Save all entries in the file, each entry containing both shape and record",
"self.bridges = [] for entry in self.entries: # Only extract shapeRecord entries of",
"in self.entries: # Only extract shapeRecord entries of bridges (tipobj 3), limit also",
"highX and lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close() if __name__ ==",
"shapefile.Reader(filename) # Save all entries in the file, each entry containing both shape",
"= self.sf.shapeRecords() self.bridges = [] for entry in self.entries: # Only extract shapeRecord",
"and lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close() if __name__ == \"__main__\":",
"bridge in self.bridges: if lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1]",
"def writeBridges(self, lowX, lowY, highX, highY, output): sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:]",
"lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return bridges def",
"self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <= highY\\",
"<= highY\\ and lowX <= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <=",
"lowX <= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape)",
"bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return bridges def writeBridges(self, lowX, lowY, highX, highY,",
"import shapefile class ShapefileReader: def __init__(self, filename): # Open and read the shapefile",
"lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close() if __name__ == \"__main__\": s",
"the file, each entry containing both shape and record object self.entries = self.sf.shapeRecords()",
"= shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0]",
"print(\"Found\", len(bridges), \"bridges\") return bridges def writeBridges(self, lowX, lowY, highX, highY, output): sf",
"def __init__(self, filename): # Open and read the shapefile (file extension not required,",
"and read the shapefile (file extension not required, only filename) self.sf = shapefile.Reader(filename)",
"entries of bridges (tipobj 3), limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3:",
"object self.entries = self.sf.shapeRecords() self.bridges = [] for entry in self.entries: # Only",
"highX and lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return",
"if lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <= highY\\ and",
"ShapefileReader: def __init__(self, filename): # Open and read the shapefile (file extension not",
"= self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <= highX and",
"bridges def writeBridges(self, lowX, lowY, highX, highY, output): sf = shapefile.Writer(output) sf.fields =",
"highY): bridges = [] for bridge in self.bridges: if lowX <= bridge.shape.bbox[0] <=",
"<= highX and lowY <= bridge.shape.bbox[1] <= highY\\ and lowX <= bridge.shape.bbox[2] <=",
"Only extract shapeRecord entries of bridges (tipobj 3), limit also by coordinates?? if",
"bridge.shape.bbox[1] <= highY\\ and lowX <= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3]",
"# Returns bridges inside coordinates bound between points (lowX, lowY) and (highX, highY)",
"bridges = [] for bridge in self.bridges: if lowX <= bridge.shape.bbox[0] <= highX",
"file, each entry containing both shape and record object self.entries = self.sf.shapeRecords() self.bridges",
"self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <= highX and lowY",
"3), limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges)) #",
"len(bridges), \"bridges\") return bridges def writeBridges(self, lowX, lowY, highX, highY, output): sf =",
"for entry in self.entries: # Only extract shapeRecord entries of bridges (tipobj 3),",
"[] for bridge in self.bridges: if lowX <= bridge.shape.bbox[0] <= highX and lowY",
"and lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return bridges",
"entries in the file, each entry containing both shape and record object self.entries",
"the shapefile (file extension not required, only filename) self.sf = shapefile.Reader(filename) # Save",
"<= bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return bridges def writeBridges(self,",
"extract shapeRecord entries of bridges (tipobj 3), limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"]",
"if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges inside coordinates bound",
"<= highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return bridges def writeBridges(self, lowX, lowY,",
"# print(\"Found\", len(bridges), \"bridges\") return bridges def writeBridges(self, lowX, lowY, highX, highY, output):",
"between points (lowX, lowY) and (highX, highY) def bridgesInsideCoords(self, lowX, lowY, highX, highY):",
"highY) def bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges = [] for bridge in",
"not required, only filename) self.sf = shapefile.Reader(filename) # Save all entries in the",
"entry in self.entries: # Only extract shapeRecord entries of bridges (tipobj 3), limit",
"# Open and read the shapefile (file extension not required, only filename) self.sf",
"def bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges = [] for bridge in self.bridges:",
"__init__(self, filename): # Open and read the shapefile (file extension not required, only",
"record object self.entries = self.sf.shapeRecords() self.bridges = [] for entry in self.entries: #",
"class ShapefileReader: def __init__(self, filename): # Open and read the shapefile (file extension",
"highY, output): sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if",
"<gh_stars>0 import shapefile class ShapefileReader: def __init__(self, filename): # Open and read the",
"lowX <= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge) #",
"# Save all entries in the file, each entry containing both shape and",
"(file extension not required, only filename) self.sf = shapefile.Reader(filename) # Save all entries",
"and record object self.entries = self.sf.shapeRecords() self.bridges = [] for entry in self.entries:",
"and lowY <= bridge.shape.bbox[1] <= highY\\ and lowX <= bridge.shape.bbox[2] <= highX and",
"== 3: self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges inside coordinates bound between points",
"bridges (tipobj 3), limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) #",
"writeBridges(self, lowX, lowY, highX, highY, output): sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:] for",
"containing both shape and record object self.entries = self.sf.shapeRecords() self.bridges = [] for",
"shapeRecord entries of bridges (tipobj 3), limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"] ==",
"in the file, each entry containing both shape and record object self.entries =",
"bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close() if __name__ == \"__main__\": s = ShapefileReader(\"TN_CESTE_L\")",
"<= bridge.shape.bbox[1] <= highY\\ and lowX <= bridge.shape.bbox[2] <= highX and lowY <=",
"and lowX <= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge)",
"sf.fields = self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <= highX",
"all entries in the file, each entry containing both shape and record object",
"3: self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges inside coordinates bound between points (lowX,",
"inside coordinates bound between points (lowX, lowY) and (highX, highY) def bridgesInsideCoords(self, lowX,",
"and lowX <= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record)",
"<= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\",",
"bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\", len(bridges),",
"lowY <= bridge.shape.bbox[1] <= highY\\ and lowX <= bridge.shape.bbox[2] <= highX and lowY",
"coordinates bound between points (lowX, lowY) and (highX, highY) def bridgesInsideCoords(self, lowX, lowY,",
"Open and read the shapefile (file extension not required, only filename) self.sf =",
"= shapefile.Reader(filename) # Save all entries in the file, each entry containing both",
"highX, highY, output): sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge in self.sf.iterShapeRecords():",
"<= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <= highY\\ and lowX <=",
"read the shapefile (file extension not required, only filename) self.sf = shapefile.Reader(filename) #",
"bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\") return bridges def writeBridges(self, lowX,",
"[] for entry in self.entries: # Only extract shapeRecord entries of bridges (tipobj",
"only filename) self.sf = shapefile.Reader(filename) # Save all entries in the file, each",
"lowY) and (highX, highY) def bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges = []",
"and (highX, highY) def bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges = [] for",
"<= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close()",
"lowX, lowY, highX, highY): bridges = [] for bridge in self.bridges: if lowX",
"limit also by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges)) # Returns",
"sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge in self.sf.iterShapeRecords(): if lowX <=",
"in self.sf.iterShapeRecords(): if lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <=",
"(highX, highY) def bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges = [] for bridge",
"self.sf.shapeRecords() self.bridges = [] for entry in self.entries: # Only extract shapeRecord entries",
"lowY, highX, highY, output): sf = shapefile.Writer(output) sf.fields = self.sf.fields[1:] for bridge in",
"by coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges inside",
"extension not required, only filename) self.sf = shapefile.Reader(filename) # Save all entries in",
"self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges inside coordinates bound between points (lowX, lowY)",
"self.bridges: if lowX <= bridge.shape.bbox[0] <= highX and lowY <= bridge.shape.bbox[1] <= highY\\",
"print(len(self.bridges)) # Returns bridges inside coordinates bound between points (lowX, lowY) and (highX,",
"# print(len(self.bridges)) # Returns bridges inside coordinates bound between points (lowX, lowY) and",
"highX, highY): bridges = [] for bridge in self.bridges: if lowX <= bridge.shape.bbox[0]",
"(lowX, lowY) and (highX, highY) def bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges =",
"<= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close() if __name__ == \"__main__\": s =",
"<= highX and lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close() if __name__",
"required, only filename) self.sf = shapefile.Reader(filename) # Save all entries in the file,",
"shape and record object self.entries = self.sf.shapeRecords() self.bridges = [] for entry in",
"shapefile class ShapefileReader: def __init__(self, filename): # Open and read the shapefile (file",
"filename): # Open and read the shapefile (file extension not required, only filename)",
"coordinates?? if entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges inside coordinates",
"= [] for bridge in self.bridges: if lowX <= bridge.shape.bbox[0] <= highX and",
"<= highX and lowY <= bridge.shape.bbox[3] <= highY: bridges.append(bridge) # print(\"Found\", len(bridges), \"bridges\")",
"lowY, highX, highY): bridges = [] for bridge in self.bridges: if lowX <=",
"self.sf = shapefile.Reader(filename) # Save all entries in the file, each entry containing",
"each entry containing both shape and record object self.entries = self.sf.shapeRecords() self.bridges =",
"both shape and record object self.entries = self.sf.shapeRecords() self.bridges = [] for entry",
"self.entries = self.sf.shapeRecords() self.bridges = [] for entry in self.entries: # Only extract",
"highY\\ and lowX <= bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY:",
"highX and lowY <= bridge.shape.bbox[1] <= highY\\ and lowX <= bridge.shape.bbox[2] <= highX",
"bridge.shape.bbox[2] <= highX and lowY <= bridge.shape.bbox[3] <= highY: sf.record(*bridge.record) sf.shape(bridge.shape) sf.close() if",
"bridges inside coordinates bound between points (lowX, lowY) and (highX, highY) def bridgesInsideCoords(self,",
"for bridge in self.bridges: if lowX <= bridge.shape.bbox[0] <= highX and lowY <=",
"bridgesInsideCoords(self, lowX, lowY, highX, highY): bridges = [] for bridge in self.bridges: if",
"entry.record[\"TIPOBJ_CES\"] == 3: self.bridges.append(entry) # print(len(self.bridges)) # Returns bridges inside coordinates bound between",
"= [] for entry in self.entries: # Only extract shapeRecord entries of bridges"
] |
[
"from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ __all__ = ['ModelWithDateRange',",
"django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _",
"if self.start_date and self.end_date\\ and self.start_date > self.end_date: raise ValidationError(_('End date must be",
"abstract = True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField() end_datetime = models.DateTimeField()",
"self.end_datetime: raise ValidationError(_('End datetime must be greater or equal' \\ ' to start",
"import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ __all__",
"from django.utils.translation import ugettext as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): #",
"= models.DateTimeField() end_datetime = models.DateTimeField() # Methods def clean(self): if self.start_datetime and self.end_datetime\\",
"class Meta: abstract = True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField() end_datetime",
"'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date = models.DateField() end_date = models.DateField() # Methods",
"' \\ 'equal to start date.')) # Meta-data class Meta: abstract = True",
"models.DateTimeField() end_datetime = models.DateTimeField() # Methods def clean(self): if self.start_datetime and self.end_datetime\\ and",
"raise ValidationError(_('End datetime must be greater or equal' \\ ' to start datetime.'))",
"> self.end_date: raise ValidationError(_('End date must be greater or ' \\ 'equal to",
"and self.start_date > self.end_date: raise ValidationError(_('End date must be greater or ' \\",
"Attributes start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() # Methods def clean(self): if self.start_datetime",
"equal' \\ ' to start datetime.')) # Meta-data class Meta: abstract = True",
"# Attributes start_date = models.DateField() end_date = models.DateField() # Methods def clean(self): if",
"start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() # Methods def clean(self): if self.start_datetime and",
"self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime must be greater or equal' \\ '",
"# Methods def clean(self): if self.start_datetime and self.end_datetime\\ and self.start_datetime > self.end_datetime: raise",
"\\ 'equal to start date.')) # Meta-data class Meta: abstract = True class",
"ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() # Methods def clean(self):",
"ugettext as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date =",
"= ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date = models.DateField() end_date = models.DateField()",
"if self.start_datetime and self.end_datetime\\ and self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime must be",
"and self.end_date\\ and self.start_date > self.end_date: raise ValidationError(_('End date must be greater or",
"date must be greater or ' \\ 'equal to start date.')) # Meta-data",
"be greater or ' \\ 'equal to start date.')) # Meta-data class Meta:",
"clean(self): if self.start_datetime and self.end_datetime\\ and self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime must",
"django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',]",
"Methods def clean(self): if self.start_date and self.end_date\\ and self.start_date > self.end_date: raise ValidationError(_('End",
"models.DateField() end_date = models.DateField() # Methods def clean(self): if self.start_date and self.end_date\\ and",
"True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() # Methods",
"_ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date = models.DateField() end_date",
"Meta: abstract = True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField() end_datetime =",
"end_date = models.DateField() # Methods def clean(self): if self.start_date and self.end_date\\ and self.start_date",
"# Meta-data class Meta: abstract = True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime =",
"ValidationError from django.utils.translation import ugettext as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model):",
"def clean(self): if self.start_date and self.end_date\\ and self.start_date > self.end_date: raise ValidationError(_('End date",
"self.end_datetime\\ and self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime must be greater or equal'",
"models.DateField() # Methods def clean(self): if self.start_date and self.end_date\\ and self.start_date > self.end_date:",
"class ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() # Methods def",
"must be greater or ' \\ 'equal to start date.')) # Meta-data class",
"date.')) # Meta-data class Meta: abstract = True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime",
"be greater or equal' \\ ' to start datetime.')) # Meta-data class Meta:",
"# Methods def clean(self): if self.start_date and self.end_date\\ and self.start_date > self.end_date: raise",
"self.start_datetime and self.end_datetime\\ and self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime must be greater",
"django.utils.translation import ugettext as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes",
"from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext as",
"as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date = models.DateField()",
"self.start_date and self.end_date\\ and self.start_date > self.end_date: raise ValidationError(_('End date must be greater",
"end_datetime = models.DateTimeField() # Methods def clean(self): if self.start_datetime and self.end_datetime\\ and self.start_datetime",
"or equal' \\ ' to start datetime.')) # Meta-data class Meta: abstract =",
"= models.DateTimeField() # Methods def clean(self): if self.start_datetime and self.end_datetime\\ and self.start_datetime >",
"= True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() #",
"greater or ' \\ 'equal to start date.')) # Meta-data class Meta: abstract",
"raise ValidationError(_('End date must be greater or ' \\ 'equal to start date.'))",
"ValidationError(_('End datetime must be greater or equal' \\ ' to start datetime.')) #",
"greater or equal' \\ ' to start datetime.')) # Meta-data class Meta: abstract",
"# Attributes start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() # Methods def clean(self): if",
"self.end_date: raise ValidationError(_('End date must be greater or ' \\ 'equal to start",
"Attributes start_date = models.DateField() end_date = models.DateField() # Methods def clean(self): if self.start_date",
"start_date = models.DateField() end_date = models.DateField() # Methods def clean(self): if self.start_date and",
"to start date.')) # Meta-data class Meta: abstract = True class ModelWithDateTimeRange(models.Model): #",
"import ugettext as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date",
"must be greater or equal' \\ ' to start datetime.')) # Meta-data class",
"__all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date = models.DateField() end_date =",
"['ModelWithDateRange', 'ModelWithDateTimeRange',] class ModelWithDateRange(models.Model): # Attributes start_date = models.DateField() end_date = models.DateField() #",
"models from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ __all__ =",
"datetime must be greater or equal' \\ ' to start datetime.')) # Meta-data",
"'equal to start date.')) # Meta-data class Meta: abstract = True class ModelWithDateTimeRange(models.Model):",
"and self.end_datetime\\ and self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime must be greater or",
"= models.DateField() # Methods def clean(self): if self.start_date and self.end_date\\ and self.start_date >",
"Methods def clean(self): if self.start_datetime and self.end_datetime\\ and self.start_datetime > self.end_datetime: raise ValidationError(_('End",
"ModelWithDateRange(models.Model): # Attributes start_date = models.DateField() end_date = models.DateField() # Methods def clean(self):",
"class ModelWithDateRange(models.Model): # Attributes start_date = models.DateField() end_date = models.DateField() # Methods def",
"import ValidationError from django.utils.translation import ugettext as _ __all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',] class",
"clean(self): if self.start_date and self.end_date\\ and self.start_date > self.end_date: raise ValidationError(_('End date must",
"self.start_date > self.end_date: raise ValidationError(_('End date must be greater or ' \\ 'equal",
"= models.DateField() end_date = models.DateField() # Methods def clean(self): if self.start_date and self.end_date\\",
"self.end_date\\ and self.start_date > self.end_date: raise ValidationError(_('End date must be greater or '",
"start date.')) # Meta-data class Meta: abstract = True class ModelWithDateTimeRange(models.Model): # Attributes",
"> self.end_datetime: raise ValidationError(_('End datetime must be greater or equal' \\ ' to",
"def clean(self): if self.start_datetime and self.end_datetime\\ and self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime",
"or ' \\ 'equal to start date.')) # Meta-data class Meta: abstract =",
"Meta-data class Meta: abstract = True class ModelWithDateTimeRange(models.Model): # Attributes start_datetime = models.DateTimeField()",
"ValidationError(_('End date must be greater or ' \\ 'equal to start date.')) #",
"models.DateTimeField() # Methods def clean(self): if self.start_datetime and self.end_datetime\\ and self.start_datetime > self.end_datetime:",
"and self.start_datetime > self.end_datetime: raise ValidationError(_('End datetime must be greater or equal' \\"
] |
[
"# # uvm_component # ## Running the phases # Figure 1: A uvm_test",
"# ## Building the testbench hierarchy # ### TestTop (uvm_test_top) # Figure 4:",
"MiddleComp (uvm_test_top.mc) # Figure 5: The middle component is instantiated by # uvm_test_top",
"def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async",
"BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc)",
"build_phase\") def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\")",
"and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async def run_phase(self): self.raise_objection() self.logger.info(f\"{self.get_name()} run phase\")",
"build_phase\") self.mc = MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc)",
"\"mc\" and instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def",
"uvm_test_top # The test is always named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self):",
"self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\") # ###",
"component and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async def run_phase(self): self.raise_objection() self.logger.info(f\"{self.get_name()} run",
"TestTop (uvm_test_top) # Figure 4: pyuvm instantiates TestTop as uvm_test_top # The test",
"middle component is instantiated by # uvm_test_top as \"mc\" and instantiates \"bc\". class",
"run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8",
"as uvm_test_top # The test is always named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def",
"end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5 run_phase\")",
"BottomComp (uvm_test_top.mc.bc) # Figure 6: The bottom component is instantiated by # the",
"The bottom component is instantiated by # the middle component and is at",
"Figure 1: A uvm_test demonstrating the phase methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test",
"self.logger.info(f\"{self.get_name()} end of elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc) # Figure 6: The",
"= BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\") # ### BottomComp",
"@pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self) def final_phase(self):",
"print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\") # ## Building the testbench hierarchy #",
"build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\") #",
"is instantiated by # the middle component and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component):",
"async def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def check_phase(self):",
"# the middle component and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async def run_phase(self):",
"instantiates TestTop as uvm_test_top # The test is always named uvm_test_top @pyuvm.test() class",
"(uvm_test_top.mc.bc) # Figure 6: The bottom component is instantiated by # the middle",
"uvm_component def build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\")",
"## Building the testbench hierarchy # ### TestTop (uvm_test_top) # Figure 4: pyuvm",
"start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6",
"def check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\") #",
"MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration",
"PhaseTest(uvm_test): # uvm_test extends uvm_component def build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\")",
"is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async def run_phase(self): self.raise_objection() self.logger.info(f\"{self.get_name()} run phase\") self.drop_objection()",
"instantiated by # uvm_test_top as \"mc\" and instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self):",
"middle component and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async def run_phase(self): self.raise_objection() self.logger.info(f\"{self.get_name()}",
"def final_phase(self): print(\"9 final_phase\") # ## Building the testbench hierarchy # ### TestTop",
"The middle component is instantiated by # uvm_test_top as \"mc\" and instantiates \"bc\".",
"class MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of",
"as \"mc\" and instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self)",
"uvm_test_top as \"mc\" and instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\",",
"\"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end",
"the testbench hierarchy # ### TestTop (uvm_test_top) # Figure 4: pyuvm instantiates TestTop",
"Figure 4: pyuvm instantiates TestTop as uvm_test_top # The test is always named",
"methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends uvm_component def build_phase(self): print(\"1 build_phase\") def",
"by # uvm_test_top as \"mc\" and instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc",
"### TestTop (uvm_test_top) # Figure 4: pyuvm instantiates TestTop as uvm_test_top # The",
"final_phase(self): print(\"9 final_phase\") # ## Building the testbench hierarchy # ### TestTop (uvm_test_top)",
"The test is always named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\")",
"hierarchy # ### TestTop (uvm_test_top) # Figure 4: pyuvm instantiates TestTop as uvm_test_top",
"import * # # uvm_component # ## Running the phases # Figure 1:",
"run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\")",
"end of elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc) # Figure 6: The bottom",
"uvm_component # ## Running the phases # Figure 1: A uvm_test demonstrating the",
"and instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self):",
"<reponame>raysalemi/python4uvm_examples<filename>28_uvm_component/testbench.py import pyuvm from pyuvm import * # # uvm_component # ## Running",
"build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self):",
"@pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends uvm_component def build_phase(self): print(\"1 build_phase\") def connect_phase(self):",
"(uvm_test_top.mc) # Figure 5: The middle component is instantiated by # uvm_test_top as",
"end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc) # Figure 6:",
"final_phase\") # ## Building the testbench hierarchy # ### TestTop (uvm_test_top) # Figure",
"connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection()",
"# uvm_test extends uvm_component def build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\") def",
"print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\") # ## Building",
"class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final",
"connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def",
"print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self):",
"check_phase\") def report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\") # ## Building the",
"the middle component and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async def run_phase(self): self.raise_objection()",
"(uvm_test_top) # Figure 4: pyuvm instantiates TestTop as uvm_test_top # The test is",
"def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc) # Figure",
"uvm_test extends uvm_component def build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self):",
"print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4",
"component is instantiated by # the middle component and is at \"uvm_test_top.mc.bc\" class",
"pyuvm instantiates TestTop as uvm_test_top # The test is always named uvm_test_top @pyuvm.test()",
"def build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def",
"Running the phases # Figure 1: A uvm_test demonstrating the phase methods @pyuvm.test()",
"# Figure 5: The middle component is instantiated by # uvm_test_top as \"mc\"",
"the phases # Figure 1: A uvm_test demonstrating the phase methods @pyuvm.test() class",
"* # # uvm_component # ## Running the phases # Figure 1: A",
"report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\") # ## Building the testbench hierarchy",
"instantiated by # the middle component and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async",
"uvm_test demonstrating the phase methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends uvm_component def",
"by # the middle component and is at \"uvm_test_top.mc.bc\" class BottomComp(uvm_component): async def",
"# ### TestTop (uvm_test_top) # Figure 4: pyuvm instantiates TestTop as uvm_test_top #",
"def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7",
"elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc) # Figure 6: The bottom component is",
"named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self)",
"build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\") # ###",
"TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\")",
"# Figure 1: A uvm_test demonstrating the phase methods @pyuvm.test() class PhaseTest(uvm_test): #",
"self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp",
"start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def",
"phase methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends uvm_component def build_phase(self): print(\"1 build_phase\")",
"check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\") # ##",
"parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc) #",
"class PhaseTest(uvm_test): # uvm_test extends uvm_component def build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2",
"print(\"9 final_phase\") # ## Building the testbench hierarchy # ### TestTop (uvm_test_top) #",
"Figure 5: The middle component is instantiated by # uvm_test_top as \"mc\" and",
"def end_of_elaboration_phase(self): print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5",
"uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self) def",
"extract_phase\") def check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\")",
"pyuvm from pyuvm import * # # uvm_component # ## Running the phases",
"Figure 6: The bottom component is instantiated by # the middle component and",
"4: pyuvm instantiates TestTop as uvm_test_top # The test is always named uvm_test_top",
"def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()} end of elaboration phase\")",
"def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self):",
"Building the testbench hierarchy # ### TestTop (uvm_test_top) # Figure 4: pyuvm instantiates",
"self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\")",
"report_phase\") def final_phase(self): print(\"9 final_phase\") # ## Building the testbench hierarchy # ###",
"print(\"3 end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection()",
"extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\") def final_phase(self):",
"bottom component is instantiated by # the middle component and is at \"uvm_test_top.mc.bc\"",
"self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc) # Figure 5: The middle component is",
"# ## Running the phases # Figure 1: A uvm_test demonstrating the phase",
"import pyuvm from pyuvm import * # # uvm_component # ## Running the",
"always named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\",",
"instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc = BottomComp(name=\"bc\", parent=self) def end_of_elaboration_phase(self): self.logger.info(f\"{self.get_name()}",
"def extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\") def",
"final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc) # Figure 5: The middle component",
"of elaboration phase\") # ### BottomComp (uvm_test_top.mc.bc) # Figure 6: The bottom component",
"demonstrating the phase methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends uvm_component def build_phase(self):",
"is instantiated by # uvm_test_top as \"mc\" and instantiates \"bc\". class MiddleComp(uvm_component): def",
"# The test is always named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()}",
"def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc = MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\") #",
"### MiddleComp (uvm_test_top.mc) # Figure 5: The middle component is instantiated by #",
"print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\") def report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9",
"extends uvm_component def build_phase(self): print(\"1 build_phase\") def connect_phase(self): print(\"2 connect_phase\") def end_of_elaboration_phase(self): print(\"3",
"self.mc = MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc) #",
"from pyuvm import * # # uvm_component # ## Running the phases #",
"self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\") def",
"self) def final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc) # Figure 5: The",
"end_of_elaboration_phase\") def start_of_simulation_phase(self): print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def",
"phase\") # ### BottomComp (uvm_test_top.mc.bc) # Figure 6: The bottom component is instantiated",
"print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\") def check_phase(self): print(\"7 check_phase\") def report_phase(self):",
"### BottomComp (uvm_test_top.mc.bc) # Figure 6: The bottom component is instantiated by #",
"A uvm_test demonstrating the phase methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends uvm_component",
"# ### BottomComp (uvm_test_top.mc.bc) # Figure 6: The bottom component is instantiated by",
"the phase methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends uvm_component def build_phase(self): print(\"1",
"# ### MiddleComp (uvm_test_top.mc) # Figure 5: The middle component is instantiated by",
"## Running the phases # Figure 1: A uvm_test demonstrating the phase methods",
"TestTop as uvm_test_top # The test is always named uvm_test_top @pyuvm.test() class TestTop(uvm_test):",
"phase\") # ### MiddleComp (uvm_test_top.mc) # Figure 5: The middle component is instantiated",
"1: A uvm_test demonstrating the phase methods @pyuvm.test() class PhaseTest(uvm_test): # uvm_test extends",
"component is instantiated by # uvm_test_top as \"mc\" and instantiates \"bc\". class MiddleComp(uvm_component):",
"pyuvm import * # # uvm_component # ## Running the phases # Figure",
"is always named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc =",
"# uvm_test_top as \"mc\" and instantiates \"bc\". class MiddleComp(uvm_component): def build_phase(self): self.bc =",
"# Figure 6: The bottom component is instantiated by # the middle component",
"def final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc) # Figure 5: The middle",
"= MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc) # Figure",
"# uvm_component # ## Running the phases # Figure 1: A uvm_test demonstrating",
"6: The bottom component is instantiated by # the middle component and is",
"phases # Figure 1: A uvm_test demonstrating the phase methods @pyuvm.test() class PhaseTest(uvm_test):",
"print(\"4 start_of_simulation_phase\") async def run_phase(self): self.raise_objection() print(\"5 run_phase\") self.drop_objection() def extract_phase(self): print(\"6 extract_phase\")",
"testbench hierarchy # ### TestTop (uvm_test_top) # Figure 4: pyuvm instantiates TestTop as",
"def report_phase(self): print(\"8 report_phase\") def final_phase(self): print(\"9 final_phase\") # ## Building the testbench",
"test is always named uvm_test_top @pyuvm.test() class TestTop(uvm_test): def build_phase(self): self.logger.info(f\"{self.get_name()} build_phase\") self.mc",
"MiddleComp(\"mc\", self) def final_phase(self): self.logger.info(\"final phase\") # ### MiddleComp (uvm_test_top.mc) # Figure 5:",
"5: The middle component is instantiated by # uvm_test_top as \"mc\" and instantiates",
"# Figure 4: pyuvm instantiates TestTop as uvm_test_top # The test is always"
] |
[
"= [ path( \"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls), ), path( \"bank/transaction/\", views.ForeignTransactionView.as_view(),",
"] urlpatterns = [ path( \"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls), ), path(",
"django.urls.conf import path, include from rest_framework import routers from . import views router",
"= [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ]",
"= routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\",",
"[ path( \"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls), ), path( \"bank/transaction/\", views.ForeignTransactionView.as_view(), name=\"bank-transaction\",",
"import views router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [ path(",
"routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ),",
"name=\"user-transactions-detail\", ), ] urlpatterns = [ path( \"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls),",
"views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns = [ path( \"user/\", include(user_transaction_urls), ), path( \"\",",
"include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(",
"routers from . import views router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls",
"name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns = [ path( \"user/\",",
"path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns =",
"router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(),",
"import path, include from rest_framework import routers from . import views router =",
"views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns = [ path(",
"router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path(",
". import views router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [",
") user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\",",
"path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns = [ path( \"user/\", include(user_transaction_urls), ),",
"views router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [ path( \"transactions/\",",
"path, include from rest_framework import routers from . import views router = routers.DefaultRouter()",
"path( \"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls), ), path( \"bank/transaction/\", views.ForeignTransactionView.as_view(), name=\"bank-transaction\", ),",
"user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ),",
"rest_framework import routers from . import views router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet,",
"r\"transactions\", views.TransactionViewSet, ) user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\",",
"\"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns = [ path( \"user/\", include(user_transaction_urls), ), path(",
"urlpatterns = [ path( \"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls), ), path( \"bank/transaction/\",",
"\"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls), ), path( \"bank/transaction/\", views.ForeignTransactionView.as_view(), name=\"bank-transaction\", ), ]",
"import routers from . import views router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, )",
"from rest_framework import routers from . import views router = routers.DefaultRouter() router.register( r\"transactions\",",
"), ] urlpatterns = [ path( \"user/\", include(user_transaction_urls), ), path( \"\", include(router.urls), ),",
"[ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns",
"), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns = [ path( \"user/\", include(user_transaction_urls),",
"\"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(), name=\"user-transactions-detail\", ), ] urlpatterns = [",
"views.TransactionViewSet, ) user_transaction_urls = [ path( \"transactions/\", views.UserTransactionListCreateView.as_view(), name=\"user-transactions\", ), path( \"transactions/<int:id>/\", views.UserTransactionView.as_view(),",
"from . import views router = routers.DefaultRouter() router.register( r\"transactions\", views.TransactionViewSet, ) user_transaction_urls =",
"from django.urls.conf import path, include from rest_framework import routers from . import views"
] |
[
"https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed",
"disk space every {period} s; \" f\"will pause when free space on {path}",
"f\"Starting: controlling process {process_id}; \" f\"checking disk space every {period} s; \" f\"will",
"int) -> bool: \"\"\" Uses the Unix ``ps`` program to see if a",
"for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. \"\"\" parser =",
"process is running. \"\"\" pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\",",
"must be less than maximum\" log.info( f\"Starting: controlling process {process_id}; \" f\"checking disk",
"f\"will pause when free space on {path} \" f\"is less than {sizeof_fmt(minimum)} and",
"f\"resume when free space is at least {sizeof_fmt(maximum)}; \" f\"pause command will be",
"f\"checking disk space every {period} s; \" f\"will pause when free space on",
"free space on {path} \" f\"is less than {sizeof_fmt(minimum)} and \" f\"resume when",
"ArgumentParser( description=\"Pauses and resumes a process by disk space; LINUX ONLY.\" ) parser.add_argument(",
"seconds (where this is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args",
"will be {pause_args}; \" f\"resume command will be {resume_args}.\" ) log.debug(\"Presuming that the",
"cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log =",
"will be {resume_args}.\" ) log.debug(\"Presuming that the process is RUNNING to begin with.\")",
"and paused: log.info(\"Disk space up to {}: resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args)",
"free disk space below this value (in bytes \" \"or as e.g. '50G')\"",
"while True: if not is_running(process_id): log.info(\"Process {} is no longer running\", process_id) sys.exit(0)",
"= False while True: if not is_running(process_id): log.info(\"Process {} is no longer running\",",
"to begin with.\") paused = False while True: if not is_running(process_id): log.info(\"Process {}",
"args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)] assert minimum",
") from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) ->",
"program to see if a process is running. \"\"\" pstr = str(process_id) encoding",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"strline = line.decode(encoding) if pstr in strline: return True return False def main()",
"code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is part of cardinal_pythonlib. Licensed",
"\" \"or as e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every n",
"parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above)",
"(e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process when free disk space",
"the process is RUNNING to begin with.\") paused = False while True: if",
"process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for {} seconds...\", period)",
"every n seconds (where this is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\"",
"bool: \"\"\" Uses the Unix ``ps`` program to see if a process is",
"shutil.disk_usage(path).free log.debug(\"Disk space on {} is {}\", path, sizeof_fmt(space)) if space < minimum",
"BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool: \"\"\" Uses the Unix ``ps`` program to",
"[\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)] assert minimum < maximum, \"Minimum",
"NoReturn: \"\"\" Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for",
"import NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes,",
"the License for the specific language governing permissions and limitations under the License.",
"import sleep from typing import NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, )",
"\"--check_every\", type=int, required=True, help=\"Check every n seconds (where this is n)\" ) parser.add_argument(",
"see if a process is running. \"\"\" pstr = str(process_id) encoding = sys.getdefaultencoding()",
"str(process_id)] assert minimum < maximum, \"Minimum must be less than maximum\" log.info( f\"Starting:",
"\" f\"checking disk space every {period} s; \" f\"will pause when free space",
"when free disk space above this value (in bytes \" \"or as e.g.",
"help=\"Check every n seconds (where this is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose",
"process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True elif space >= maximum and",
"{} is no longer running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space on",
"Unless required by applicable law or agreed to in writing, software distributed under",
"from typing import NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter",
"License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,",
"\"--resume_when_free_above\", type=str, required=True, help=\"Resume process when free disk space above this value (in",
"if pstr in strline: return True return False def main() -> NoReturn: \"\"\"",
"{process_id}; \" f\"checking disk space every {period} s; \" f\"will pause when free",
"f\"pause command will be {pause_args}; \" f\"resume command will be {resume_args}.\" ) log.debug(\"Presuming",
"and not paused: log.info(\"Disk space down to {}: pausing process {}\", sizeof_fmt(space), process_id)",
"log.info( f\"Starting: controlling process {process_id}; \" f\"checking disk space every {period} s; \"",
"paused = False log.debug(\"Sleeping for {} seconds...\", period) sleep(period) if __name__ == '__main__':",
"above this value (in bytes \" \"or as e.g. '70G')\" ) parser.add_argument( \"--check_every\",",
"running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space on {} is {}\", path,",
"\"\"\" from argparse import ArgumentParser import logging import shutil import subprocess import sys",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"required=True, help=\"Pause process when free disk space below this value (in bytes \"",
"License, Version 2.0 (the \"License\"); you may not use this file except in",
"tool. Use the ``--help`` option for help. \"\"\" parser = ArgumentParser( description=\"Pauses and",
"sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for {} seconds...\", period) sleep(period) if",
"import subprocess import sys from time import sleep from typing import NoReturn from",
"\"--pause_when_free_below\", type=str, required=True, help=\"Pause process when free disk space below this value (in",
"process when free disk space above this value (in bytes \" \"or as",
"space on {path} \" f\"is less than {sizeof_fmt(minimum)} and \" f\"resume when free",
"-> NoReturn: \"\"\" Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option",
"= ArgumentParser( description=\"Pauses and resumes a process by disk space; LINUX ONLY.\" )",
"License for the specific language governing permissions and limitations under the License. ===============================================================================",
"line.decode(encoding) if pstr in strline: return True return False def main() -> NoReturn:",
"'/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process when free disk space below",
"n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG",
"space down to {}: pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True",
"(in bytes \" \"or as e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check",
"resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for {} seconds...\",",
"copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is part of cardinal_pythonlib. Licensed under",
"human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool: \"\"\" Uses the",
"help=\"Pause process when free disk space below this value (in bytes \" \"or",
"when free space is at least {sizeof_fmt(maximum)}; \" f\"pause command will be {pause_args};",
"bytes \" \"or as e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every",
"software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"by applicable law or agreed to in writing, software distributed under the License",
"space above this value (in bytes \" \"or as e.g. '70G')\" ) parser.add_argument(",
"space on {} is {}\", path, sizeof_fmt(space)) if space < minimum and not",
"under the License. =============================================================================== **Pauses and resumes a process by disk space; LINUX",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License",
"s; \" f\"will pause when free space on {path} \" f\"is less than",
"up to {}: resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping",
"\" f\"pause command will be {pause_args}; \" f\"resume command will be {resume_args}.\" )",
"is_running(process_id: int) -> bool: \"\"\" Uses the Unix ``ps`` program to see if",
"e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every n seconds (where this",
"n seconds (where this is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" )",
"for the specific language governing permissions and limitations under the License. =============================================================================== **Pauses",
"cardinal_pythonlib. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not",
"copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"this is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args = parser.parse_args()",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"shutil import subprocess import sys from time import sleep from typing import NoReturn",
"language governing permissions and limitations under the License. =============================================================================== **Pauses and resumes a",
"command will be {resume_args}.\" ) log.debug(\"Presuming that the process is RUNNING to begin",
"type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path to check free space for",
"= BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool: \"\"\" Uses the Unix ``ps`` program",
"in compliance with the License. You may obtain a copy of the License",
"command will be {pause_args}; \" f\"resume command will be {resume_args}.\" ) log.debug(\"Presuming that",
"KIND, either express or implied. See the License for the specific language governing",
"paused: log.info(\"Disk space up to {}: resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused",
"be {resume_args}.\" ) log.debug(\"Presuming that the process is RUNNING to begin with.\") paused",
"a process by disk space; LINUX ONLY.** \"\"\" from argparse import ArgumentParser import",
"in writing, software distributed under the License is distributed on an \"AS IS\"",
"in strline: return True return False def main() -> NoReturn: \"\"\" Command-line handler",
"writing, software distributed under the License is distributed on an \"AS IS\" BASIS,",
"log.debug(\"Presuming that the process is RUNNING to begin with.\") paused = False while",
"BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id:",
"or agreed to in writing, software distributed under the License is distributed on",
"typing import NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import",
"permissions and limitations under the License. =============================================================================== **Pauses and resumes a process by",
"{}: resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for {}",
">= maximum and paused: log.info(\"Disk space up to {}: resuming process {}\", sizeof_fmt(space),",
"**Pauses and resumes a process by disk space; LINUX ONLY.** \"\"\" from argparse",
"maximum\" log.info( f\"Starting: controlling process {process_id}; \" f\"checking disk space every {period} s;",
"file is part of cardinal_pythonlib. Licensed under the Apache License, Version 2.0 (the",
"the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"down to {}: pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True elif",
"parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose",
"output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) minimum =",
"False while True: if not is_running(process_id): log.info(\"Process {} is no longer running\", process_id)",
"part of cardinal_pythonlib. Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"\" f\"is less than {sizeof_fmt(minimum)} and \" f\"resume when free space is at",
"``--help`` option for help. \"\"\" parser = ArgumentParser( description=\"Pauses and resumes a process",
"OR CONDITIONS OF ANY KIND, either express or implied. See the License for",
"OF ANY KIND, either express or implied. See the License for the specific",
"be less than maximum\" log.info( f\"Starting: controlling process {process_id}; \" f\"checking disk space",
"log.debug(\"Disk space on {} is {}\", path, sizeof_fmt(space)) if space < minimum and",
"\"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else",
"space every {period} s; \" f\"will pause when free space on {path} \"",
"sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space on {} is {}\", path, sizeof_fmt(space)) if",
"help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path to check free space for (e.g.",
"\"\"\" Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help.",
"may not use this file except in compliance with the License. You may",
"level=logging.DEBUG if args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path =",
"longer running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space on {} is {}\",",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"free space for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process when",
"help=\"Verbose output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) minimum",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool: \"\"\" Uses the Unix",
"process_id) subprocess.check_call(pause_args) paused = True elif space >= maximum and paused: log.info(\"Disk space",
"than maximum\" log.info( f\"Starting: controlling process {process_id}; \" f\"checking disk space every {period}",
"from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool:",
"begin with.\") paused = False while True: if not is_running(process_id): log.info(\"Process {} is",
"path, sizeof_fmt(space)) if space < minimum and not paused: log.info(\"Disk space down to",
"less than {sizeof_fmt(minimum)} and \" f\"resume when free space is at least {sizeof_fmt(maximum)};",
"less than maximum\" log.info( f\"Starting: controlling process {process_id}; \" f\"checking disk space every",
"sizeof_fmt(space)) if space < minimum and not paused: log.info(\"Disk space down to {}:",
"return True return False def main() -> NoReturn: \"\"\" Command-line handler for the",
"# cardinal_pythonlib/openxml/pause_process_by_disk_space.py \"\"\" =============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file",
"line in s.stdout: strline = line.decode(encoding) if pstr in strline: return True return",
"be {pause_args}; \" f\"resume command will be {resume_args}.\" ) log.debug(\"Presuming that the process",
"pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)] assert minimum <",
"for line in s.stdout: strline = line.decode(encoding) if pstr in strline: return True",
"See the License for the specific language governing permissions and limitations under the",
"space for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process when free",
"{}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for {} seconds...\", period) sleep(period)",
"path = args.path process_id = args.process_id period = args.check_every pause_args = [\"kill\", \"-STOP\",",
"to {}: pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True elif space",
"this file except in compliance with the License. You may obtain a copy",
"minimum and not paused: log.info(\"Disk space down to {}: pausing process {}\", sizeof_fmt(space),",
"action=\"store_true\", help=\"Verbose output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO)",
"subprocess.check_call(pause_args) paused = True elif space >= maximum and paused: log.info(\"Disk space up",
"logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path = args.path process_id = args.process_id",
"to {}: resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for",
"of cardinal_pythonlib. Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"\"License\"); you may not use this file except in compliance with the License.",
"is part of cardinal_pythonlib. Licensed under the Apache License, Version 2.0 (the \"License\");",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"import shutil import subprocess import sys from time import sleep from typing import",
"``ps`` program to see if a process is running. \"\"\" pstr = str(process_id)",
"you may not use this file except in compliance with the License. You",
"agreed to in writing, software distributed under the License is distributed on an",
") parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path to check",
"is no longer running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space on {}",
"pstr in strline: return True return False def main() -> NoReturn: \"\"\" Command-line",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"the specific language governing permissions and limitations under the License. =============================================================================== **Pauses and",
"( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def",
"if args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path = args.path",
"resumes a process by disk space; LINUX ONLY.** \"\"\" from argparse import ArgumentParser",
"f\"resume command will be {resume_args}.\" ) log.debug(\"Presuming that the process is RUNNING to",
"with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0",
"the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. \"\"\" parser = ArgumentParser(",
"implied. See the License for the specific language governing permissions and limitations under",
"sleep from typing import NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from",
"def is_running(process_id: int) -> bool: \"\"\" Uses the Unix ``ps`` program to see",
"a process by disk space; LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process ID.\"",
"when free disk space below this value (in bytes \" \"or as e.g.",
"parser.add_argument( \"--path\", required=True, help=\"Path to check free space for (e.g. '/')\" ) parser.add_argument(",
"\"Minimum must be less than maximum\" log.info( f\"Starting: controlling process {process_id}; \" f\"checking",
"time import sleep from typing import NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger,",
"least {sizeof_fmt(maximum)}; \" f\"pause command will be {pause_args}; \" f\"resume command will be",
"if space < minimum and not paused: log.info(\"Disk space down to {}: pausing",
"log.info(\"Disk space down to {}: pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused =",
"{sizeof_fmt(minimum)} and \" f\"resume when free space is at least {sizeof_fmt(maximum)}; \" f\"pause",
"at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software",
"subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for {} seconds...\", period) sleep(period) if __name__ ==",
"True elif space >= maximum and paused: log.info(\"Disk space up to {}: resuming",
"subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encoding) if pstr",
"use this file except in compliance with the License. You may obtain a",
") parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if",
"License. =============================================================================== **Pauses and resumes a process by disk space; LINUX ONLY.** \"\"\"",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use",
"log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool: \"\"\" Uses the Unix ``ps``",
"process is RUNNING to begin with.\") paused = False while True: if not",
"pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encoding) if pstr in strline:",
"'50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process when free disk space above",
"\"\"\" pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE)",
"bytes \" \"or as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process",
"no longer running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space on {} is",
"def main() -> NoReturn: \"\"\" Command-line handler for the ``pause_process_by_disk_space`` tool. Use the",
"not is_running(process_id): log.info(\"Process {} is no longer running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free",
"(in bytes \" \"or as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume",
"the Unix ``ps`` program to see if a process is running. \"\"\" pstr",
"=============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is part of",
"< maximum, \"Minimum must be less than maximum\" log.info( f\"Starting: controlling process {process_id};",
"governing permissions and limitations under the License. =============================================================================== **Pauses and resumes a process",
"required=True, help=\"Check every n seconds (where this is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\",",
"required by applicable law or agreed to in writing, software distributed under the",
"below this value (in bytes \" \"or as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\",",
"{sizeof_fmt(maximum)}; \" f\"pause command will be {pause_args}; \" f\"resume command will be {resume_args}.\"",
"(where this is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args =",
"parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path to check free",
"disk space below this value (in bytes \" \"or as e.g. '50G')\" )",
"ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path to",
") parser.add_argument( \"--path\", required=True, help=\"Path to check free space for (e.g. '/')\" )",
"running. \"\"\" pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr],",
"parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process when free disk space above this value",
"args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum",
"free disk space above this value (in bytes \" \"or as e.g. '70G')\"",
"[\"kill\", \"-CONT\", str(process_id)] assert minimum < maximum, \"Minimum must be less than maximum\"",
"{}: pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True elif space >=",
"paused = True elif space >= maximum and paused: log.info(\"Disk space up to",
"and resumes a process by disk space; LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int,",
"main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path",
"as e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every n seconds (where",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"is {}\", path, sizeof_fmt(space)) if space < minimum and not paused: log.info(\"Disk space",
"paused = False while True: if not is_running(process_id): log.info(\"Process {} is no longer",
"not use this file except in compliance with the License. You may obtain",
"obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"help. \"\"\" parser = ArgumentParser( description=\"Pauses and resumes a process by disk space;",
"to see if a process is running. \"\"\" pstr = str(process_id) encoding =",
"cardinal_pythonlib/openxml/pause_process_by_disk_space.py \"\"\" =============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is",
") parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every n seconds (where this is n)\"",
"import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool: \"\"\" Uses",
"is at least {sizeof_fmt(maximum)}; \" f\"pause command will be {pause_args}; \" f\"resume command",
"is_running(process_id): log.info(\"Process {} is no longer running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk",
"import logging import shutil import subprocess import sys from time import sleep from",
"stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encoding) if pstr in strline: return",
"assert minimum < maximum, \"Minimum must be less than maximum\" log.info( f\"Starting: controlling",
"help=\"Resume process when free disk space above this value (in bytes \" \"or",
"else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path = args.path process_id =",
"and resumes a process by disk space; LINUX ONLY.** \"\"\" from argparse import",
"space = shutil.disk_usage(path).free log.debug(\"Disk space on {} is {}\", path, sizeof_fmt(space)) if space",
"this value (in bytes \" \"or as e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int,",
"a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"main() -> NoReturn: \"\"\" Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help``",
"on {path} \" f\"is less than {sizeof_fmt(minimum)} and \" f\"resume when free space",
"\"or as e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every n seconds",
"ANY KIND, either express or implied. See the License for the specific language",
"=============================================================================== **Pauses and resumes a process by disk space; LINUX ONLY.** \"\"\" from",
"\" f\"will pause when free space on {path} \" f\"is less than {sizeof_fmt(minimum)}",
"parser = ArgumentParser( description=\"Pauses and resumes a process by disk space; LINUX ONLY.\"",
"file except in compliance with the License. You may obtain a copy of",
"= human2bytes(args.resume_when_free_above) path = args.path process_id = args.process_id period = args.check_every pause_args =",
"to check free space for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause",
"space up to {}: resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused = False",
"strline: return True return False def main() -> NoReturn: \"\"\" Command-line handler for",
"\"--path\", required=True, help=\"Path to check free space for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\",",
"2.0 (the \"License\"); you may not use this file except in compliance with",
"log.info(\"Disk space up to {}: resuming process {}\", sizeof_fmt(space), process_id) subprocess.check_call(resume_args) paused =",
"specific language governing permissions and limitations under the License. =============================================================================== **Pauses and resumes",
"Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. \"\"\"",
"period = args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)]",
"= line.decode(encoding) if pstr in strline: return True return False def main() ->",
"a process is running. \"\"\" pstr = str(process_id) encoding = sys.getdefaultencoding() s =",
"encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line in s.stdout:",
"= str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line",
"(the \"License\"); you may not use this file except in compliance with the",
"(C) 2009-2021 <NAME> (<EMAIL>). This file is part of cardinal_pythonlib. Licensed under the",
"this value (in bytes \" \"or as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str,",
"= True elif space >= maximum and paused: log.info(\"Disk space up to {}:",
"ArgumentParser import logging import shutil import subprocess import sys from time import sleep",
"log.info(\"Process {} is no longer running\", process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space",
"``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. \"\"\" parser = ArgumentParser( description=\"Pauses",
"process by disk space; LINUX ONLY.** \"\"\" from argparse import ArgumentParser import logging",
"\"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path to check free space",
") parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process when free disk space above this",
"and \" f\"resume when free space is at least {sizeof_fmt(maximum)}; \" f\"pause command",
"not paused: log.info(\"Disk space down to {}: pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args)",
"This file is part of cardinal_pythonlib. Licensed under the Apache License, Version 2.0",
"space; LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True,",
"\"\"\" =============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is part",
"ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path to check free space for (e.g. '/')\"",
"that the process is RUNNING to begin with.\") paused = False while True:",
"process_id = args.process_id period = args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args =",
"\"-p\", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encoding) if pstr in",
"pause when free space on {path} \" f\"is less than {sizeof_fmt(minimum)} and \"",
"value (in bytes \" \"or as e.g. '70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True,",
"2009-2021 <NAME> (<EMAIL>). This file is part of cardinal_pythonlib. Licensed under the Apache",
"'70G')\" ) parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every n seconds (where this is",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"description=\"Pauses and resumes a process by disk space; LINUX ONLY.\" ) parser.add_argument( \"process_id\",",
"parser.add_argument( \"--check_every\", type=int, required=True, help=\"Check every n seconds (where this is n)\" )",
"str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)] assert minimum < maximum, \"Minimum must be",
"import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__))",
"help=\"Path to check free space for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True,",
"(<EMAIL>). This file is part of cardinal_pythonlib. Licensed under the Apache License, Version",
"NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt",
"You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"subprocess import sys from time import sleep from typing import NoReturn from cardinal_pythonlib.logs",
"from cardinal_pythonlib.logs import ( BraceStyleAdapter, main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log",
"by disk space; LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument(",
"law or agreed to in writing, software distributed under the License is distributed",
"on {} is {}\", path, sizeof_fmt(space)) if space < minimum and not paused:",
"value (in bytes \" \"or as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True,",
"Version 2.0 (the \"License\"); you may not use this file except in compliance",
"the Apache License, Version 2.0 (the \"License\"); you may not use this file",
"from argparse import ArgumentParser import logging import shutil import subprocess import sys from",
"= shutil.disk_usage(path).free log.debug(\"Disk space on {} is {}\", path, sizeof_fmt(space)) if space <",
"for help. \"\"\" parser = ArgumentParser( description=\"Pauses and resumes a process by disk",
"as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process when free disk",
"args.path process_id = args.process_id period = args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args",
"under the Apache License, Version 2.0 (the \"License\"); you may not use this",
"= human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path = args.path process_id = args.process_id period =",
"free space is at least {sizeof_fmt(maximum)}; \" f\"pause command will be {pause_args}; \"",
"either express or implied. See the License for the specific language governing permissions",
"every {period} s; \" f\"will pause when free space on {path} \" f\"is",
"= sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline",
"\"\"\" parser = ArgumentParser( description=\"Pauses and resumes a process by disk space; LINUX",
"s.stdout: strline = line.decode(encoding) if pstr in strline: return True return False def",
"{} is {}\", path, sizeof_fmt(space)) if space < minimum and not paused: log.info(\"Disk",
"pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for",
"{}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True elif space >= maximum and paused:",
"= args.path process_id = args.process_id period = args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)]",
"check free space for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process",
"Apache License, Version 2.0 (the \"License\"); you may not use this file except",
"or implied. See the License for the specific language governing permissions and limitations",
"disk space; LINUX ONLY.** \"\"\" from argparse import ArgumentParser import logging import shutil",
"True return False def main() -> NoReturn: \"\"\" Command-line handler for the ``pause_process_by_disk_space``",
"logging import shutil import subprocess import sys from time import sleep from typing",
") args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below)",
"type=str, required=True, help=\"Pause process when free disk space below this value (in bytes",
"= [\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)] assert minimum < maximum,",
"required=True, help=\"Path to check free space for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str,",
"= args.process_id period = args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\",",
"process by disk space; LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" )",
"args.process_id period = args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\",",
"args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path = args.path process_id",
"than {sizeof_fmt(minimum)} and \" f\"resume when free space is at least {sizeof_fmt(maximum)}; \"",
"-> bool: \"\"\" Uses the Unix ``ps`` program to see if a process",
"is running. \"\"\" pstr = str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\",",
"the License. =============================================================================== **Pauses and resumes a process by disk space; LINUX ONLY.**",
"CONDITIONS OF ANY KIND, either express or implied. See the License for the",
"handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help. \"\"\" parser",
"maximum, \"Minimum must be less than maximum\" log.info( f\"Starting: controlling process {process_id}; \"",
"True: if not is_running(process_id): log.info(\"Process {} is no longer running\", process_id) sys.exit(0) space",
"= args.check_every pause_args = [\"kill\", \"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)] assert",
"to in writing, software distributed under the License is distributed on an \"AS",
"for (e.g. '/')\" ) parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process when free disk",
"LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\", required=True, help=\"Path",
"by disk space; LINUX ONLY.** \"\"\" from argparse import ArgumentParser import logging import",
"sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True elif space >= maximum and paused: log.info(\"Disk",
"maximum and paused: log.info(\"Disk space up to {}: resuming process {}\", sizeof_fmt(space), process_id)",
"except in compliance with the License. You may obtain a copy of the",
"space >= maximum and paused: log.info(\"Disk space up to {}: resuming process {}\",",
"disk space above this value (in bytes \" \"or as e.g. '70G')\" )",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
") parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process when free disk space below this",
"option for help. \"\"\" parser = ArgumentParser( description=\"Pauses and resumes a process by",
"\"or as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process when free",
"minimum < maximum, \"Minimum must be less than maximum\" log.info( f\"Starting: controlling process",
"argparse import ArgumentParser import logging import shutil import subprocess import sys from time",
"of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"= [\"kill\", \"-CONT\", str(process_id)] assert minimum < maximum, \"Minimum must be less than",
"False def main() -> NoReturn: \"\"\" Command-line handler for the ``pause_process_by_disk_space`` tool. Use",
"is n)\" ) parser.add_argument( \"--verbose\", action=\"store_true\", help=\"Verbose output\" ) args = parser.parse_args() main_only_quicksetup_rootlogger(",
"\"-CONT\", str(process_id)] assert minimum < maximum, \"Minimum must be less than maximum\" log.info(",
"Use the ``--help`` option for help. \"\"\" parser = ArgumentParser( description=\"Pauses and resumes",
"Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is part of cardinal_pythonlib.",
"= False log.debug(\"Sleeping for {} seconds...\", period) sleep(period) if __name__ == '__main__': main()",
"space is at least {sizeof_fmt(maximum)}; \" f\"pause command will be {pause_args}; \" f\"resume",
"required=True, help=\"Resume process when free disk space above this value (in bytes \"",
"human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path = args.path process_id = args.process_id period = args.check_every",
"from time import sleep from typing import NoReturn from cardinal_pythonlib.logs import ( BraceStyleAdapter,",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"{period} s; \" f\"will pause when free space on {path} \" f\"is less",
"with.\") paused = False while True: if not is_running(process_id): log.info(\"Process {} is no",
"resume_args = [\"kill\", \"-CONT\", str(process_id)] assert minimum < maximum, \"Minimum must be less",
"\"\"\" Uses the Unix ``ps`` program to see if a process is running.",
"ONLY.** \"\"\" from argparse import ArgumentParser import logging import shutil import subprocess import",
"is RUNNING to begin with.\") paused = False while True: if not is_running(process_id):",
"LINUX ONLY.** \"\"\" from argparse import ArgumentParser import logging import shutil import subprocess",
"space < minimum and not paused: log.info(\"Disk space down to {}: pausing process",
"and limitations under the License. =============================================================================== **Pauses and resumes a process by disk",
"e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process when free disk space",
"\" f\"resume when free space is at least {sizeof_fmt(maximum)}; \" f\"pause command will",
"compliance with the License. You may obtain a copy of the License at",
"limitations under the License. =============================================================================== **Pauses and resumes a process by disk space;",
"human2bytes(args.resume_when_free_above) path = args.path process_id = args.process_id period = args.check_every pause_args = [\"kill\",",
"= subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encoding) if",
"Unix ``ps`` program to see if a process is running. \"\"\" pstr =",
"express or implied. See the License for the specific language governing permissions and",
"type=int, required=True, help=\"Check every n seconds (where this is n)\" ) parser.add_argument( \"--verbose\",",
"elif space >= maximum and paused: log.info(\"Disk space up to {}: resuming process",
"License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required",
"paused: log.info(\"Disk space down to {}: pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused",
"f\"is less than {sizeof_fmt(minimum)} and \" f\"resume when free space is at least",
"when free space on {path} \" f\"is less than {sizeof_fmt(minimum)} and \" f\"resume",
"controlling process {process_id}; \" f\"checking disk space every {period} s; \" f\"will pause",
"\" \"or as e.g. '50G')\" ) parser.add_argument( \"--resume_when_free_above\", type=str, required=True, help=\"Resume process when",
"space below this value (in bytes \" \"or as e.g. '50G')\" ) parser.add_argument(",
"= parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) minimum = human2bytes(args.pause_when_free_below) maximum =",
"process_id) subprocess.check_call(resume_args) paused = False log.debug(\"Sleeping for {} seconds...\", period) sleep(period) if __name__",
"< minimum and not paused: log.info(\"Disk space down to {}: pausing process {}\",",
"{}\", path, sizeof_fmt(space)) if space < minimum and not paused: log.info(\"Disk space down",
"str(process_id) encoding = sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line in",
"main_only_quicksetup_rootlogger, ) from cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int)",
"applicable law or agreed to in writing, software distributed under the License is",
"the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless",
"sys from time import sleep from typing import NoReturn from cardinal_pythonlib.logs import (",
"process {process_id}; \" f\"checking disk space every {period} s; \" f\"will pause when",
"in s.stdout: strline = line.decode(encoding) if pstr in strline: return True return False",
"if a process is running. \"\"\" pstr = str(process_id) encoding = sys.getdefaultencoding() s",
"resumes a process by disk space; LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process",
"{pause_args}; \" f\"resume command will be {resume_args}.\" ) log.debug(\"Presuming that the process is",
"return False def main() -> NoReturn: \"\"\" Command-line handler for the ``pause_process_by_disk_space`` tool.",
"python3 # cardinal_pythonlib/openxml/pause_process_by_disk_space.py \"\"\" =============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This",
"{resume_args}.\" ) log.debug(\"Presuming that the process is RUNNING to begin with.\") paused =",
"at least {sizeof_fmt(maximum)}; \" f\"pause command will be {pause_args}; \" f\"resume command will",
"pausing process {}\", sizeof_fmt(space), process_id) subprocess.check_call(pause_args) paused = True elif space >= maximum",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"space; LINUX ONLY.** \"\"\" from argparse import ArgumentParser import logging import shutil import",
"maximum = human2bytes(args.resume_when_free_above) path = args.path process_id = args.process_id period = args.check_every pause_args",
"#!/usr/bin/env python3 # cardinal_pythonlib/openxml/pause_process_by_disk_space.py \"\"\" =============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>).",
"minimum = human2bytes(args.pause_when_free_below) maximum = human2bytes(args.resume_when_free_above) path = args.path process_id = args.process_id period",
"\" f\"resume command will be {resume_args}.\" ) log.debug(\"Presuming that the process is RUNNING",
"RUNNING to begin with.\") paused = False while True: if not is_running(process_id): log.info(\"Process",
"<NAME> (<EMAIL>). This file is part of cardinal_pythonlib. Licensed under the Apache License,",
"import sys from time import sleep from typing import NoReturn from cardinal_pythonlib.logs import",
"process when free disk space below this value (in bytes \" \"or as",
"\"-STOP\", str(process_id)] resume_args = [\"kill\", \"-CONT\", str(process_id)] assert minimum < maximum, \"Minimum must",
"parser.add_argument( \"--pause_when_free_below\", type=str, required=True, help=\"Pause process when free disk space below this value",
"import ArgumentParser import logging import shutil import subprocess import sys from time import",
"type=str, required=True, help=\"Resume process when free disk space above this value (in bytes",
"sys.getdefaultencoding() s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline =",
"disk space; LINUX ONLY.\" ) parser.add_argument( \"process_id\", type=int, help=\"Process ID.\" ) parser.add_argument( \"--path\",",
") log.debug(\"Presuming that the process is RUNNING to begin with.\") paused = False",
"{path} \" f\"is less than {sizeof_fmt(minimum)} and \" f\"resume when free space is",
"cardinal_pythonlib.sizeformatter import human2bytes, sizeof_fmt log = BraceStyleAdapter(logging.getLogger(__name__)) def is_running(process_id: int) -> bool: \"\"\"",
"s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE) for line in s.stdout: strline = line.decode(encoding)",
"the ``--help`` option for help. \"\"\" parser = ArgumentParser( description=\"Pauses and resumes a",
"if not is_running(process_id): log.info(\"Process {} is no longer running\", process_id) sys.exit(0) space =",
"process_id) sys.exit(0) space = shutil.disk_usage(path).free log.debug(\"Disk space on {} is {}\", path, sizeof_fmt(space))",
"Uses the Unix ``ps`` program to see if a process is running. \"\"\""
] |
[
"#print(curso.lower().strip()) #converte a string para letras minusculas #print(curso.upper()) #converte a string para letras",
"espaços da string #print(curso.lower().strip()) #converte a string para letras minusculas #print(curso.upper()) #converte a",
"string #print(curso.lower().strip()) #converte a string para letras minusculas #print(curso.upper()) #converte a string para",
"string para letras minusculas #print(curso.upper()) #converte a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca",
"curso=\"Curso de Python\" #print(curso[9:15]) #print(curso.strip()) #remove os espaços da string #print(curso.lower().strip()) #converte a",
"<filename>aula06/Strings_P1.py curso=\"Curso de Python\" #print(curso[9:15]) #print(curso.strip()) #remove os espaços da string #print(curso.lower().strip()) #converte",
"#converte a string para letras minusculas #print(curso.upper()) #converte a string para letras maiusculas",
"a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\" \") #remove",
"de Python\" #print(curso[9:15]) #print(curso.strip()) #remove os espaços da string #print(curso.lower().strip()) #converte a string",
"Python\" #print(curso[9:15]) #print(curso.strip()) #remove os espaços da string #print(curso.lower().strip()) #converte a string para",
"da string #print(curso.lower().strip()) #converte a string para letras minusculas #print(curso.upper()) #converte a string",
"a=curso.split(\" \") #remove tudo que estiver entre \"\" e divide o restante em",
"#remove tudo que estiver entre \"\" e divide o restante em uma array",
"que estiver entre \"\" e divide o restante em uma array print(a[0]) print(\"Tamanho:",
"#print(curso.strip()) #remove os espaços da string #print(curso.lower().strip()) #converte a string para letras minusculas",
"#remove os espaços da string #print(curso.lower().strip()) #converte a string para letras minusculas #print(curso.upper())",
"letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\" \") #remove tudo que estiver",
"#converte a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\" \")",
"string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\" \") #remove tudo",
"entre \"\" e divide o restante em uma array print(a[0]) print(\"Tamanho: \" +",
"\") #remove tudo que estiver entre \"\" e divide o restante em uma",
"estiver entre \"\" e divide o restante em uma array print(a[0]) print(\"Tamanho: \"",
"minusculas #print(curso.upper()) #converte a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array",
"#print(curso[9:15]) #print(curso.strip()) #remove os espaços da string #print(curso.lower().strip()) #converte a string para letras",
"da array a=curso.split(\" \") #remove tudo que estiver entre \"\" e divide o",
"objetos da array a=curso.split(\" \") #remove tudo que estiver entre \"\" e divide",
"\"\" e divide o restante em uma array print(a[0]) print(\"Tamanho: \" + str(len(curso)))",
"array a=curso.split(\" \") #remove tudo que estiver entre \"\" e divide o restante",
"maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\" \") #remove tudo que estiver entre",
"#print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\" \") #remove tudo que estiver entre \"\"",
"os espaços da string #print(curso.lower().strip()) #converte a string para letras minusculas #print(curso.upper()) #converte",
"para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\" \") #remove tudo que",
"a string para letras minusculas #print(curso.upper()) #converte a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\"))",
"letras minusculas #print(curso.upper()) #converte a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da",
"para letras minusculas #print(curso.upper()) #converte a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos",
"#print(curso.upper()) #converte a string para letras maiusculas #print(curso.replace(\"Python\",\"SQL\")) #troca objetos da array a=curso.split(\"",
"#troca objetos da array a=curso.split(\" \") #remove tudo que estiver entre \"\" e",
"tudo que estiver entre \"\" e divide o restante em uma array print(a[0])"
] |
[
":, -1:-2:-1] # mask= mask *255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def",
"mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask= mask *255 # cv2.imshow(\"vis\", mask)",
"import cv2 import numpy as np from src.base import Base from src.load_config import",
"cv2.COLOR_BGR2RGB) img[img >= 122] = 255 img[img < 122] = 1 img[img ==",
"import pdb import numpy as np import os import argparse import cv2 import",
"255] = 0 # BGR set all G and R to 0 img[:,",
"== 255] = 0 # BGR set all G and R to 0",
"mask *255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label = Labeling(cfg)",
"filename=None): img = cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] =",
"-1:-2:-1] # mask= mask *255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg):",
"binaryzation, args, random_crop class Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg) self.mode = '1_to_1'",
"0 img[:, :, 1] = 0 img[:, :, 2] = 0 cv2.imwrite(output_path, img)",
"== 'default' else args.mode def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img =",
"img[:, :, 1] = 0 img[:, :, 2] = 0 cv2.imwrite(output_path, img) #",
"# cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label = Labeling(cfg) label.handle() if",
"#pdb.set_trace() def labeling(cfg): label = Labeling(cfg) label.handle() if __name__ == '__main__': cfg =",
"import Base from src.load_config import load_yml from src.misc_utils import attach_file_suffix, binaryzation, args, random_crop",
"argparse import cv2 import numpy as np from src.base import Base from src.load_config",
"np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask= mask *255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0)",
"from src.misc_utils import attach_file_suffix, binaryzation, args, random_crop class Labeling(Base): def __init__(self, cfg): Base.__init__(self,",
"_handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path) # img = cv2.cvtColor(img,",
"= '1_to_1' if args.mode == 'default' else args.mode def _handle_image(self, input_path, output_path, compare_path=None,",
">= 122] = 255 img[img < 122] = 1 img[img == 255] =",
"img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] = 255 img[img < 122] =",
"def __init__(self, cfg): Base.__init__(self, cfg) self.mode = '1_to_1' if args.mode == 'default' else",
"= cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] = 255 img[img < 122] = 1",
"Base.__init__(self, cfg) self.mode = '1_to_1' if args.mode == 'default' else args.mode def _handle_image(self,",
"args.mode == 'default' else args.mode def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img",
"src.misc_utils import attach_file_suffix, binaryzation, args, random_crop class Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg)",
"# cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label = Labeling(cfg) label.handle() if __name__ == '__main__':",
"import os import argparse import cv2 import numpy as np from src.base import",
"img[img == 255] = 0 # BGR set all G and R to",
"= 0 img[:, :, 2] = 0 cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img),",
"encoding=utf-8 import pdb import numpy as np import os import argparse import cv2",
"labeling(cfg): label = Labeling(cfg) label.handle() if __name__ == '__main__': cfg = load_yml(args.ymlpath) labeling(cfg)",
"0 # BGR set all G and R to 0 img[:, :, 1]",
"if args.mode == 'default' else args.mode def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None):",
"import numpy as np from src.base import Base from src.load_config import load_yml from",
"src.load_config import load_yml from src.misc_utils import attach_file_suffix, binaryzation, args, random_crop class Labeling(Base): def",
"input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)",
"img[img >= 122] = 255 img[img < 122] = 1 img[img == 255]",
"= 0 # BGR set all G and R to 0 img[:, :,",
"abs_out_dir=None, filename=None): img = cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122]",
"src.base import Base from src.load_config import load_yml from src.misc_utils import attach_file_suffix, binaryzation, args,",
"img[img < 122] = 1 img[img == 255] = 0 # BGR set",
"# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] = 255 img[img < 122]",
"= 1 img[img == 255] = 0 # BGR set all G and",
"cv2 import numpy as np from src.base import Base from src.load_config import load_yml",
"import load_yml from src.misc_utils import attach_file_suffix, binaryzation, args, random_crop class Labeling(Base): def __init__(self,",
"Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg) self.mode = '1_to_1' if args.mode == 'default'",
"255 img[img < 122] = 1 img[img == 255] = 0 # BGR",
":, 2] = 0 cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1]",
"'1_to_1' if args.mode == 'default' else args.mode def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None,",
"# mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask= mask *255 # cv2.imshow(\"vis\",",
"= 0 cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask=",
"1 img[img == 255] = 0 # BGR set all G and R",
"compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >=",
"R to 0 img[:, :, 1] = 0 img[:, :, 2] = 0",
"self.mode = '1_to_1' if args.mode == 'default' else args.mode def _handle_image(self, input_path, output_path,",
"attach_file_suffix, binaryzation, args, random_crop class Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg) self.mode =",
"axis=2)[:, :, -1:-2:-1] # mask= mask *255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace()",
"import attach_file_suffix, binaryzation, args, random_crop class Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg) self.mode",
"cfg) self.mode = '1_to_1' if args.mode == 'default' else args.mode def _handle_image(self, input_path,",
"class Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg) self.mode = '1_to_1' if args.mode ==",
"= 255 img[img < 122] = 1 img[img == 255] = 0 #",
"import numpy as np import os import argparse import cv2 import numpy as",
"from src.load_config import load_yml from src.misc_utils import attach_file_suffix, binaryzation, args, random_crop class Labeling(Base):",
"img) # mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask= mask *255 #",
"random_crop class Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg) self.mode = '1_to_1' if args.mode",
"*255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label = Labeling(cfg) label.handle()",
"and R to 0 img[:, :, 1] = 0 img[:, :, 2] =",
"as np import os import argparse import cv2 import numpy as np from",
"all G and R to 0 img[:, :, 1] = 0 img[:, :,",
"mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label = Labeling(cfg) label.handle() if __name__ ==",
"img = cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] = 255",
"as np from src.base import Base from src.load_config import load_yml from src.misc_utils import",
"np import os import argparse import cv2 import numpy as np from src.base",
":, 1] = 0 img[:, :, 2] = 0 cv2.imwrite(output_path, img) # mask",
"__init__(self, cfg): Base.__init__(self, cfg) self.mode = '1_to_1' if args.mode == 'default' else args.mode",
"0 cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask= mask",
"G and R to 0 img[:, :, 1] = 0 img[:, :, 2]",
"to 0 img[:, :, 1] = 0 img[:, :, 2] = 0 cv2.imwrite(output_path,",
"cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask= mask *255",
"122] = 255 img[img < 122] = 1 img[img == 255] = 0",
"pdb import numpy as np import os import argparse import cv2 import numpy",
"args.mode def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path) # img",
"'default' else args.mode def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path)",
"img[:, :, 2] = 0 cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img), axis=2)[:, :,",
"= np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] # mask= mask *255 # cv2.imshow(\"vis\", mask) #",
"1] = 0 img[:, :, 2] = 0 cv2.imwrite(output_path, img) # mask =",
"np from src.base import Base from src.load_config import load_yml from src.misc_utils import attach_file_suffix,",
"# mask= mask *255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label",
"set all G and R to 0 img[:, :, 1] = 0 img[:,",
"< 122] = 1 img[img == 255] = 0 # BGR set all",
"# encoding=utf-8 import pdb import numpy as np import os import argparse import",
"os import argparse import cv2 import numpy as np from src.base import Base",
"2] = 0 cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img), axis=2)[:, :, -1:-2:-1] #",
"cfg): Base.__init__(self, cfg) self.mode = '1_to_1' if args.mode == 'default' else args.mode def",
"cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] = 255 img[img <",
"cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label = Labeling(cfg) label.handle() if __name__ == '__main__': cfg",
"from src.base import Base from src.load_config import load_yml from src.misc_utils import attach_file_suffix, binaryzation,",
"def labeling(cfg): label = Labeling(cfg) label.handle() if __name__ == '__main__': cfg = load_yml(args.ymlpath)",
"args, random_crop class Labeling(Base): def __init__(self, cfg): Base.__init__(self, cfg) self.mode = '1_to_1' if",
"numpy as np import os import argparse import cv2 import numpy as np",
"mask= mask *255 # cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label =",
"<reponame>misads/im_scripts # encoding=utf-8 import pdb import numpy as np import os import argparse",
"BGR set all G and R to 0 img[:, :, 1] = 0",
"def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path) # img =",
"# BGR set all G and R to 0 img[:, :, 1] =",
"load_yml from src.misc_utils import attach_file_suffix, binaryzation, args, random_crop class Labeling(Base): def __init__(self, cfg):",
"numpy as np from src.base import Base from src.load_config import load_yml from src.misc_utils",
"import argparse import cv2 import numpy as np from src.base import Base from",
"cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] = 255 img[img < 122] = 1 img[img",
"else args.mode def _handle_image(self, input_path, output_path, compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path) #",
"122] = 1 img[img == 255] = 0 # BGR set all G",
"0 img[:, :, 2] = 0 cv2.imwrite(output_path, img) # mask = np.unpackbits(np.array(img), axis=2)[:,",
"cv2.imshow(\"vis\", mask) # cv2.waitKey(0) #pdb.set_trace() def labeling(cfg): label = Labeling(cfg) label.handle() if __name__",
"= cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img >= 122] = 255 img[img",
"output_path, compare_path=None, abs_out_dir=None, filename=None): img = cv2.imread(input_path) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img[img",
"Base from src.load_config import load_yml from src.misc_utils import attach_file_suffix, binaryzation, args, random_crop class"
] |
[
"-*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class",
"from __future__ import unicode_literals from django.apps import AppConfig class SpidermanagerConfig(AppConfig): name = 'maincrawler'",
"-*- from __future__ import unicode_literals from django.apps import AppConfig class SpidermanagerConfig(AppConfig): name =",
"# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig",
"coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class SpidermanagerConfig(AppConfig):",
"utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class SpidermanagerConfig(AppConfig): name"
] |
[
"2 gaps = gaps[:100][::-1] # shell_sort for gap in gaps: array, tmp_cnt =",
"paste to the submission form. # ---------function------------ def insertion_sort(array, gap): n = len(array)",
"input_txt = \"\"\" 1 1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input()) # copy the",
"+= 1 gap = (3 ** i - 1) // 2 gaps =",
"gaps.append(gap) i += 1 gap = (3 ** i - 1) // 2",
"- gap while j >= 0 and array[j] > moving: array[j + gap]",
"1) // 2 gaps = gaps[:100][::-1] # shell_sort for gap in gaps: array,",
"tmp_cnt = insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for",
"below part and paste to the submission form. # ---------function------------ def insertion_sort(array, gap):",
"moving return array, cnt def main(): n = int(input()) array = [] for",
"moving = array[i] j = i - gap while j >= 0 and",
"moving: array[j + gap] = array[j] j -= gap cnt += 1 array[j",
"// 2 gaps = gaps[:100][::-1] # shell_sort for gap in gaps: array, tmp_cnt",
"# copy the below part and paste to the submission form. # ---------function------------",
"main(): n = int(input()) array = [] for i in range(n): array.append(int(input())) cnt",
"n = len(array) cnt = 0 for i in range(gap, n): moving =",
"0 and array[j] > moving: array[j + gap] = array[j] j -= gap",
"array.append(int(input())) cnt = 0 gaps = [] i = 1 gap = 1",
"i += 1 gap = (3 ** i - 1) // 2 gaps",
"<= n: gaps.append(gap) i += 1 gap = (3 ** i - 1)",
"cnt = 0 for i in range(gap, n): moving = array[i] j =",
"\".join(map(str, gaps))) print(cnt) for i in array: print(i) return main() # ----------------------------- sys.stdin",
"import sys import io input_txt = \"\"\" 1 1 \"\"\" sys.stdin = io.StringIO(input_txt)",
"to the submission form. # ---------function------------ def insertion_sort(array, gap): n = len(array) cnt",
"gap cnt += 1 array[j + gap] = moving return array, cnt def",
"gap] = moving return array, cnt def main(): n = int(input()) array =",
"n): moving = array[i] j = i - gap while j >= 0",
"while gap <= n: gaps.append(gap) i += 1 gap = (3 ** i",
"array = [] for i in range(n): array.append(int(input())) cnt = 0 gaps =",
"[] for i in range(n): array.append(int(input())) cnt = 0 gaps = [] i",
"i - gap while j >= 0 and array[j] > moving: array[j +",
"gaps = gaps[:100][::-1] # shell_sort for gap in gaps: array, tmp_cnt = insertion_sort(array,",
"io input_txt = \"\"\" 1 1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input()) # copy",
"= \"\"\" 1 1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input()) # copy the below",
"and paste to the submission form. # ---------function------------ def insertion_sort(array, gap): n =",
"gap] = array[j] j -= gap cnt += 1 array[j + gap] =",
"(3 ** i - 1) // 2 gaps = gaps[:100][::-1] # shell_sort for",
"while j >= 0 and array[j] > moving: array[j + gap] = array[j]",
"= gaps[:100][::-1] # shell_sort for gap in gaps: array, tmp_cnt = insertion_sort(array, gap)",
"cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for i in array: print(i)",
"= 1 gap = 1 while gap <= n: gaps.append(gap) i += 1",
"= array[i] j = i - gap while j >= 0 and array[j]",
"io.StringIO(input_txt) print(input()) # copy the below part and paste to the submission form.",
"print(input()) # copy the below part and paste to the submission form. #",
"0 for i in range(gap, n): moving = array[i] j = i -",
"= len(array) cnt = 0 for i in range(gap, n): moving = array[i]",
"return array, cnt def main(): n = int(input()) array = [] for i",
"range(n): array.append(int(input())) cnt = 0 gaps = [] i = 1 gap =",
"j >= 0 and array[j] > moving: array[j + gap] = array[j] j",
"= [] for i in range(n): array.append(int(input())) cnt = 0 gaps = []",
"i in range(n): array.append(int(input())) cnt = 0 gaps = [] i = 1",
"= i - gap while j >= 0 and array[j] > moving: array[j",
"= array[j] j -= gap cnt += 1 array[j + gap] = moving",
"---------function------------ def insertion_sort(array, gap): n = len(array) cnt = 0 for i in",
"i - 1) // 2 gaps = gaps[:100][::-1] # shell_sort for gap in",
"cnt += 1 array[j + gap] = moving return array, cnt def main():",
"# shell_sort for gap in gaps: array, tmp_cnt = insertion_sort(array, gap) cnt +=",
"part and paste to the submission form. # ---------function------------ def insertion_sort(array, gap): n",
"gap in gaps: array, tmp_cnt = insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps)) print(\"",
"= io.StringIO(input_txt) print(input()) # copy the below part and paste to the submission",
"gap): n = len(array) cnt = 0 for i in range(gap, n): moving",
"def main(): n = int(input()) array = [] for i in range(n): array.append(int(input()))",
"- 1) // 2 gaps = gaps[:100][::-1] # shell_sort for gap in gaps:",
"> moving: array[j + gap] = array[j] j -= gap cnt += 1",
"len(array) cnt = 0 for i in range(gap, n): moving = array[i] j",
"i in range(gap, n): moving = array[i] j = i - gap while",
"+= tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for i in array: print(i) return",
"-= gap cnt += 1 array[j + gap] = moving return array, cnt",
"gaps[:100][::-1] # shell_sort for gap in gaps: array, tmp_cnt = insertion_sort(array, gap) cnt",
"j = i - gap while j >= 0 and array[j] > moving:",
"# ---------function------------ def insertion_sort(array, gap): n = len(array) cnt = 0 for i",
"copy the below part and paste to the submission form. # ---------function------------ def",
"+ gap] = array[j] j -= gap cnt += 1 array[j + gap]",
"= 0 for i in range(gap, n): moving = array[i] j = i",
"shell_sort for gap in gaps: array, tmp_cnt = insertion_sort(array, gap) cnt += tmp_cnt",
"gap <= n: gaps.append(gap) i += 1 gap = (3 ** i -",
"= [] i = 1 gap = 1 while gap <= n: gaps.append(gap)",
"1 while gap <= n: gaps.append(gap) i += 1 gap = (3 **",
"array[j + gap] = array[j] j -= gap cnt += 1 array[j +",
"gaps))) print(cnt) for i in array: print(i) return main() # ----------------------------- sys.stdin =",
"gap = 1 while gap <= n: gaps.append(gap) i += 1 gap =",
"the submission form. # ---------function------------ def insertion_sort(array, gap): n = len(array) cnt =",
"for gap in gaps: array, tmp_cnt = insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps))",
"and array[j] > moving: array[j + gap] = array[j] j -= gap cnt",
"= 0 gaps = [] i = 1 gap = 1 while gap",
"form. # ---------function------------ def insertion_sort(array, gap): n = len(array) cnt = 0 for",
"array, cnt def main(): n = int(input()) array = [] for i in",
"range(gap, n): moving = array[i] j = i - gap while j >=",
"for i in range(n): array.append(int(input())) cnt = 0 gaps = [] i =",
"gaps = [] i = 1 gap = 1 while gap <= n:",
"sys.stdin = io.StringIO(input_txt) print(input()) # copy the below part and paste to the",
"+= 1 array[j + gap] = moving return array, cnt def main(): n",
"<filename>ALDS/ALDS1_2_D.py import sys import io input_txt = \"\"\" 1 1 \"\"\" sys.stdin =",
"in range(n): array.append(int(input())) cnt = 0 gaps = [] i = 1 gap",
"tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for i in array: print(i) return main()",
"print(\" \".join(map(str, gaps))) print(cnt) for i in array: print(i) return main() # -----------------------------",
"j -= gap cnt += 1 array[j + gap] = moving return array,",
"insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for i in",
"cnt def main(): n = int(input()) array = [] for i in range(n):",
"gap while j >= 0 and array[j] > moving: array[j + gap] =",
"int(input()) array = [] for i in range(n): array.append(int(input())) cnt = 0 gaps",
"submission form. # ---------function------------ def insertion_sort(array, gap): n = len(array) cnt = 0",
"array, tmp_cnt = insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt)",
"= moving return array, cnt def main(): n = int(input()) array = []",
"print(cnt) for i in array: print(i) return main() # ----------------------------- sys.stdin = sys.__stdin__",
"\"\"\" 1 1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input()) # copy the below part",
"= 1 while gap <= n: gaps.append(gap) i += 1 gap = (3",
"0 gaps = [] i = 1 gap = 1 while gap <=",
"for i in range(gap, n): moving = array[i] j = i - gap",
"print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for i in array: print(i) return main() #",
"array[j] j -= gap cnt += 1 array[j + gap] = moving return",
"gap) cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for i in array:",
"[] i = 1 gap = 1 while gap <= n: gaps.append(gap) i",
"array[i] j = i - gap while j >= 0 and array[j] >",
"import io input_txt = \"\"\" 1 1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input()) #",
"the below part and paste to the submission form. # ---------function------------ def insertion_sort(array,",
"= insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps))) print(cnt) for i",
"1 array[j + gap] = moving return array, cnt def main(): n =",
"gap = (3 ** i - 1) // 2 gaps = gaps[:100][::-1] #",
"1 1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input()) # copy the below part and",
"in range(gap, n): moving = array[i] j = i - gap while j",
"gaps: array, tmp_cnt = insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str, gaps)))",
"in gaps: array, tmp_cnt = insertion_sort(array, gap) cnt += tmp_cnt print(len(gaps)) print(\" \".join(map(str,",
"= int(input()) array = [] for i in range(n): array.append(int(input())) cnt = 0",
"i = 1 gap = 1 while gap <= n: gaps.append(gap) i +=",
"= (3 ** i - 1) // 2 gaps = gaps[:100][::-1] # shell_sort",
"** i - 1) // 2 gaps = gaps[:100][::-1] # shell_sort for gap",
"insertion_sort(array, gap): n = len(array) cnt = 0 for i in range(gap, n):",
"\"\"\" sys.stdin = io.StringIO(input_txt) print(input()) # copy the below part and paste to",
"array[j + gap] = moving return array, cnt def main(): n = int(input())",
"1 gap = 1 while gap <= n: gaps.append(gap) i += 1 gap",
"def insertion_sort(array, gap): n = len(array) cnt = 0 for i in range(gap,",
"array[j] > moving: array[j + gap] = array[j] j -= gap cnt +=",
"1 gap = (3 ** i - 1) // 2 gaps = gaps[:100][::-1]",
">= 0 and array[j] > moving: array[j + gap] = array[j] j -=",
"n: gaps.append(gap) i += 1 gap = (3 ** i - 1) //",
"+ gap] = moving return array, cnt def main(): n = int(input()) array",
"1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input()) # copy the below part and paste",
"cnt = 0 gaps = [] i = 1 gap = 1 while",
"n = int(input()) array = [] for i in range(n): array.append(int(input())) cnt =",
"sys import io input_txt = \"\"\" 1 1 \"\"\" sys.stdin = io.StringIO(input_txt) print(input())"
] |
[
"import setup, find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15',",
"scripts = [ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\":",
"'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require = [ 'unittest' ] scripts = [",
"version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong',",
"description=''' This is just a test package for learn something about 'How to",
"is just a test package for learn something about 'How to create a",
"for learn something about 'How to create a python package' ''', exclude_package_date={ 'Animal-Courier':",
"package for learn something about 'How to create a python package' ''', exclude_package_date={",
"a python package' ''', exclude_package_date={ 'Animal-Courier': ['.gitignore', '.circleci/*', '.anaconda/*'], }, install_requires=install_requires, scripts=scripts, )",
"\"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This is just a test",
"'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>',",
"= [ 'unittest' ] scripts = [ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'),",
"[ 'unittest' ] scripts = [ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']),",
"configparser from setuptools import setup, find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires = [",
"test package for learn something about 'How to create a python package' ''',",
"[ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require =",
"'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require = [",
"from setuptools import setup, find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15',",
"install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ]",
"configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly',",
"'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require = [ 'unittest' ]",
"'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require = [ 'unittest' ] scripts",
"\"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This is just",
"tests_require = [ 'unittest' ] scripts = [ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest',",
"find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5',",
"learn something about 'How to create a python package' ''', exclude_package_date={ 'Animal-Courier': ['.gitignore',",
"import configparser from setuptools import setup, find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires =",
"'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require = [ 'unittest' ] scripts =",
"] tests_require = [ 'unittest' ] scripts = [ 'bin/multi_run.py' ] setup( name='Animal-Courier',",
"] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", },",
"packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description='''",
"version = configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7',",
"[ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\":",
"author='chenyuelong', author_email='<EMAIL>', description=''' This is just a test package for learn something about",
"to create a python package' ''', exclude_package_date={ 'Animal-Courier': ['.gitignore', '.circleci/*', '.anaconda/*'], }, install_requires=install_requires,",
"= [ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\",",
"setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT",
"create a python package' ''', exclude_package_date={ 'Animal-Courier': ['.gitignore', '.circleci/*', '.anaconda/*'], }, install_requires=install_requires, scripts=scripts,",
"License', author='chenyuelong', author_email='<EMAIL>', description=''' This is just a test package for learn something",
"'How to create a python package' ''', exclude_package_date={ 'Animal-Courier': ['.gitignore', '.circleci/*', '.anaconda/*'], },",
"author_email='<EMAIL>', description=''' This is just a test package for learn something about 'How",
"'unittest' ] scripts = [ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier',",
"setup, find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8',",
"version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise'",
"'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\",",
"something about 'How to create a python package' ''', exclude_package_date={ 'Animal-Courier': ['.gitignore', '.circleci/*',",
"project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This is",
"a test package for learn something about 'How to create a python package'",
"'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require = [ 'unittest'",
"}, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This is just a test package for",
"name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License',",
"= [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0', 'plotly', 'apprise' ] tests_require",
"= configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4', 'certifi>=2018.10.15', 'psutil>=5.4.8', 'python-dateutil>=2.7.5', 'pytz>=2018.7', 'six>=1.12.0',",
"'six>=1.12.0', 'plotly', 'apprise' ] tests_require = [ 'unittest' ] scripts = [ 'bin/multi_run.py'",
"This is just a test package for learn something about 'How to create",
"'plotly', 'apprise' ] tests_require = [ 'unittest' ] scripts = [ 'bin/multi_run.py' ]",
"license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This is just a test package for learn",
"just a test package for learn something about 'How to create a python",
"'apprise' ] tests_require = [ 'unittest' ] scripts = [ 'bin/multi_run.py' ] setup(",
"] scripts = [ 'bin/multi_run.py' ] setup( name='Animal-Courier', version=version.get('latest', 'version'), packages=find_packages(exclude=['tests']), url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={",
"url='https://github.com/dota2-BioTools/Animal-Courier', project_urls={ \"issues\": \"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This",
"\"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This is just a test package",
"setuptools import setup, find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires = [ 'numpy>=1.15', 'pandas>=0.23.4',",
"\"https://github.com/dota2-BioTools/Animal-Courier/issues\", \"releases\": \"https://github.com/dota2-BioTools/Animal-Courier/releases\", }, license='MIT License', author='chenyuelong', author_email='<EMAIL>', description=''' This is just a",
"<reponame>btrspg/Animal-Courier import configparser from setuptools import setup, find_packages version = configparser.ConfigParser() version.read('VERSION') install_requires",
"about 'How to create a python package' ''', exclude_package_date={ 'Animal-Courier': ['.gitignore', '.circleci/*', '.anaconda/*'],"
] |
[
"free and false otherwise if self.map[pos] == chr(32) or self.map[pos].islower(): return True else:",
"return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, agtfrom, agtto) else:",
"__WaitPrec_t(self, t): if t in self.concurrent: joint_concurrent = self.concurrent[t] # a state that",
"letter][agent number (0 since it is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: # Checks",
"external_key) del self.boxes[external_key] self.map[pos] = \" \" def deleteGoal(self, external_key): del self.goals[external_key] def",
"# print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd == \"Push\": # (agtfrom, boxfrom,",
"0), \"W\": (0, -1)} self.deltaPos = { (-1, 0): \"N\", (0, 1): \"E\",",
"return self.agentColor[color] def getBoxesByKey(self, key): key = key.upper() # same as getPos, just",
"movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir, i) if actionParams is not None: return",
"if the state is a goal state keys = self.getGoalKeys() for key in",
"by adding a time table to the usual `StateInit`. Parameters ---------- parent: StateInit",
"next time `self.t`. This ensures that agents just wait if the next state",
"is not None: child = StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) #",
"of the agent self.map[pos] = key self.agents[key] = [[pos, color]] # This is",
"self.map[pos[0], pos[1]] = obj_key else: # agents don't leave ghosts behind and are",
"# if key not in self.agents: # return None return self.agents[key] def getAgentsByColor(self,",
"# print(\"Direction\", boxdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1:",
"StateInit(Literals): def __init__(self, parent: \"Literals\" = None): # initializes the state # it",
"joint_concurrent.values(): if pos is None: continue if agent_pos[0] == pos[0] and agent_pos[1] ==",
"agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values(): if pos is None:",
"literals.\"\"\" def __init__(self, parent: StateInit = None, concurrent: Dict = None): \"\"\"Initialize by",
"= state.prevState else: # format used by server while state.actionPerformed is not None:",
"all agents with the given key return self.agentColor[color] def getBoxesByKey(self, key): key =",
"objtype[obj][i][0] else: return None def setPos(self, objtype, obj, pos, i=0): # sets the",
"\"agents\" if format.isnumeric() else \"boxes\" while state.actionPerformed is not None: path.append( [ state.t,",
"child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is there some",
"None self.g = 0 self.t = 0 self.h = None self.f = None",
"cmd = state.actionPerformed[0] if cmd == \"Push\": # (agtfrom, boxfrom, boxto) parm1 =",
"state.actionPerformed is not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd ==",
"[] # Loop iterales through every possible action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec():",
"anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t in self.concurrent:",
"getPos, just for all agents with the given key # if key not",
"This is only used to get easy access to agents by color if",
"...}, ...} \"\"\" super().__init__(parent) self.concurrent = concurrent if concurrent else parent.concurrent self.hunt_ghost() def",
"i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent number (0 since it",
"given key # if key not in self.goals: # return None return self.goals[key]",
"rigid self.goals = parent.goals # rigid self.agentColor = parent.agentColor # rigid # TODO",
"# initializes the state # it is (row, column) and not (x, y)",
"# Moves the object with the given parameters # Does not check preconditions",
"str(boxfrom) + \" (row,col)\") return True def Push(self, agt, boxkey, boxdir, i): #",
"= [] state = copy.deepcopy(self) if format == 1: # format used by",
"unique thus 0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom] = agt",
"action by another agent. \"\"\" return self.t in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify",
"are not in the StateInit self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0], pos[1]] =",
"self.__PushEffect(*actionParams) else: return None def __PullPrec(self, agt, boxkey, agtdir, i=0): # Moves the",
"class StateInit(Literals): def __init__(self, parent: \"Literals\" = None): # initializes the state #",
"a Move action if it is possible it is appended to the the",
"= copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState = parent # reference",
"str(boxto) + \" (row,col) is not free\") return None def __PushEffect(self, agt, boxkey,",
"and not (x, y) super().__init__(parent) def getAgentsByKey(self, key): # same as getPos, just",
"boxkey, agtfrom, boxfrom, boxto, i): # Moves the objects with the given parameters",
"\"\"\"def updateParentCost(self, total_cost): state = self.prevState i = 0 while state is not",
"to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed =",
"ghost box which will be removed on child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\"",
"self.agents[key] = [[pos, color]] # This is only used to get easy access",
"exist\") return None if boxdir not in self.dir: # # # print(\"Direction\", boxdir,",
"hashtable self.agents = {} # hashtable self.boxes = {} # hashtable self.prevState =",
"will be called by by strategy. \"\"\" future = [t for t in",
"agtto[1] - agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt, agtdir): # returns the movement",
"def isExplored(self): # returns true if the state is explored return self.minimalRep() in",
"the state is explored return self.minimalRep() in self.explored def __addToExplored(self, children): # adds",
"self.map[boxto] = boxkey # print(\"Agent \" + agt + \" is now at",
"!= external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0): # gets the position of",
"+ \" is now at \" + str(boxto) + \" (row,col)\") # print(\"Box",
"to have only one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in",
"getPos(objecttype, the key, the index (if multiple)) # returns None if not in",
"= {} # hashtable self.boxes = {} # hashtable self.prevState = None self.actionPerformed",
"+ agt + \" is now at \" + str(agtto) + \" (row,col)\")",
"actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move action if it is possible it",
"parameters if the preconditions are met # otherwise it returns 0 agtfrom =",
"(if multiple)) # returns None if not in hashtable if obj in objtype:",
"parent: StateInit = None, concurrent: Dict = None): \"\"\"Initialize by adding a time",
"boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom is None: # # # print(\"agent\",",
"= [] # Loop iterales through every possible action for direction in self.dir:",
"return self future_self = self while next_time > future_self.t: println(future_self) future_self = StateConcurrent(future_self)",
"copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for direction in self.dir: for agtkey in",
"to all children. \"\"\" children = [] # Loop iterales through every possible",
"`self.t`. This ensures that agents just wait if the next state is new",
"to previous state self.actionPerformed = None # gets defined when action is chosen",
"child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\" def __init__(self, parent:",
"= [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push action if it is",
"self.concurrent if t > self.t] if future: return min(future) return False def advance(self)",
"time `self.t`. This ensures that agents just wait if the next state is",
"np from utils import println class Literals: def __init__(self, parent: \"Literals\" = None):",
"obj, i=0): # gets the position of an object getPos(objecttype, the key, the",
"# reference to previous state self.actionPerformed = None # gets defined when action",
"at boxes at the # neighboring tiles of the agent for boxkey in",
"other agent.\"\"\" next_time = self.AdvancePrec() if not next_time: return self future_self = self",
"Moves the object with the given parameters # Does not check preconditions self.setPos(self.agents,",
"usual `StateInit`. Parameters ---------- parent: StateInit concurrent: Dict Shared table that contains times",
"\" \" for color in self.agentColor: if external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key)",
"free # returns true if it is free and false otherwise if self.map[pos]",
"checks the precondition and does the movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir, i)",
"# agents don't leave ghosts behind and are not in the StateInit self.map[self.map",
"== \"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos, index)",
"is being solved is guaranteed to have only one agent agent_pos = self.getPos(self.agents,",
"self.concurrent[t] # a state that it is being solved is guaranteed to have",
"to the the children actionParams = self.__MovePrec(agtkey, direction) if actionParams is not None:",
"time until the environment is changed by other agent.\"\"\" next_time = self.AdvancePrec() if",
"(row, column) and not (x, y) super().__init__(parent) def getAgentsByKey(self, key): # same as",
"possible action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent effects to all",
"agtdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1: # #",
"color]) def addBox(self, key, pos, color=\"c\"): # Adds a box to the map",
"# Debugging purposes return \"\\n\".join([\"\".join(line) for line in self.map]) + f\" t={self.t}\" class",
"if it is possible it is appended to the the children actionParams =",
"(row,col)\") return True def Move(self, agt, agtdir): # moves the object in the",
"line in self.map]) + f\" t={self.t}\" class StateInit(Literals): def __init__(self, parent: \"Literals\" =",
"[[pos, color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored = set()",
"True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes of the world. Something has",
"for agtkey in self.agents: # TODO make a noop function child = StateInit(self)",
"= \"Ñ\" self.map[pos[0], pos[1]] = obj_key return True def hunt_ghost(self): \"\"\"Remove ghosted positions",
"child_def.__ConcurrentPrec(): # apply concurrent effects to all children but also append # a",
"self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks if the state is a goal",
"# gets defined when action is chosen self.g = parent.g + 1 self.h",
"in self.concurrent if t > self.t] if future: return min(future) return False def",
"i = 0 while state is not None: i += 1 state.h =",
"boxes at # the neighboring tiles of the agent for boxkey in child_def.boxes:",
"= state.prevState elif isinstance(format, str): # trace back an object looking_for = format",
"np.array(map2) def addAgent(self, key, pos, color=\"c\"): # Adds an agent to the map",
"def getBoxesByKey(self, key): key = key.upper() # same as getPos, just for all",
"utils import println class Literals: def __init__(self, parent: \"Literals\" = None): # initializes",
"it returns 0 agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if",
"agt, boxkey, agtfrom, agtto, boxfrom, i): # Moves the objects with the given",
"is possible it is appended to the the children actionParams = self.__PullPrec(agtkey, boxkey,",
"is not free\") return None def __MoveEffect(self, agt, agtfrom, agtto): # Moves the",
"not in self.boxes: # return None return self.boxes[key] def getGoalsByKey(self, key): key =",
"# returns the direction the agent moved dir = (agtto[0] - agtfrom[0], agtto[1]",
"object # setPos(objecttype, the key, position, the index (if multiple)) # returns None",
"\"boxes\" if obj_group == \"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group),",
"None return self.boxes[key] def getGoalsByKey(self, key): key = key.lower() # same as getPos,",
"list of children children = [] # Loop iterales through every possible action",
"# Checks a Move action if it is possible it is appended to",
"child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push action if it",
"t in self.concurrent if t > self.t] if future: return min(future) return False",
"= set() else: # if a parent is present! self.dir = parent.dir #",
"# Returns true if the 2 positions are neighbours, otherwise false if abs(pos1[0]",
"Returns true if the 2 positions are neighbours, otherwise false if abs(pos1[0] -",
"(0 since it is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: # Checks a pull",
"while state.actionPerformed is not None: path.append(state.actionPerformed) state = state.prevState elif isinstance(format, str): #",
"= { (-1, 0): \"N\", (0, 1): \"E\", (1, 0): \"S\", (0, -1):",
"+ agt + \" is now at \" + str(boxto) + \" (row,col)\")",
"(agt, agtfrom, agtto) else: # # # print(\"Pos \" + str(agtto) + \"",
"Parameters ---------- parent: StateInit concurrent: Dict Shared table that contains times where an",
"function returns the list of actions used to reach the state path =",
"objects with the given parameters # Does not check preconditions self.setPos(self.agents, agt, boxfrom,",
"StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\" def __init__(self, parent: StateInit = None, concurrent:",
"and are not in the StateInit self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0], pos[1]]",
"self.t] if future: return min(future) return False def advance(self) -> StateInit: \"\"\"Advance in",
"self.agents: # return None return self.agents[key] def getAgentsByColor(self, color): # same as getPos,",
"= key if key not in self.boxes: self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos,",
"through every possible action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent effects",
"all agents with the given key # if key not in self.agents: #",
"path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for, index), ] ) state = state.prevState else:",
"import numpy as np from utils import println class Literals: def __init__(self, parent:",
"agtto, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom]",
"False return True def bestPath(self, format=0, index=0): # function returns the list of",
"pos, color=\"c\"): # Adds an agent to the map and to a hashtable",
"if external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key): pos",
"action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent effects to all children",
"+ 1 self.h = None self.f = None self.t = parent.t + 1",
"def Pull(self, agt, boxkey, boxdir, i): # moves the objects in the given",
"the agent number and color is the color of the agent self.map[pos] =",
"state is new and applies the concurrent changes to all children. \"\"\" children",
"return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, boxkey, agtfrom, agtto,",
"else: # # # print(\"Pos \" + str(agtto) + \" (row,col) is not",
"[\"NoOp\", None] child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\" def",
"from utils import println class Literals: def __init__(self, parent: \"Literals\" = None): #",
"= self.getPos(self.boxes, boxkey, i) if agtfrom is None: # # # print(\"agent\", agt,",
"agtfrom, agtto, boxfrom, i): # Moves the objects with the given parameters #",
"list of actions used to reach the state path = [] state =",
"\" is now at \" + str(boxto) + \" (row,col)\") # print(\"Box \"",
"\" def deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for",
"the the children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction, i ) if actionParams",
"\" + str(box) + \" is now at \" + str(boxfrom) + \"",
"= self.concurrent[t] # a state that it is being solved is guaranteed to",
"in joint_concurrent.values(): if pos is None: continue if agent_pos[0] == pos[0] and agent_pos[1]",
"= [[pos, color]] # This is only used to get easy access to",
"self.agents = {} # hashtable self.boxes = {} # hashtable self.prevState = None",
"is a letter key = key.upper() self.map[pos] = key if key not in",
"# same as getPos, just for all Goal with the given key #",
"it is possible it is appended to the the children actionParams = child_def._StateInit__PullPrec(",
"through every possible action for direction in self.dir: for agtkey in self.agents: #",
"framework.\"\"\" import copy import operator from typing import Dict import numpy as np",
"self future_self = self while next_time > future_self.t: println(future_self) future_self = StateConcurrent(future_self) future_self.actionPerformed",
"pos, color in goals: if self.map[pos] != key.upper(): return False return True def",
"present! self.dir = {\"N\": (-1, 0), \"E\": (0, 1), \"S\": (1, 0), \"W\":",
"key not in self.goals: self.goals[key] = [[pos, color]] else: self.goals[key].append([pos, color]) def addBox(self,",
"the given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] =",
"{t: {box: [(row, col), index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent = concurrent if",
"precondition for concurrent changes of the world. Something has changed given a concurrent",
"his position without doing anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t):",
"parent is present! self.dir = parent.dir # rigid self.deltaPos = parent.deltaPos # rigid",
"the environment is changed by other agent.\"\"\" next_time = self.AdvancePrec() if not next_time:",
"all the keys return list(self.goals.keys()) def getAgentKeys(self): # returns all the keys return",
") if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams]",
"= child_def._StateInit__PullPrec( agtkey, boxkey, direction, i ) if actionParams is not None: child",
"TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState",
"hashtable # key is a letter key = key.upper() self.map[pos] = key if",
"y) super().__init__(parent) def getAgentsByKey(self, key): # same as getPos, just for all agents",
"optimized by only looking at boxes at # the neighboring tiles of the",
"defined when action is chosen self.g = parent.g + 1 self.h = None",
"children def AdvancePrec(self): \"\"\"Is there some concurrent change in the future. It will",
"def getAgentKeys(self): # returns all the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state",
"perhaps be optimized by only looking at boxes at # the neighboring tiles",
"self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": # (agtfrom,",
"if self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom, boxto, i) else: # # #",
"external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key): pos =",
"given a concurrent action by another agent. \"\"\" return self.t in self.concurrent def",
"check preconditions self.setPos(self.agents, agt, boxfrom, 0) # agents are unique thus 0 self.setPos(self.boxes,",
"with the given key # if key not in self.goals: # return None",
"# print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return None boxto =",
"the the children actionParams = self.__MovePrec(agtkey, direction) if actionParams is not None: child",
"1: # # # print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return",
"walls self.map = np.array(map2) def addAgent(self, key, pos, color=\"c\"): # Adds an agent",
"[] state = copy.deepcopy(self) if format == 1: # format used by actions",
"returns the movement parameters if the preconditions are met # otherwise it returns",
"color): # same as getPos, just for all agents with the given key",
"return self.t in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment according to concurrent actions",
"given key # if key not in self.boxes: # return None return self.boxes[key]",
"not in the StateInit self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0], pos[1]] = obj_key",
"objtype, obj, i=0): # gets the position of an object getPos(objecttype, the key,",
"returns None if not in hashtable if obj in objtype: return objtype[obj][i][0] else:",
"return None def __PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom, i): # Moves the",
"boxdir, i) if actionParams is not None: return self.__PullEffect(*actionParams) else: return None def",
"state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): # simply adds two positions together return tuple(map(operator.add,",
"(1, 0): \"S\", (0, -1): \"W\", } self.goals = {} # hashtable self.agentColor",
"another agent: {t: {box: [(row, col), index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent =",
"addAgent(self, key, pos, color=\"c\"): # Adds an agent to the map and to",
"\"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t in self.concurrent: joint_concurrent",
"# [agent letter][agent number (0 since it is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor:",
"\" + str(agtto) + \" (row,col)\") return True def Move(self, agt, agtdir): #",
"= self.__MovePrec(agt, agtdir) if actionParams is not None: return self.__MoveEffect(*actionParams) else: return None",
"def deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] = \" \"",
"when action is chosen self.g = parent.g + 1 self.h = None self.f",
"self.g = parent.g + 1 self.h = None self.f = None self.t =",
"given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto, 0) # agents",
"ext_agents = list(self.agents.keys()) for external_agent in ext_agents: if external_agent != external_key: self.deleteAgent(external_agent) def",
"(if multiple)) # returns None if not in hashtable if type(objtype[obj][i][0]) == tuple:",
"path[::-1] def explore(self): # Explores unexplroed states and returns a list of children",
"not check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto] = agt #",
"Reverse the order return path[::-1] def explore(self): # Explores unexplroed states and returns",
"\"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif cmd ==",
"external_agent in ext_agents: if external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals =",
"while state is not None: i += 1 state.h = total_cost + i",
"__PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto, i): # Moves the objects with the",
"which just waits for the env to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if",
"self.goals[key] def getGoalKeys(self): # returns all the keys return list(self.goals.keys()) def getAgentKeys(self): #",
"initialized a map with only walls self.map = np.array(map2) def addAgent(self, key, pos,",
"if obj in objtype: return objtype[obj][i][0] else: return None def setPos(self, objtype, obj,",
"not in self.boxes: self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove",
"letter key = key.lower() if key not in self.goals: self.goals[key] = [[pos, color]]",
"state = self.prevState i = 0 while state is not None: i +=",
"+ str(box) + \" is now at \" + str(boxfrom) + \" (row,col)\")",
"= [\"NoOp\", None] child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\"",
"a letter key = key.upper() self.map[pos] = key if key not in self.boxes:",
"= copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState = parent # reference to previous state",
"is changed by other agent.\"\"\" next_time = self.AdvancePrec() if not next_time: return self",
"print(\"Direction\", agtdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1: #",
"not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1: # # # print(\"agent\",",
"self while next_time > future_self.t: println(future_self) future_self = StateConcurrent(future_self) future_self.actionPerformed = [\"NoOp\", None]",
"the environment has been changed by another agent: {t: {box: [(row, col), index],",
"pos, index) # introduce a ghost box which will be removed on child",
"appended to the the children actionParams = self.__PullPrec(agtkey, boxkey, direction, i) if actionParams",
"self.t = 0 self.h = None self.f = None self.explored = set() else:",
"def getAgentsByColor(self, color): # same as getPos, just for all agents with the",
"time `t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key in joint_concurrent: pos, index = list(joint_concurrent[obj_key])",
"the 2 positions are neighbours, otherwise false if abs(pos1[0] - pos2[0]) + abs(pos1[1]",
"= [[pos, color]] else: self.goals[key].append([pos, color]) def addBox(self, key, pos, color=\"c\"): # Adds",
"thus 0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom] = agt self.map[boxto]",
"hashtable self.boxes = {} # hashtable self.prevState = None self.actionPerformed = None self.g",
"parent.goals # rigid self.agentColor = parent.agentColor # rigid # TODO avoid deepcopies self.agents",
"# This is only used to get easy access to agents by color",
"`agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] = \" \" for color",
"with concurrent literals.\"\"\" def __init__(self, parent: StateInit = None, concurrent: Dict = None):",
"the children actionParams = self.__PullPrec(agtkey, boxkey, direction, i) if actionParams is not None:",
"exist\") return None if agtdir not in self.dir: # # # print(\"Direction\", agtdir,",
"`StateInit`. Parameters ---------- parent: StateInit concurrent: Dict Shared table that contains times where",
"not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children",
"print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return None boxto = self.__addPos(boxfrom,",
"i) if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Push\", actionParams]",
"child = StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push",
"and does the movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir, i) if actionParams is",
"] ) state = state.prevState else: # format used by server while state.actionPerformed",
"in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is",
"the movemnt actionParams = self.__MovePrec(agt, agtdir) if actionParams is not None: return self.__MoveEffect(*actionParams)",
"object (box) in the environment has been changed by another agent: {t: {box:",
"None: return self.__PushEffect(*actionParams) else: return None def __PullPrec(self, agt, boxkey, agtdir, i=0): #",
"boxkey, i) if agtfrom is None: # # # print(\"agent\", agt, \"does not",
"format used by actions while state.actionPerformed is not None: path.append(state.actionPerformed) state = state.prevState",
"# # # print(\"Box\", boxkey, \"does not exist\") return None if boxdir not",
"while state.actionPerformed is not None: path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for, index), ]",
"key = key.lower() if key not in self.goals: self.goals[key] = [[pos, color]] else:",
"child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for direction",
"state.actionPerformed[0] if cmd == \"Push\": # (agtfrom, boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2],",
"it checks the precondition and does the movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir,",
"boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom] = agt self.map[boxto] = boxkey # print(\"Agent",
"= None self.actionPerformed = None self.g = 0 self.t = 0 self.h =",
"- agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt, agtdir): # returns",
"\"and box\", boxkey, \"are not neighbors\") return None boxto = self.__addPos(boxfrom, boxdir) if",
"(row,col)\") return True def Pull(self, agt, boxkey, boxdir, i): # moves the objects",
"actions schemas for the muli-PDDL framework.\"\"\" import copy import operator from typing import",
"self.boxes[key] def getGoalsByKey(self, key): key = key.lower() # same as getPos, just for",
"agtdir not in self.dir: # # # print(\"Direction\", agtdir, \"does not exist\") return",
"is possible it is appended to the the children actionParams = child_def._StateInit__PullPrec( agtkey,",
"self.goals[key].append([pos, color]) def addBox(self, key, pos, color=\"c\"): # Adds a box to the",
"[[pos, color]] else: self.goals[key].append([pos, color]) def addBox(self, key, pos, color=\"c\"): # Adds a",
"self.agentColor[color].append(key) def addGoal(self, key, pos, color=None): # Adds a goal to a hashtable",
"otherwise if self.map[pos] == chr(32) or self.map[pos].islower(): return True else: return False def",
"self.map[agtto] = agt # print(\"Agent \" + agt + \" is now at",
"time table to the usual `StateInit`. Parameters ---------- parent: StateInit concurrent: Dict Shared",
"not check preconditions self.setPos(self.agents, agt, boxfrom, 0) # agents are unique thus 0",
"StateInit: \"\"\"Advance in time until the environment is changed by other agent.\"\"\" next_time",
"number (0 since it is unique)][color] if self.agents[agtkey][0][1] == boxcolor: # Checks a",
") parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif cmd ==",
"Push action if it is possible it is appended to the the children",
"# if key not in self.goals: # return None return self.goals[key] def getGoalKeys(self):",
"self.dir: for agtkey in self.agents: # TODO reformat these nested loops and if",
"changes of the world. Something has changed given a concurrent action by another",
"if the next state is new and applies the concurrent changes to all",
"= concurrent if concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp.",
"= child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed =",
"(row,col)\") return True def Push(self, agt, boxkey, boxdir, i): # moves the objects",
"None self.t = parent.t + 1 self.explored = parent.explored super().__init__() def addMap(self, map2):",
"True def Push(self, agt, boxkey, boxdir, i): # moves the objects in the",
"returns None if not in hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos",
"another agent. \"\"\" return self.t in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment according",
"if format == 1: # format used by actions while state.actionPerformed is not",
"(0 since it is unique)][color] if self.agents[agtkey][0][1] == boxcolor: # Checks a pull",
"from typing import Dict import numpy as np from utils import println class",
"(1, 0), \"W\": (0, -1)} self.deltaPos = { (-1, 0): \"N\", (0, 1):",
"self.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it is possible it",
"# returns the movement parameters if the preconditions are met # otherwise it",
"= f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": # (agtfrom, agtto, boxfrom) parm1 = self.__getDir(",
"hashtable self.prevState = None self.actionPerformed = None self.g = 0 self.t = 0",
"\"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1: # # #",
"# Loop iterales through every possible action for direction in self.dir: for agtkey",
"by actions while state.actionPerformed is not None: path.append(state.actionPerformed) state = state.prevState elif isinstance(format,",
"self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key)",
"i += 1 state.h = total_cost + i state.f = state.g + state.h",
"\" (row,col)\") return True def Move(self, agt, agtdir): # moves the object in",
"+ str(agtfrom) + \" (row,col)\") return True def Pull(self, agt, boxkey, boxdir, i):",
"neighbours, otherwise false if abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) == 1:",
"None if not in hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos else:",
"pos = self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] = \" \" for color in",
"precondition and does the movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir, i) if actionParams",
"parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif cmd == \"Pull\":",
"= parent.map.copy() self.prevState = parent # reference to previous state self.actionPerformed = None",
"= 0 self.h = None self.f = None self.explored = set() else: #",
"self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values(): if pos is None: continue if",
"+ \" (row,col)\") return True def Move(self, agt, agtdir): # moves the object",
"not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks if the state is a",
"return True else: return False def Color(self, obj): pass def Neighbour(self, pos1, pos2):",
"changed by another agent: {t: {box: [(row, col), index], ...}, ...} \"\"\" super().__init__(parent)",
"True else: return False def Color(self, obj): pass def Neighbour(self, pos1, pos2): #",
"return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t in self.concurrent: joint_concurrent =",
"is present! self.dir = parent.dir # rigid self.deltaPos = parent.deltaPos # rigid self.goals",
"return None return self.goals[key] def getGoalKeys(self): # returns all the keys return list(self.goals.keys())",
"not None: child = StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks",
"not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks",
"agtfrom, agtto, boxfrom, i) else: # # # print(\"Pos \" + str(agtto) +",
"agt, agtfrom, agtto): # Moves the object with the given parameters # Does",
"color]] # This is only used to get easy access to agents by",
"if abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) == 1: return True else:",
"# checks if position in map is free # returns true if it",
"keys return list(self.goals.keys()) def getAgentKeys(self): # returns all the keys return list(self.agents.keys()) \"\"\"def",
"state = state.prevState elif isinstance(format, str): # trace back an object looking_for =",
"possible action for direction in self.dir: for agtkey in self.agents: # TODO reformat",
"and applies the concurrent changes to all children. \"\"\" children = [] #",
"# print(\"agent\", agt, \"does not exist\") return None if agtdir not in self.dir:",
"explored list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks if the",
"None def Free(self, pos): # checks if position in map is free #",
"-1)} self.deltaPos = { (-1, 0): \"N\", (0, 1): \"E\", (1, 0): \"S\",",
"if actionParams is not None: return self.__PushEffect(*actionParams) else: return None def __PullPrec(self, agt,",
"in self.dir: # # # print(\"Direction\", agtdir, \"does not exist\") return None if",
"in self.agentColor: if external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self,",
"by another agent; i.e., there is an entry in `self.concurrent` for the next",
"agtto): # returns the direction the agent moved dir = (agtto[0] - agtfrom[0],",
"changed by another agent; i.e., there is an entry in `self.concurrent` for the",
"for all agents with the given key # if key not in self.agents:",
"in self.dir: # # # print(\"Direction\", boxdir, \"does not exist\") return None if",
"return objtype[obj][i][0] else: return None def setPos(self, objtype, obj, pos, i=0): # sets",
"actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children)",
"\"\"\" super().__init__(parent) self.concurrent = concurrent if concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate",
"it is free and false otherwise if self.map[pos] == chr(32) or self.map[pos].islower(): return",
"is free # returns true if it is free and false otherwise if",
"not neighbors\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, boxkey,",
"child.__addToExplored(children) # Checks a Push action if it is possible it is appended",
"no parent is present! self.dir = {\"N\": (-1, 0), \"E\": (0, 1), \"S\":",
"Does not check preconditions self.setPos(self.agents, agt, agtto, 0) # agents are unique thus",
"self.map[agtfrom] = boxkey self.map[agtto] = agt # print(\"Agent \" + agt + \"",
"# return None return self.agents[key] def getAgentsByColor(self, color): # same as getPos, just",
"representation of the states return str([self.agents, self.boxes]) def isExplored(self): # returns true if",
"a box to the map and to a hashtable # key is a",
"external_key): boxes = list(self.boxes.keys()) for external_agent in boxes: if external_agent != external_key: self.deleteBox(external_agent)",
"self.map = parent.map.copy() self.prevState = parent # reference to previous state self.actionPerformed =",
"self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key) def addGoal(self, key, pos, color=None): # Adds",
"is possible it is appended to the the children actionParams = self.__MovePrec(agtkey, direction)",
"it is appended to the the children # Checks a Move action if",
"= f\"Move({parm1})\" elif cmd == \"NoOp\": cmd = \"NoOp\" path.append(cmd) state = state.prevState",
"chr(32) self.map[agtfrom] = boxkey self.map[agtto] = agt # print(\"Agent \" + agt +",
"not exist\") return None if boxfrom is None: # # # print(\"Box\", boxkey,",
"reference to previous state self.actionPerformed = None # gets defined when action is",
"= set() def deleteAgent(self, external_key): \"\"\"Delete from `agents`, the `map` and `agent_color`.\"\"\" pos",
"boxdir, i) if actionParams is not None: return self.__PushEffect(*actionParams) else: return None def",
"new and applies the concurrent changes to all children. \"\"\" children = []",
"not in hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos else: return None",
"(agt, boxkey, agtfrom, agtto, boxfrom, i) else: # # # print(\"Pos \" +",
"def __WaitPrec_t(self, t): if t in self.concurrent: joint_concurrent = self.concurrent[t] # a state",
"= parent.agentColor # rigid # TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes =",
"\"does not exist\") return None if agtdir not in self.dir: # # #",
"is explored return self.minimalRep() in self.explored def __addToExplored(self, children): # adds the state",
"self.actionPerformed = None self.g = 0 self.t = 0 self.h = None self.f",
"for the next time `self.t`. This ensures that agents just wait if the",
"\"\"\"Advance in time until the environment is changed by other agent.\"\"\" next_time =",
"super().__init__(parent) self.concurrent = concurrent if concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition",
"# Explores unexplroed states and returns a list of children children = []",
"self.Free(agtto): return (agt, boxkey, agtfrom, agtto, boxfrom, i) else: # # # print(\"Pos",
"Loop iterales through every possible action for direction in self.dir: for agtkey in",
"of the states return str([self.agents, self.boxes]) def isExplored(self): # returns true if the",
"boxkey, boxdir, i) if actionParams is not None: return self.__PullEffect(*actionParams) else: return None",
"cmd = f\"Move({parm1})\" elif cmd == \"NoOp\": cmd = \"NoOp\" path.append(cmd) state =",
"children = [] # Loop iterales through every possible action for direction in",
"self.goals: self.goals[key] = [[pos, color]] else: self.goals[key].append([pos, color]) def addBox(self, key, pos, color=\"c\"):",
"table that contains times where an object (box) in the environment has been",
"return None if self.Neighbour(agtfrom, boxfrom) != 1: # # # print(\"agent\", agt, \"and",
"a letter key = key.lower() if key not in self.goals: self.goals[key] = [[pos,",
"minimal representation of the states return str([self.agents, self.boxes]) def isExplored(self): # returns true",
"Checks a Push action if it is possible it is appended to the",
"nodes.\"\"\" self.explored = set() def deleteAgent(self, external_key): \"\"\"Delete from `agents`, the `map` and",
"TODO reformat these nested loops and if statements! # This can be perhaps",
"= self.getPos(self.agents, agt) if agtfrom is None: # # # print(\"agent\", agt, \"does",
"direction, it checks the precondition and does the movemnt actionParams = self.__MovePrec(agt, agtdir)",
"self.concurrent[t] for obj_key in joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group = \"agents\" if",
"external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for external_agent in",
"else: return None def setPos(self, objtype, obj, pos, i=0): # sets the position",
"agent: {t: {box: [(row, col), index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent = concurrent",
"explore(self): \"\"\"Explore with 'NoOp's. The Preconditions to a NoOp is that the environment",
"keys: goals = self.getGoalsByKey(key) for pos, color in goals: if self.map[pos] != key.upper():",
"index (if multiple)) # returns None if not in hashtable if obj in",
"now at \" + str(agtfrom) + \" (row,col)\") return True def Pull(self, agt,",
"Shared table that contains times where an object (box) in the environment has",
"key not in self.goals: # return None return self.goals[key] def getGoalKeys(self): # returns",
"None if not in hashtable if obj in objtype: return objtype[obj][i][0] else: return",
"a list of children children = [] # Loop iterales through every possible",
"NoOp is that the environment was changed by another agent; i.e., there is",
"= {} # hashtable self.prevState = None self.actionPerformed = None self.g = 0",
"advance(self) -> StateInit: \"\"\"Advance in time until the environment is changed by other",
"until the environment is changed by other agent.\"\"\" next_time = self.AdvancePrec() if not",
"concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent can stay",
"= parent.explored super().__init__() def addMap(self, map2): # initialized a map with only walls",
"+ \" (row,col)\") # print(\"Box \" + str(box) + \" is now at",
"actionParams = self.__PushPrec(agtkey, boxkey, direction, i) if actionParams is not None: child =",
"same as getPos, just for all Boxes with the given key # if",
"the keys return list(self.goals.keys()) def getAgentKeys(self): # returns all the keys return list(self.agents.keys())",
"`self.concurrent` for the next time `self.t`. This ensures that agents just wait if",
"child = StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend",
"in self.goals: # return None return self.goals[key] def getGoalKeys(self): # returns all the",
"= self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values(): if pos is None: continue",
"if actionParams is not None: return self.__PullEffect(*actionParams) else: return None def minimalRep(self): #",
"not free\") return None def __MoveEffect(self, agt, agtfrom, agtto): # Moves the object",
"checks the precondition and does the movemnt actionParams = self.__MovePrec(agt, agtdir) if actionParams",
"+ \" is now at \" + str(agtto) + \" (row,col)\") # print(\"Box",
"called by by strategy. \"\"\" future = [t for t in self.concurrent if",
"# same as getPos, just for all agents with the given key return",
"self.agentColor[color][to_del] def deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] = \"",
"agtdir) if actionParams is not None: return self.__MoveEffect(*actionParams) else: return None def __PushPrec(self,",
"not None: self.map[pos[0], pos[1]] = obj_key else: # agents don't leave ghosts behind",
"there is an entry in `self.concurrent` for the next time `self.t`. This ensures",
"boxto, i) else: # # # print(\"Pos \" + str(boxto) + \" (row,col)",
"\"E\": (0, 1), \"S\": (1, 0), \"W\": (0, -1)} self.deltaPos = { (-1,",
"actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children)",
"child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move",
"self.getGoalsByKey(key) for pos, color in goals: if self.map[pos] != key.upper(): return False return",
"col), index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent = concurrent if concurrent else parent.concurrent",
"[ state.t, state.getPos(getattr(state, obj_group), looking_for, index), ] ) state = state.prevState else: #",
"state.h state = state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): # simply adds two positions",
"tiles of the agent for boxkey in child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor",
"not None: return self.__PushEffect(*actionParams) else: return None def __PullPrec(self, agt, boxkey, agtdir, i=0):",
"applies the concurrent changes to all children. \"\"\" children = [] # Loop",
"these nested loops and if statements! # This can be perhaps be optimized",
"obj_key] = \"Ñ\" self.map[pos[0], pos[1]] = obj_key return True def hunt_ghost(self): \"\"\"Remove ghosted",
"to a hashtable # key is a letter key = key.lower() if key",
"for all agents with the given key return self.agentColor[color] def getBoxesByKey(self, key): key",
"to the map and to a hashtable # key is the agent number",
"direction, i ) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed =",
"for i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent number (0 since",
"is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return",
"+ str(box) + \" is now at \" + str(agtfrom) + \" (row,col)\")",
"+ \" (row,col)\") return True def Pull(self, agt, boxkey, boxdir, i): # moves",
"\"are not neighbors\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt,",
"chosen self.g = parent.g + 1 self.h = None self.f = None self.t",
"state path = [] state = copy.deepcopy(self) if format == 1: # format",
"return None return self.agents[key] def getAgentsByColor(self, color): # same as getPos, just for",
"deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] = \" \" def",
"__MovePrec(self, agt, agtdir): # returns the movement parameters if the preconditions are met",
"\" + str(agtto) + \" (row,col) is not free\") return None def __PullEffect(self,",
"# Loop iterales through every possible action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): #",
"direction, it checks the precondition and does the movemnt actionParams = self.__PullPrec(agt, boxkey,",
") cmd = f\"Move({parm1})\" elif cmd == \"NoOp\": cmd = \"NoOp\" path.append(cmd) state",
"all Boxes with the given key # if key not in self.boxes: #",
"will be removed on child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos is",
"boxkey, agtfrom, boxfrom, boxto, i) else: # # # print(\"Pos \" + str(boxto)",
"\" (row,col)\") # print(\"Box \" + str(box) + \" is now at \"",
"key not in self.agents: # return None return self.agents[key] def getAgentsByColor(self, color): #",
"\"Ñ\" if pos is not None: self.map[pos[0], pos[1]] = obj_key else: # agents",
"# returns None if not in hashtable if obj in objtype: return objtype[obj][i][0]",
"if boxfrom is None: # # # print(\"Box\", boxkey, \"does not exist\") return",
"obj_group = \"agents\" if obj_key.isnumeric() else \"boxes\" if obj_group == \"boxes\": prev_pos =",
"if cmd == \"Push\": # (agtfrom, boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3]",
"= np.array(map2) def addAgent(self, key, pos, color=\"c\"): # Adds an agent to the",
"does the movemnt actionParams = self.__MovePrec(agt, agtdir) if actionParams is not None: return",
"in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is",
"not check preconditions self.setPos(self.agents, agt, agtto, 0) # agents are unique thus 0",
"\" is now at \" + str(boxfrom) + \" (row,col)\") return True def",
"# rigid self.deltaPos = parent.deltaPos # rigid self.goals = parent.goals # rigid self.agentColor",
"boxes = list(self.boxes.keys()) for external_agent in boxes: if external_agent != external_key: self.deleteBox(external_agent) def",
"self.explored = set() else: # if a parent is present! self.dir = parent.dir",
"self.getGoalKeys() for key in keys: goals = self.getGoalsByKey(key) for pos, color in goals:",
"None def __PullPrec(self, agt, boxkey, agtdir, i=0): # Moves the object with the",
"an object looking_for = format obj_group = \"agents\" if format.isnumeric() else \"boxes\" while",
"children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction, i ) if actionParams is not",
"return None if boxfrom is None: # # # print(\"Box\", boxkey, \"does not",
"self.getPos(self.agents, agt) if agtfrom is None: # # # print(\"agent\", agt, \"does not",
"return self.goals[key] def getGoalKeys(self): # returns all the keys return list(self.goals.keys()) def getAgentKeys(self):",
"agent for boxkey in self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] #",
"# # # print(\"agent\", agt, \"does not exist\") return None if agtdir not",
"for concurrent changes of the world. Something has changed given a concurrent action",
"== pos[0] and agent_pos[1] == pos[1]: return False return True def __ConcurrentPrec(self): \"\"\"Evaluate",
"= parent.t + 1 self.explored = parent.explored super().__init__() def addMap(self, map2): # initialized",
"if key not in self.agents: # return None return self.agents[key] def getAgentsByColor(self, color):",
"agent for boxkey in child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] #",
"agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey self.map[agtto] = agt # print(\"Agent",
"i ) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\",",
"if child_def.__ConcurrentPrec(): # apply concurrent effects to all children but also append #",
"return True def Push(self, agt, boxkey, boxdir, i): # moves the objects in",
"\"does not exist\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt,",
"# a state that it is being solved is guaranteed to have only",
"deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState = parent",
"parameters # Does not check preconditions agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes,",
"avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState =",
"\"\\n\".join([\"\".join(line) for line in self.map]) + f\" t={self.t}\" class StateInit(Literals): def __init__(self, parent:",
"the objects in the given direction, it checks the precondition and does the",
"and color is the color of the agent self.map[pos] = key self.agents[key] =",
"agtto): # Moves the object with the given parameters # Does not check",
"true if the state is explored return self.minimalRep() in self.explored def __addToExplored(self, children):",
"i): # Moves the objects with the given parameters # Does not check",
"type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos else: return None def Free(self, pos): #",
"\" + agt + \" is now at \" + str(boxto) + \"",
"updateParentCost(self, total_cost): state = self.prevState i = 0 while state is not None:",
"future_self = self while next_time > future_self.t: println(future_self) future_self = StateConcurrent(future_self) future_self.actionPerformed =",
"explore(self): # Explores unexplroed states and returns a list of children children =",
"= None self.explored = set() else: # if a parent is present! self.dir",
"= self.prevState i = 0 while state is not None: i += 1",
"else \"boxes\" if obj_group == \"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self,",
"1: return True else: return False def __str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line)",
"noop function child = StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return children class",
") cmd = f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2]",
"child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent",
"parent: \"Literals\" = None): # initializes the state # it is (row, column)",
"+ str(boxfrom) + \" (row,col)\") return True def Push(self, agt, boxkey, boxdir, i):",
"import println class Literals: def __init__(self, parent: \"Literals\" = None): # initializes the",
"the movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir, i) if actionParams is not None:",
"met # otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes,",
"== \"Ñ\"] = \" \" def explore(self): \"\"\"Explore with 'NoOp's. The Preconditions to",
"all Goal with the given key # if key not in self.goals: #",
"boxkey in child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent",
"children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction, i ) if actionParams is not",
"state.prevState else: # format used by server while state.actionPerformed is not None: #",
"pos2[0]) + abs(pos1[1] - pos2[1]) == 1: return True else: return False def",
"\"\"\"Extend StateInit with concurrent literals.\"\"\" def __init__(self, parent: StateInit = None, concurrent: Dict",
"# hashtable self.agents = {} # hashtable self.boxes = {} # hashtable self.prevState",
"return None def __PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto, i): # Moves the",
"concurrent actions at time `t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key in joint_concurrent: pos,",
"return False def advance(self) -> StateInit: \"\"\"Advance in time until the environment is",
"self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey self.map[agtto] = agt",
"if not in hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos else: return",
"self.agents: # TODO make a noop function child = StateInit(self) child.actionPerformed = [\"NoOp\",",
"obj_key.isnumeric() else \"boxes\" if obj_group == \"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key, index)",
"# key is a letter key = key.lower() if key not in self.goals:",
"key): key = key.upper() # same as getPos, just for all Boxes with",
"# # print(\"Pos \" + str(boxto) + \" (row,col) is not free\") return",
"two positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto): # returns",
"object in the given direction, it checks the precondition and does the movemnt",
"the agent moved dir = (agtto[0] - agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir]",
"the order return path[::-1] def explore(self): # Explores unexplroed states and returns a",
"agtfrom, boxfrom, boxto, i): # Moves the objects with the given parameters #",
"def bestPath(self, format=0, index=0): # function returns the list of actions used to",
"environment according to concurrent actions at time `t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key",
"state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": # (agtfrom, agtto, boxfrom)",
"parent.explored super().__init__() def addMap(self, map2): # initialized a map with only walls self.map",
"# # print(\"agent\", agt, \"does not exist\") return None if agtdir not in",
"def AdvancePrec(self): \"\"\"Is there some concurrent change in the future. It will be",
") if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams]",
"key not in self.boxes: self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self):",
"agtdir, i=0): # Moves the object with the given parameters # Does not",
"None self.explored = set() else: # if a parent is present! self.dir =",
"only walls self.map = np.array(map2) def addAgent(self, key, pos, color=\"c\"): # Adds an",
"!= key.upper(): return False return True def bestPath(self, format=0, index=0): # function returns",
"children but also append # a NoOp children which just waits for the",
"= f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd",
"\"\"\"Delete from `agents`, the `map` and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del self.agents[external_key]",
"concurrent literals.\"\"\" def __init__(self, parent: StateInit = None, concurrent: Dict = None): \"\"\"Initialize",
"# returns None if not in hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] =",
"objects in the given direction, it checks the precondition and does the movemnt",
"order return path[::-1] def explore(self): # Explores unexplroed states and returns a list",
"an object # setPos(objecttype, the key, position, the index (if multiple)) # returns",
"def addAgent(self, key, pos, color=\"c\"): # Adds an agent to the map and",
"self.setPos(self.agents, agt, agtto, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, agtfrom,",
"in objtype: return objtype[obj][i][0] else: return None def setPos(self, objtype, obj, pos, i=0):",
"state self.actionPerformed = None # gets defined when action is chosen self.g =",
"Something has changed given a concurrent action by another agent. \"\"\" return self.t",
"StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents: # TODO",
"key in keys: goals = self.getGoalsByKey(key) for pos, color in goals: if self.map[pos]",
"elif cmd == \"NoOp\": cmd = \"NoOp\" path.append(cmd) state = state.prevState # Reverse",
"don't leave ghosts behind and are not in the StateInit self.map[self.map == obj_key]",
"__init__(self, parent: \"Literals\" = None): # initializes the state # it is (row,",
"environment is changed by other agent.\"\"\" next_time = self.AdvancePrec() if not next_time: return",
"numpy as np from utils import println class Literals: def __init__(self, parent: \"Literals\"",
"objects with the given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto,",
"an agent to the map and to a hashtable # key is the",
"- pos2[1]) == 1: return True else: return False def __str__(self): # Debugging",
"can be perhaps be optimized by only looking at boxes at # the",
"action for direction in self.dir: for agtkey in self.agents: # TODO reformat these",
"self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\"",
"the env to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def)",
"obj_group = \"agents\" if format.isnumeric() else \"boxes\" while state.actionPerformed is not None: path.append(",
"self.map[pos] = key self.agents[key] = [[pos, color]] # This is only used to",
"in self.agents: # TODO reformat these nested loops and if statements! # This",
"StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push action if",
"else: return None def __PullPrec(self, agt, boxkey, agtdir, i=0): # Moves the object",
"self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1 =",
"are met # otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) if agtfrom",
"state = state.prevState else: # format used by server while state.actionPerformed is not",
"class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\" def __init__(self, parent: StateInit = None,",
"= copy.deepcopy(self) if format == 1: # format used by actions while state.actionPerformed",
"= self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": #",
"Neighbour(self, pos1, pos2): # Returns true if the 2 positions are neighbours, otherwise",
"= self.__PushPrec(agt, boxkey, boxdir, i) if actionParams is not None: return self.__PushEffect(*actionParams) else:",
"= copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move action",
"pos, color=None): # Adds a goal to a hashtable # key is a",
"key if key not in self.boxes: self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos, color])",
"# print(\"Agent \" + agt + \" is now at \" + str(boxto)",
"return self.__MoveEffect(*actionParams) else: return None def __PushPrec(self, agt, boxkey, boxdir, i=0): # returns",
"is (row, column) and not (x, y) super().__init__(parent) def getAgentsByKey(self, key): # same",
"agtto) else: # # # print(\"Pos \" + str(agtto) + \" (row,col) is",
"isExplored(self): # returns true if the state is explored return self.minimalRep() in self.explored",
"__getDir(self, agtfrom, agtto): # returns the direction the agent moved dir = (agtto[0]",
"for boxkey in child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent",
"else: # # # print(\"Pos \" + str(boxto) + \" (row,col) is not",
"(0, 1): \"E\", (1, 0): \"S\", (0, -1): \"W\", } self.goals = {}",
"{} # hashtable self.agentColor = {} # hashtable self.agents = {} # hashtable",
"to a hashtable # key is the agent number and color is the",
"getAgentKeys(self): # returns all the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state =",
"Agent can stay at his position without doing anything. \"\"\" return self.__WaitPrec_t(self.t) and",
"return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto): # returns the direction the",
"purposes return \"\\n\".join([\"\".join(line) for line in self.map]) + f\" t={self.t}\" class StateInit(Literals): def",
"else: return None def Free(self, pos): # checks if position in map is",
"in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key): pos = self.getPos(self.boxes,",
"return True def Pull(self, agt, boxkey, boxdir, i): # moves the objects in",
"{} # hashtable self.agents = {} # hashtable self.boxes = {} # hashtable",
"map2): # initialized a map with only walls self.map = np.array(map2) def addAgent(self,",
"Does not check preconditions self.setPos(self.agents, agt, boxfrom, 0) # agents are unique thus",
"1 state.h = total_cost + i state.f = state.g + state.h state =",
"for all Boxes with the given key # if key not in self.boxes:",
"goals: if self.map[pos] != key.upper(): return False return True def bestPath(self, format=0, index=0):",
"return list(self.goals.keys()) def getAgentKeys(self): # returns all the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self,",
"None): \"\"\"Initialize by adding a time table to the usual `StateInit`. Parameters ----------",
"not in self.dir: # # # print(\"Direction\", boxdir, \"does not exist\") return None",
"= StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent effects to all children but also",
"in the future. It will be called by by strategy. \"\"\" future =",
"def __init__(self, parent: \"Literals\" = None): # initializes the state # it is",
"# Does not check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto] =",
"a NoOp children which just waits for the env to change # println(\"Applying",
"\" \" def deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys())",
"a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] = \" \" def explore(self): \"\"\"Explore with",
"it checks the precondition and does the movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir,",
"appended to the the children actionParams = self.__MovePrec(agtkey, direction) if actionParams is not",
"Adds a box to the map and to a hashtable # key is",
"color is the color of the agent self.map[pos] = key self.agents[key] = [[pos,",
"Checks a pull action if it is possible it is appended to the",
"# TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy()",
"def addMap(self, map2): # initialized a map with only walls self.map = np.array(map2)",
"looking_for, index), ] ) state = state.prevState else: # format used by server",
"direction, i) if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Push\",",
"None: child = StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey,",
"guaranteed to have only one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _",
"action if it is possible it is appended to the the children actionParams",
"+ abs(pos1[1] - pos2[1]) == 1: return True else: return False def __str__(self):",
"# if key not in self.boxes: # return None return self.boxes[key] def getGoalsByKey(self,",
"trace back an object looking_for = format obj_group = \"agents\" if format.isnumeric() else",
"is not None: child = StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams",
"neighbors\") return None boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt, boxkey, agtfrom,",
"else: self.agentColor[color].append(key) def addGoal(self, key, pos, color=None): # Adds a goal to a",
"# return None return self.goals[key] def getGoalKeys(self): # returns all the keys return",
"boxfrom, boxto, i): # Moves the objects with the given parameters # Does",
"agt, \"and box\", boxkey, \"are not neighbors\") return None agtto = self.__addPos(agtfrom, agtdir)",
"forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored = set() def deleteAgent(self, external_key): \"\"\"Delete from `agents`,",
"can be perhaps be optimized by only looking at boxes at the #",
"else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored = set() def deleteAgent(self,",
"+ \" is now at \" + str(agtto) + \" (row,col)\") return True",
"- pos2[0]) + abs(pos1[1] - pos2[1]) == 1: return True else: return False",
"in the given direction, it checks the precondition and does the movemnt actionParams",
"agt, boxfrom, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, boxto, i)",
"state is not None: i += 1 state.h = total_cost + i state.f",
"of the world. Something has changed given a concurrent action by another agent.",
"the environment was changed by another agent; i.e., there is an entry in",
"change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\",",
"if self.Free(agtto): return (agt, agtfrom, agtto) else: # # # print(\"Pos \" +",
"print(\"Agent \" + agt + \" is now at \" + str(agtto) +",
"states return str([self.agents, self.boxes]) def isExplored(self): # returns true if the state is",
"None def __PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom, i): # Moves the objects",
"path.append(cmd) state = state.prevState # Reverse the order return path[::-1] def explore(self): #",
"boxkey, boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom] = agt self.map[boxto] = boxkey #",
"+ \" is now at \" + str(agtfrom) + \" (row,col)\") return True",
"if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams)",
"every possible action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent effects to",
"returns 0 agtfrom = self.getPos(self.agents, agt) if agtfrom is None: # # #",
"else: return None def __PushPrec(self, agt, boxkey, boxdir, i=0): # returns the movement",
"the precondition and does the movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir, i) if",
"agtto, boxfrom, i) else: # # # print(\"Pos \" + str(agtto) + \"",
"the object with the given parameters # Does not check preconditions agtfrom =",
"= self.AdvancePrec() if not next_time: return self future_self = self while next_time >",
"unique)][color] if self.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it is",
"while next_time > future_self.t: println(future_self) future_self = StateConcurrent(future_self) future_self.actionPerformed = [\"NoOp\", None] return",
"Adds a goal to a hashtable # key is a letter key =",
"is a letter key = key.lower() if key not in self.goals: self.goals[key] =",
"agt, agtdir): # returns the movement parameters if the preconditions are met #",
"it is appended to the the children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction,",
"key not in self.boxes: # return None return self.boxes[key] def getGoalsByKey(self, key): key",
"...} \"\"\" super().__init__(parent) self.concurrent = concurrent if concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self):",
"if external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for external_agent",
"self.agentColor = {} # hashtable self.agents = {} # hashtable self.boxes = {}",
"# Does not check preconditions self.setPos(self.agents, agt, boxfrom, 0) # agents are unique",
"def Push(self, agt, boxkey, boxdir, i): # moves the objects in the given",
"loops and if statements! # This can be perhaps be optimized by only",
"with the given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto, 0)",
"agt, agtto, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, agtfrom, i)",
"state.prevState # Reverse the order return path[::-1] def explore(self): # Explores unexplroed states",
"str(agtto) + \" (row,col)\") # print(\"Box \" + str(box) + \" is now",
"\" def explore(self): \"\"\"Explore with 'NoOp's. The Preconditions to a NoOp is that",
"self.dir[agtdir])) def __getDir(self, agtfrom, agtto): # returns the direction the agent moved dir",
"StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction, i)",
"key is the agent number and color is the color of the agent",
"self.map[pos] = key if key not in self.boxes: self.boxes[key] = [[pos, color]] else:",
"in child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent number",
"the given direction, it checks the precondition and does the movemnt actionParams =",
"is None: # # # print(\"Box\", boxkey, \"does not exist\") return None if",
"the given key # if key not in self.boxes: # return None return",
"boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom, boxto, i)",
"# hashtable self.agentColor = {} # hashtable self.agents = {} # hashtable self.boxes",
"the index (if multiple)) # returns None if not in hashtable if type(objtype[obj][i][0])",
"f\" t={self.t}\" class StateInit(Literals): def __init__(self, parent: \"Literals\" = None): # initializes the",
"None if agtdir not in self.dir: # # # print(\"Direction\", agtdir, \"does not",
"introduce a ghost box which will be removed on child nodes self.map[prev_pos[0], prev_pos[1]]",
"in the environment has been changed by another agent: {t: {box: [(row, col),",
"= \"NoOp\" path.append(cmd) state = state.prevState # Reverse the order return path[::-1] def",
"# simply adds two positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom,",
"changed by other agent.\"\"\" next_time = self.AdvancePrec() if not next_time: return self future_self",
"+ state.h state = state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): # simply adds two",
"self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for external_agent in boxes: if external_agent",
"[\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents: # TODO make a noop",
"# neighboring tiles of the agent for boxkey in self.boxes: for i in",
"parent is None: # if no parent is present! self.dir = {\"N\": (-1,",
"concurrent changes of the world. Something has changed given a concurrent action by",
"with the given parameters # Does not check preconditions agtfrom = self.getPos(self.agents, agt)",
"now at \" + str(boxto) + \" (row,col)\") # print(\"Box \" + str(box)",
"looking_for = format obj_group = \"agents\" if format.isnumeric() else \"boxes\" while state.actionPerformed is",
"This ensures that agents just wait if the next state is new and",
"next_time: return self future_self = self while next_time > future_self.t: println(future_self) future_self =",
"explored return self.minimalRep() in self.explored def __addToExplored(self, children): # adds the state to",
"is now at \" + str(agtto) + \" (row,col)\") # print(\"Box \" +",
"map with only walls self.map = np.array(map2) def addAgent(self, key, pos, color=\"c\"): #",
"0): \"N\", (0, 1): \"E\", (1, 0): \"S\", (0, -1): \"W\", } self.goals",
"# it is (row, column) and not (x, y) super().__init__(parent) def getAgentsByKey(self, key):",
"i.e., there is an entry in `self.concurrent` for the next time `self.t`. This",
"if self.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it is possible",
"agents with the given key # if key not in self.agents: # return",
"self.agentColor[color] def getBoxesByKey(self, key): key = key.upper() # same as getPos, just for",
"in self.goals: self.goals[key] = [[pos, color]] else: self.goals[key].append([pos, color]) def addBox(self, key, pos,",
"cmd = f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] )",
"environment was changed by another agent; i.e., there is an entry in `self.concurrent`",
"key): key = key.lower() # same as getPos, just for all Goal with",
"goal to a hashtable # key is a letter key = key.lower() if",
"boxkey, \"does not exist\") return None if boxdir not in self.dir: # #",
"to the the children actionParams = self.__PullPrec(agtkey, boxkey, direction, i) if actionParams is",
"StateInit self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0], pos[1]] = obj_key return True def",
"another agent; i.e., there is an entry in `self.concurrent` for the next time",
"== pos[1]: return False return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes",
"an object (box) in the environment has been changed by another agent: {t:",
"if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams)",
"if not next_time: return self future_self = self while next_time > future_self.t: println(future_self)",
"{ (-1, 0): \"N\", (0, 1): \"E\", (1, 0): \"S\", (0, -1): \"W\",",
"given key # if key not in self.agents: # return None return self.agents[key]",
"ext_goals = list(self.goals.keys()) for external_goal in ext_goals: if external_goal != external_key: self.deleteGoal(external_goal) def",
"schemas for the muli-PDDL framework.\"\"\" import copy import operator from typing import Dict",
"a hashtable # key is a letter key = key.lower() if key not",
"an object getPos(objecttype, the key, the index (if multiple)) # returns None if",
"for external_agent in ext_agents: if external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals",
"if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams)",
"self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos]",
"states and returns a list of children children = [] # Loop iterales",
"preconditions self.setPos(self.agents, agt, agtto, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey,",
"for external_goal in ext_goals: if external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes",
"in self.agents: # TODO make a noop function child = StateInit(self) child.actionPerformed =",
"color in goals: if self.map[pos] != key.upper(): return False return True def bestPath(self,",
"boxfrom) != 1: # # # print(\"agent\", agt, \"and box\", boxkey, \"are not",
"self.dir = parent.dir # rigid self.deltaPos = parent.deltaPos # rigid self.goals = parent.goals",
"movemnt actionParams = self.__MovePrec(agt, agtdir) if actionParams is not None: return self.__MoveEffect(*actionParams) else:",
"setPos(objecttype, the key, position, the index (if multiple)) # returns None if not",
"cmd = f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": # (agtfrom, agtto, boxfrom) parm1 =",
"there some concurrent change in the future. It will be called by by",
"state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1],",
"self.__MovePrec(agtkey, direction) if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Move\",",
"chr(32) self.map[agtto] = agt # print(\"Agent \" + agt + \" is now",
"\" + str(boxfrom) + \" (row,col)\") return True def Push(self, agt, boxkey, boxdir,",
"agent to the map and to a hashtable # key is the agent",
"neighboring tiles of the agent for boxkey in child_def.boxes: for i in range(len(child_def.boxes[boxkey])):",
"moved dir = (agtto[0] - agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self,",
"0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey self.map[agtto] =",
"if obj_group == \"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key,",
"def __addToExplored(self, children): # adds the state to the explored list if not",
"# format used by server while state.actionPerformed is not None: # print(state.actionPerformed, state.actionPerformed[0])",
"state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif",
"to a NoOp is that the environment was changed by another agent; i.e.,",
"is the agent number and color is the color of the agent self.map[pos]",
"i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent number (0 since it",
"is not None: path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for, index), ] ) state",
"obj_group == \"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos,",
"def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes of the world. Something has changed",
"\"does not exist\") return None if boxdir not in self.dir: # # #",
"# # print(\"Box\", boxkey, \"does not exist\") return None if agtdir not in",
"and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] = \" \" for",
"- agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt, agtdir): # returns the movement parameters",
"color if color not in self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key) def addGoal(self,",
"elif cmd == \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\"",
"checks the precondition and does the movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir, i)",
"return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state = self.prevState i = 0 while state",
"self.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color] if self.agents[agtkey][0][1] ==",
"else: # agents don't leave ghosts behind and are not in the StateInit",
"# returns true if the state is explored return self.minimalRep() in self.explored def",
"preconditions are met # otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) if",
"self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for external_goal in ext_goals: if external_goal",
"unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it is",
"!= 1: # # # print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\")",
"the the children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction, i ) if actionParams",
"# rigid self.agentColor = parent.agentColor # rigid # TODO avoid deepcopies self.agents =",
"the states return str([self.agents, self.boxes]) def isExplored(self): # returns true if the state",
"return True else: return False def __str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line) for",
"is not None: i += 1 state.h = total_cost + i state.f =",
"environment has been changed by another agent: {t: {box: [(row, col), index], ...},",
"is appended to the the children # Checks a Move action if it",
"are unique thus 0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom] =",
"column) and not (x, y) super().__init__(parent) def getAgentsByKey(self, key): # same as getPos,",
"neighboring tiles of the agent for boxkey in self.boxes: for i in range(len(self.boxes[boxkey])):",
"to all children but also append # a NoOp children which just waits",
"(-1, 0): \"N\", (0, 1): \"E\", (1, 0): \"S\", (0, -1): \"W\", }",
"agtfrom, agtto): # Moves the object with the given parameters # Does not",
"it is possible it is appended to the the children actionParams = child_def._StateInit__MovePrec(agtkey,",
"= self.__PullPrec(agt, boxkey, boxdir, i) if actionParams is not None: return self.__PullEffect(*actionParams) else:",
"self.boxes[external_key] self.map[pos] = \" \" def deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self, external_key):",
"# # print(\"Pos \" + str(agtto) + \" (row,col) is not free\") return",
"def __PushPrec(self, agt, boxkey, boxdir, i=0): # returns the movement parameters if the",
"stay at his position without doing anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def",
"solved is guaranteed to have only one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for",
"= obj_key return True def hunt_ghost(self): \"\"\"Remove ghosted positions put by a Councurent",
"external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0): # gets the position of an",
"# if no parent is present! self.dir = {\"N\": (-1, 0), \"E\": (0,",
"del self.boxes[external_key] self.map[pos] = \" \" def deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self,",
"doing anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t in",
"agt, boxkey, agtfrom, boxfrom, boxto, i): # Moves the objects with the given",
"__init__(self, parent: \"Literals\" = None): # initializes the literals if parent is None:",
"keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for external_agent in boxes: if external_agent != external_key:",
"0 agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom is",
"= state.actionPerformed[0] if cmd == \"Push\": # (agtfrom, boxfrom, boxto) parm1 = self.__getDir(",
"key, pos, color=\"c\"): # Adds a box to the map and to a",
"pos[1]] = obj_key return True def hunt_ghost(self): \"\"\"Remove ghosted positions put by a",
"__addPos(self, agtfrom, agtdir): # simply adds two positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir]))",
"def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for external_agent in ext_agents: if external_agent !=",
"agt, boxkey, agtdir, i=0): # Moves the object with the given parameters #",
"a parent is present! self.dir = parent.dir # rigid self.deltaPos = parent.deltaPos #",
"positions put by a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] = \" \" def",
"on child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos is not None: self.map[pos[0],",
"= [key] else: self.agentColor[color].append(key) def addGoal(self, key, pos, color=None): # Adds a goal",
"self.map[agtfrom] = chr(32) self.map[agtto] = agt # print(\"Agent \" + agt + \"",
"None): # initializes the state # it is (row, column) and not (x,",
"children): # adds the state to the explored list if not self.isExplored(): self.explored.add(self.minimalRep())",
"[t for t in self.concurrent if t > self.t] if future: return min(future)",
"state.t, state.getPos(getattr(state, obj_group), looking_for, index), ] ) state = state.prevState else: # format",
"all the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state = self.prevState i =",
"# Adds a goal to a hashtable # key is a letter key",
"range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color]",
"state that it is being solved is guaranteed to have only one agent",
"same as getPos, just for all agents with the given key return self.agentColor[color]",
"= parent.goals # rigid self.agentColor = parent.agentColor # rigid # TODO avoid deepcopies",
"children actionParams = self.__MovePrec(agtkey, direction) if actionParams is not None: child = StateInit(self)",
"position of an object getPos(objecttype, the key, the index (if multiple)) # returns",
"\"Pull\": # (agtfrom, agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 =",
"agtkey, boxkey, direction, i ) if actionParams is not None: child = copy.deepcopy(child_def)",
"keys = self.getGoalKeys() for key in keys: goals = self.getGoalsByKey(key) for pos, color",
"parameters # Does not check preconditions self.setPos(self.agents, agt, boxfrom, 0) # agents are",
"only one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values(): if",
"list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric() else \"boxes\" if obj_group == \"boxes\": prev_pos",
"index = list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric() else \"boxes\" if obj_group ==",
"(agtfrom, agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2],",
"def __MovePrec(self, agt, agtdir): # returns the movement parameters if the preconditions are",
"appended to the the children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction, i )",
"given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32)",
"at \" + str(boxto) + \" (row,col)\") # print(\"Box \" + str(box) +",
"getPos, just for all Goal with the given key # if key not",
"child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move action if it",
"not check preconditions agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if",
"in self.map]) + f\" t={self.t}\" class StateInit(Literals): def __init__(self, parent: \"Literals\" = None):",
"if format.isnumeric() else \"boxes\" while state.actionPerformed is not None: path.append( [ state.t, state.getPos(getattr(state,",
"\"\"\"Evaluate precondition for concurrent changes of the world. Something has changed given a",
"agents with the given key return self.agentColor[color] def getBoxesByKey(self, key): key = key.upper()",
"not in hashtable if obj in objtype: return objtype[obj][i][0] else: return None def",
"self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, agtfrom, agtto) else: # # # print(\"Pos",
"= StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend StateInit",
"AdvancePrec(self): \"\"\"Is there some concurrent change in the future. It will be called",
"keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state = self.prevState i = 0 while",
"cmd == \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif",
"boxkey, boxdir, i): # moves the objects in the given direction, it checks",
"key.lower() if key not in self.goals: self.goals[key] = [[pos, color]] else: self.goals[key].append([pos, color])",
"return None def __PullPrec(self, agt, boxkey, agtdir, i=0): # Moves the object with",
"= {} # hashtable self.agents = {} # hashtable self.boxes = {} #",
"parent.dir # rigid self.deltaPos = parent.deltaPos # rigid self.goals = parent.goals # rigid",
"Effect.\"\"\" self.map[self.map == \"Ñ\"] = \" \" def explore(self): \"\"\"Explore with 'NoOp's. The",
"\"\"\"Evaluate precondition for NoOp. Agent can stay at his position without doing anything.",
"__addToExplored(self, children): # adds the state to the explored list if not self.isExplored():",
"be removed on child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos is not",
"agent_pos[0] == pos[0] and agent_pos[1] == pos[1]: return False return True def __ConcurrentPrec(self):",
"None): # initializes the literals if parent is None: # if no parent",
"returns the direction the agent moved dir = (agtto[0] - agtfrom[0], agtto[1] -",
"def __ConcurrentEffect(self, t): \"\"\"Modify environment according to concurrent actions at time `t`.\"\"\" joint_concurrent",
"boxkey, boxdir, i) if actionParams is not None: return self.__PushEffect(*actionParams) else: return None",
"\"and box\", boxkey, \"are not neighbors\") return None agtto = self.__addPos(agtfrom, agtdir) if",
"as getPos, just for all Goal with the given key # if key",
"list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks if the state",
"(0, -1)} self.deltaPos = { (-1, 0): \"N\", (0, 1): \"E\", (1, 0):",
"path = [] state = copy.deepcopy(self) if format == 1: # format used",
"parent.map.copy() self.prevState = parent # reference to previous state self.actionPerformed = None #",
"\"\"\"Explore with 'NoOp's. The Preconditions to a NoOp is that the environment was",
"= self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif cmd == \"NoOp\": cmd",
"where an object (box) in the environment has been changed by another agent:",
"# agents are unique thus 0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] = chr(32)",
"list(self.goals.keys()) def getAgentKeys(self): # returns all the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost):",
"\"Ñ\"] = \" \" def explore(self): \"\"\"Explore with 'NoOp's. The Preconditions to a",
"# # print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return None agtto",
"agtdir) if self.Free(agtto): return (agt, boxkey, agtfrom, agtto, boxfrom, i) else: # #",
"= StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push action",
"if agtdir not in self.dir: # # # print(\"Direction\", agtdir, \"does not exist\")",
"+ str(boxto) + \" (row,col)\") # print(\"Box \" + str(box) + \" is",
"if not in hashtable if obj in objtype: return objtype[obj][i][0] else: return None",
"concurrent if concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent",
"getPos(self, objtype, obj, i=0): # gets the position of an object getPos(objecttype, the",
"for all Goal with the given key # if key not in self.goals:",
"boxto, i): # Moves the objects with the given parameters # Does not",
"[] # Loop iterales through every possible action for direction in self.dir: for",
"the children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction, i ) if actionParams is",
"\"Literals\" = None): # initializes the literals if parent is None: # if",
"is appended to the the children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction, i",
"Moves the objects with the given parameters # Does not check preconditions self.setPos(self.agents,",
"{} # hashtable self.boxes = {} # hashtable self.prevState = None self.actionPerformed =",
"self.t = parent.t + 1 self.explored = parent.explored super().__init__() def addMap(self, map2): #",
"= (agtto[0] - agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt, agtdir):",
"= [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction, i) if actionParams",
"be optimized by only looking at boxes at # the neighboring tiles of",
"None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, boxkey, agtfrom, agtto, boxfrom,",
"copy import operator from typing import Dict import numpy as np from utils",
"`agents`, the `map` and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] =",
"can stay at his position without doing anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1)",
"at his position without doing anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self,",
"previous state self.actionPerformed = None # gets defined when action is chosen self.g",
"the key, position, the index (if multiple)) # returns None if not in",
"# # print(\"Direction\", agtdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) !=",
"self.__PullPrec(agtkey, boxkey, direction, i) if actionParams is not None: child = StateInit(self) child.actionPerformed",
"= copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for direction in self.dir: for agtkey",
"key # if key not in self.agents: # return None return self.agents[key] def",
"at the # neighboring tiles of the agent for boxkey in self.boxes: for",
"is only used to get easy access to agents by color if color",
"None, concurrent: Dict = None): \"\"\"Initialize by adding a time table to the",
"True def Pull(self, agt, boxkey, boxdir, i): # moves the objects in the",
"self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, boxkey, agtfrom, agtto, boxfrom, i) else: #",
"to the the children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not None:",
"f\"Move({parm1})\" elif cmd == \"NoOp\": cmd = \"NoOp\" path.append(cmd) state = state.prevState #",
"= \"agents\" if obj_key.isnumeric() else \"boxes\" if obj_group == \"boxes\": prev_pos = self.getPos(getattr(self,",
"def explore(self): # Explores unexplroed states and returns a list of children children",
"pos, color=\"c\"): # Adds a box to the map and to a hashtable",
"by a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] = \" \" def explore(self): \"\"\"Explore",
"removed on child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos is not None:",
"__init__(self, parent: StateInit = None, concurrent: Dict = None): \"\"\"Initialize by adding a",
"# println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None]",
"child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push action if it is possible it is",
"tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto): # returns the direction the agent",
"is an entry in `self.concurrent` for the next time `self.t`. This ensures that",
"box to the map and to a hashtable # key is a letter",
"= parent # reference to previous state self.actionPerformed = None # gets defined",
"tiles of the agent for boxkey in self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor",
"parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent can stay at his",
"[\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction, i) if actionParams is",
"concurrent change in the future. It will be called by by strategy. \"\"\"",
"(agtfrom, boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3],",
"self.AdvancePrec() if not next_time: return self future_self = self while next_time > future_self.t:",
"agent. \"\"\" return self.t in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment according to",
"child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push action if it is possible it is",
"def getAgentsByKey(self, key): # same as getPos, just for all agents with the",
"# # # print(\"Direction\", boxdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom)",
"= list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric() else \"boxes\" if obj_group == \"boxes\":",
"children actionParams = self.__PullPrec(agtkey, boxkey, direction, i) if actionParams is not None: child",
"the movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir, i) if actionParams is not None:",
"0 self.t = 0 self.h = None self.f = None self.explored = set()",
"def __MoveEffect(self, agt, agtfrom, agtto): # Moves the object with the given parameters",
"print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return None agtto = self.__addPos(agtfrom,",
"= \" \" def explore(self): \"\"\"Explore with 'NoOp's. The Preconditions to a NoOp",
"was changed by another agent; i.e., there is an entry in `self.concurrent` for",
"= key.lower() if key not in self.goals: self.goals[key] = [[pos, color]] else: self.goals[key].append([pos,",
"None self.actionPerformed = None self.g = 0 self.t = 0 self.h = None",
"now at \" + str(agtto) + \" (row,col)\") return True def Move(self, agt,",
"in time until the environment is changed by other agent.\"\"\" next_time = self.AdvancePrec()",
"if self.map[pos] != key.upper(): return False return True def bestPath(self, format=0, index=0): #",
"= copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is",
"a time table to the usual `StateInit`. Parameters ---------- parent: StateInit concurrent: Dict",
"boxfrom is None: # # # print(\"Box\", boxkey, \"does not exist\") return None",
"the the children actionParams = self.__PullPrec(agtkey, boxkey, direction, i) if actionParams is not",
"if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams)",
"continue if agent_pos[0] == pos[0] and agent_pos[1] == pos[1]: return False return True",
"= \" \" for color in self.agentColor: if external_key in self.agentColor[color]: to_del =",
"agt self.map[boxto] = boxkey # print(\"Agent \" + agt + \" is now",
"True else: return False def __str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line) for line",
"is appended to the the children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction, i",
"children.append(self) def isGoalState(self): # checks if the state is a goal state keys",
"is not free\") return None def __PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto, i):",
"moves the object in the given direction, it checks the precondition and does",
"the world. Something has changed given a concurrent action by another agent. \"\"\"",
"state.h = total_cost + i state.f = state.g + state.h state = state.prevState\"\"\"",
"i=0): # gets the position of an object getPos(objecttype, the key, the index",
"of an object # setPos(objecttype, the key, position, the index (if multiple)) #",
"<filename>multi_sokoban/actions.py \"\"\"Define literals and actions schemas for the muli-PDDL framework.\"\"\" import copy import",
"return self.agents[key] def getAgentsByColor(self, color): # same as getPos, just for all agents",
"-> StateInit: \"\"\"Advance in time until the environment is changed by other agent.\"\"\"",
"self.goals: # return None return self.goals[key] def getGoalKeys(self): # returns all the keys",
"parent.g + 1 self.h = None self.f = None self.t = parent.t +",
"# same as getPos, just for all agents with the given key #",
"not free\") return None def __PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom, i): #",
"position of an object # setPos(objecttype, the key, position, the index (if multiple))",
"obj_key return True def hunt_ghost(self): \"\"\"Remove ghosted positions put by a Councurent Effect.\"\"\"",
"self.concurrent: joint_concurrent = self.concurrent[t] # a state that it is being solved is",
"is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it",
"# # print(\"agent\", agt, \"does not exist\") return None if boxfrom is None:",
"if t in self.concurrent: joint_concurrent = self.concurrent[t] # a state that it is",
"agent; i.e., there is an entry in `self.concurrent` for the next time `self.t`.",
"boxkey, \"does not exist\") return None if agtdir not in self.dir: # #",
"state keys = self.getGoalKeys() for key in keys: goals = self.getGoalsByKey(key) for pos,",
"at \" + str(agtto) + \" (row,col)\") # print(\"Box \" + str(box) +",
"boxkey, \"are not neighbors\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return",
"format.isnumeric() else \"boxes\" while state.actionPerformed is not None: path.append( [ state.t, state.getPos(getattr(state, obj_group),",
"pos2[1]) == 1: return True else: return False def __str__(self): # Debugging purposes",
"= [t for t in self.concurrent if t > self.t] if future: return",
"if self.map[pos] == chr(32) or self.map[pos].islower(): return True else: return False def Color(self,",
"leave ghosts behind and are not in the StateInit self.map[self.map == obj_key] =",
"print(\"Box \" + str(box) + \" is now at \" + str(agtfrom) +",
"{} # hashtable self.prevState = None self.actionPerformed = None self.g = 0 self.t",
"actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children)",
"it is appended to the the children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams",
"of the agent for boxkey in self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor =",
"It will be called by by strategy. \"\"\" future = [t for t",
"= self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom is None: #",
"state.actionPerformed is not None: path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for, index), ] )",
"= None, concurrent: Dict = None): \"\"\"Initialize by adding a time table to",
"to the the children # Checks a Move action if it is possible",
"by another agent. \"\"\" return self.t in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment",
"state.actionPerformed is not None: path.append(state.actionPerformed) state = state.prevState elif isinstance(format, str): # trace",
"boxfrom, i) else: # # # print(\"Pos \" + str(agtto) + \" (row,col)",
"in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment according to concurrent actions at time",
"pos[1]: return False return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes of",
"is not None: return self.__MoveEffect(*actionParams) else: return None def __PushPrec(self, agt, boxkey, boxdir,",
"return False return True def bestPath(self, format=0, index=0): # function returns the list",
"None boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom, boxto,",
"self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\"",
"if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks if the state is",
"now at \" + str(agtto) + \" (row,col)\") # print(\"Box \" + str(box)",
"if it is free and false otherwise if self.map[pos] == chr(32) or self.map[pos].islower():",
"at \" + str(boxfrom) + \" (row,col)\") return True def Push(self, agt, boxkey,",
"None: # # # print(\"agent\", agt, \"does not exist\") return None if boxfrom",
"self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom, boxto, i) else: # # # print(\"Pos",
"concurrent effects to all children but also append # a NoOp children which",
"agents just wait if the next state is new and applies the concurrent",
"child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is there some concurrent change in the",
"(row,col) is not free\") return None def __MoveEffect(self, agt, agtfrom, agtto): # Moves",
"concurrent: Dict Shared table that contains times where an object (box) in the",
"only looking at boxes at the # neighboring tiles of the agent for",
"else: self.goals[key].append([pos, color]) def addBox(self, key, pos, color=\"c\"): # Adds a box to",
"self.map = np.array(map2) def addAgent(self, key, pos, color=\"c\"): # Adds an agent to",
"actionParams is not None: return self.__PushEffect(*actionParams) else: return None def __PullPrec(self, agt, boxkey,",
"parent # reference to previous state self.actionPerformed = None # gets defined when",
"[\"NoOp\", None] child._StateInit__addToExplored(children) for direction in self.dir: for agtkey in self.agents: # TODO",
"by only looking at boxes at # the neighboring tiles of the agent",
"self.boxes]) def isExplored(self): # returns true if the state is explored return self.minimalRep()",
"of an object getPos(objecttype, the key, the index (if multiple)) # returns None",
"self.prevState = parent # reference to previous state self.actionPerformed = None # gets",
"False def __str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line) for line in self.map]) +",
"otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i)",
"not None: i += 1 state.h = total_cost + i state.f = state.g",
"actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction, i ) if actionParams is not None:",
"# rigid # TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map",
"if color not in self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key) def addGoal(self, key,",
"if key not in self.boxes: self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos, color]) def",
"that agents just wait if the next state is new and applies the",
"a concurrent action by another agent. \"\"\" return self.t in self.concurrent def __ConcurrentEffect(self,",
"is now at \" + str(boxto) + \" (row,col)\") # print(\"Box \" +",
"self.deltaPos[dir] def __MovePrec(self, agt, agtdir): # returns the movement parameters if the preconditions",
"and to a hashtable # key is the agent number and color is",
"actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is there some concurrent change in",
"contains times where an object (box) in the environment has been changed by",
"checks if the state is a goal state keys = self.getGoalKeys() for key",
"return children class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\" def __init__(self, parent: StateInit",
"str(agtfrom) + \" (row,col)\") return True def Pull(self, agt, boxkey, boxdir, i): #",
"just for all agents with the given key return self.agentColor[color] def getBoxesByKey(self, key):",
"0 while state is not None: i += 1 state.h = total_cost +",
"color=None): # Adds a goal to a hashtable # key is a letter",
"movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir, i) if actionParams is not None: return",
"getGoalKeys(self): # returns all the keys return list(self.goals.keys()) def getAgentKeys(self): # returns all",
"if self.Neighbour(agtfrom, boxfrom) != 1: # # # print(\"agent\", agt, \"and box\", boxkey,",
"def explore(self): \"\"\"Explore with 'NoOp's. The Preconditions to a NoOp is that the",
"some concurrent change in the future. It will be called by by strategy.",
"state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": # (agtfrom, agtto,",
"a state that it is being solved is guaranteed to have only one",
"__str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line) for line in self.map]) + f\" t={self.t}\"",
"None if self.Neighbour(agtfrom, boxfrom) != 1: # # # print(\"agent\", agt, \"and box\",",
"def addGoal(self, key, pos, color=None): # Adds a goal to a hashtable #",
"the `map` and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] = \"",
"self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos is not None: self.map[pos[0], pos[1]] = obj_key",
"(x, y) super().__init__(parent) def getAgentsByKey(self, key): # same as getPos, just for all",
"Free(self, pos): # checks if position in map is free # returns true",
"self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom] = agt self.map[boxto] = boxkey",
"explored nodes.\"\"\" self.explored = set() def deleteAgent(self, external_key): \"\"\"Delete from `agents`, the `map`",
"# print(\"Agent \" + agt + \" is now at \" + str(agtto)",
"if key not in self.boxes: # return None return self.boxes[key] def getGoalsByKey(self, key):",
"agt, \"does not exist\") return None if agtdir not in self.dir: # #",
"1): \"E\", (1, 0): \"S\", (0, -1): \"W\", } self.goals = {} #",
"is now at \" + str(boxfrom) + \" (row,col)\") return True def Push(self,",
"= parent.dir # rigid self.deltaPos = parent.deltaPos # rigid self.goals = parent.goals #",
"the future. It will be called by by strategy. \"\"\" future = [t",
"the agent self.map[pos] = key self.agents[key] = [[pos, color]] # This is only",
"also append # a NoOp children which just waits for the env to",
"optimized by only looking at boxes at the # neighboring tiles of the",
"import operator from typing import Dict import numpy as np from utils import",
"None: i += 1 state.h = total_cost + i state.f = state.g +",
"is present! self.dir = {\"N\": (-1, 0), \"E\": (0, 1), \"S\": (1, 0),",
"copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState = parent # reference to",
"adding a time table to the usual `StateInit`. Parameters ---------- parent: StateInit concurrent:",
"unique thus 0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey",
"child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move action if it is possible it is",
"None: # print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd == \"Push\": # (agtfrom,",
"i): # moves the objects in the given direction, it checks the precondition",
"external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for external_agent in boxes: if",
"color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored = set() def",
"all children. \"\"\" children = [] # Loop iterales through every possible action",
"None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def",
"self.__PullPrec(agt, boxkey, boxdir, i) if actionParams is not None: return self.__PullEffect(*actionParams) else: return",
"the given key # if key not in self.goals: # return None return",
"self.boxes: # return None return self.boxes[key] def getGoalsByKey(self, key): key = key.lower() #",
"and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t in self.concurrent: joint_concurrent = self.concurrent[t] #",
"it is appended to the the children actionParams = self.__PullPrec(agtkey, boxkey, direction, i)",
"= \"agents\" if format.isnumeric() else \"boxes\" while state.actionPerformed is not None: path.append( [",
"# introduce a ghost box which will be removed on child nodes self.map[prev_pos[0],",
"0): \"S\", (0, -1): \"W\", } self.goals = {} # hashtable self.agentColor =",
"bestPath(self, format=0, index=0): # function returns the list of actions used to reach",
"+ str(boxto) + \" (row,col) is not free\") return None def __PushEffect(self, agt,",
"and does the movemnt actionParams = self.__MovePrec(agt, agtdir) if actionParams is not None:",
"else: return None def minimalRep(self): # returns the minimal representation of the states",
"None: continue if agent_pos[0] == pos[0] and agent_pos[1] == pos[1]: return False return",
"actionParams = self.__MovePrec(agt, agtdir) if actionParams is not None: return self.__MoveEffect(*actionParams) else: return",
"def __init__(self, parent: StateInit = None, concurrent: Dict = None): \"\"\"Initialize by adding",
"looking at boxes at the # neighboring tiles of the agent for boxkey",
"True def hunt_ghost(self): \"\"\"Remove ghosted positions put by a Councurent Effect.\"\"\" self.map[self.map ==",
"`t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key in joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group",
"it checks the precondition and does the movemnt actionParams = self.__MovePrec(agt, agtdir) if",
"an entry in `self.concurrent` for the next time `self.t`. This ensures that agents",
"i ) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\",",
"Dict = None): \"\"\"Initialize by adding a time table to the usual `StateInit`.",
"changes to all children. \"\"\" children = [] # Loop iterales through every",
"self.__MovePrec(agt, agtdir) if actionParams is not None: return self.__MoveEffect(*actionParams) else: return None def",
"child_def._StateInit__PushPrec( agtkey, boxkey, direction, i ) if actionParams is not None: child =",
"letter][agent number (0 since it is unique)][color] if self.agents[agtkey][0][1] == boxcolor: # Checks",
"= self.getGoalsByKey(key) for pos, color in goals: if self.map[pos] != key.upper(): return False",
"direction, i) if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Pull\",",
"together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto): # returns the direction",
"been changed by another agent: {t: {box: [(row, col), index], ...}, ...} \"\"\"",
"\"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos, index) #",
"\" + str(agtto) + \" (row,col)\") # print(\"Box \" + str(box) + \"",
"hashtable # key is the agent number and color is the color of",
"now at \" + str(boxfrom) + \" (row,col)\") return True def Push(self, agt,",
"getPos, just for all Boxes with the given key # if key not",
"Adds an agent to the map and to a hashtable # key is",
"cmd == \"NoOp\": cmd = \"NoOp\" path.append(cmd) state = state.prevState # Reverse the",
"return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes of the world. Something",
"self.map[boxfrom] = agt self.map[boxto] = boxkey # print(\"Agent \" + agt + \"",
"None: # # # print(\"agent\", agt, \"does not exist\") return None if agtdir",
"given direction, it checks the precondition and does the movemnt actionParams = self.__PushPrec(agt,",
"return self.minimalRep() in self.explored def __addToExplored(self, children): # adds the state to the",
"Does not check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto] = agt",
"\"NoOp\": cmd = \"NoOp\" path.append(cmd) state = state.prevState # Reverse the order return",
"ext_goals: if external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for",
"same as getPos, just for all agents with the given key # if",
"Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] = \" \" def explore(self): \"\"\"Explore with 'NoOp's.",
"agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto): # returns the direction the agent moved",
"This can be perhaps be optimized by only looking at boxes at #",
"agent number and color is the color of the agent self.map[pos] = key",
"preconditions are met # otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) boxfrom",
"obj_group), looking_for, index), ] ) state = state.prevState else: # format used by",
"next state is new and applies the concurrent changes to all children. \"\"\"",
"child._StateInit__addToExplored(children) # Checks a Move action if it is possible it is appended",
"str(box) + \" is now at \" + str(agtfrom) + \" (row,col)\") return",
"def __init__(self, parent: \"Literals\" = None): # initializes the literals if parent is",
"child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents: # TODO make",
"# hashtable self.boxes = {} # hashtable self.prevState = None self.actionPerformed = None",
"\"\"\" children = [] # Loop iterales through every possible action child_def =",
"\"S\": (1, 0), \"W\": (0, -1)} self.deltaPos = { (-1, 0): \"N\", (0,",
"2 positions are neighbours, otherwise false if abs(pos1[0] - pos2[0]) + abs(pos1[1] -",
"# # print(\"Direction\", boxdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) !=",
"self.map[pos] != key.upper(): return False return True def bestPath(self, format=0, index=0): # function",
"as getPos, just for all Boxes with the given key # if key",
"exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1: # # # print(\"agent\", agt,",
"isinstance(format, str): # trace back an object looking_for = format obj_group = \"agents\"",
"box which will be removed on child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if",
"parameters # Does not check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto]",
"def getPos(self, objtype, obj, i=0): # gets the position of an object getPos(objecttype,",
"pos, index = list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric() else \"boxes\" if obj_group",
"key.upper() # same as getPos, just for all Boxes with the given key",
"for i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent number (0 since",
"self.__PullEffect(*actionParams) else: return None def minimalRep(self): # returns the minimal representation of the",
"in map is free # returns true if it is free and false",
"self.t in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment according to concurrent actions at",
"\"does not exist\") return None if boxfrom is None: # # # print(\"Box\",",
"it is unique)][color] if self.agents[agtkey][0][1] == boxcolor: # Checks a pull action if",
"---------- parent: StateInit concurrent: Dict Shared table that contains times where an object",
"= boxkey self.map[agtto] = agt # print(\"Agent \" + agt + \" is",
"perhaps be optimized by only looking at boxes at the # neighboring tiles",
"# hashtable self.prevState = None self.actionPerformed = None self.g = 0 self.t =",
"print(\"Direction\", agtdir, \"does not exist\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto):",
"child = StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey,",
"-1): \"W\", } self.goals = {} # hashtable self.agentColor = {} # hashtable",
"list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state = self.prevState i = 0 while state is",
"for obj_key in joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric()",
"keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for external_goal in ext_goals: if external_goal != external_key:",
"(agtto[0] - agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt, agtdir): #",
"agt, \"and box\", boxkey, \"are not neighbors\") return None boxto = self.__addPos(boxfrom, boxdir)",
"map and to a hashtable # key is a letter key = key.upper()",
"to the map and to a hashtable # key is a letter key",
"# # # print(\"Pos \" + str(boxto) + \" (row,col) is not free\")",
"boxfrom, i): # Moves the objects with the given parameters # Does not",
"self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks if the state is a goal state",
"not in self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key) def addGoal(self, key, pos, color=None):",
"has been changed by another agent: {t: {box: [(row, col), index], ...}, ...}",
"objtype, obj, pos, i=0): # sets the position of an object # setPos(objecttype,",
"# This can be perhaps be optimized by only looking at boxes at",
"boxfrom, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom]",
"(row,col) is not free\") return None def __PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom,",
"possible it is appended to the the children actionParams = self.__PullPrec(agtkey, boxkey, direction,",
"child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for direction in self.dir: for agtkey in self.agents:",
"agents by color if color not in self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key)",
"del self.agentColor[color][to_del] def deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] =",
"return None def minimalRep(self): # returns the minimal representation of the states return",
"# print(\"Pos \" + str(agtto) + \" (row,col) is not free\") return None",
"deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for external_agent in",
"it returns 0 agtfrom = self.getPos(self.agents, agt) if agtfrom is None: # #",
"is free and false otherwise if self.map[pos] == chr(32) or self.map[pos].islower(): return True",
"in self.agents: # return None return self.agents[key] def getAgentsByColor(self, color): # same as",
"in the StateInit self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0], pos[1]] = obj_key return",
"index) # introduce a ghost box which will be removed on child nodes",
"\"Ñ\" self.map[pos[0], pos[1]] = obj_key return True def hunt_ghost(self): \"\"\"Remove ghosted positions put",
"the given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto, 0) #",
"state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif cmd == \"NoOp\": cmd = \"NoOp\"",
"self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent number (0",
"= self.__MovePrec(agtkey, direction) if actionParams is not None: child = StateInit(self) child.actionPerformed =",
"with the given parameters # Does not check preconditions self.setPos(self.agents, agt, boxfrom, 0)",
"return min(future) return False def advance(self) -> StateInit: \"\"\"Advance in time until the",
"Moves the object with the given parameters # Does not check preconditions agtfrom",
"and if statements! # This can be perhaps be optimized by only looking",
"hunt_ghost(self): \"\"\"Remove ghosted positions put by a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] =",
"child._StateInit__addToExplored(children) for direction in self.dir: for agtkey in self.agents: # TODO reformat these",
"have only one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values():",
"getAgentsByKey(self, key): # same as getPos, just for all agents with the given",
"agtfrom = self.getPos(self.agents, agt) if agtfrom is None: # # # print(\"agent\", agt,",
"at \" + str(agtto) + \" (row,col)\") return True def Move(self, agt, agtdir):",
"__NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent can stay at his position without doing",
"external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for external_goal in ext_goals: if",
"= self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos, index) # introduce a",
"copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push action if",
"literals if parent is None: # if no parent is present! self.dir =",
"return False def Color(self, obj): pass def Neighbour(self, pos1, pos2): # Returns true",
"in self.explored def __addToExplored(self, children): # adds the state to the explored list",
"getAgentsByColor(self, color): # same as getPos, just for all agents with the given",
"= key.lower() # same as getPos, just for all Goal with the given",
"and does the movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir, i) if actionParams is",
"actionParams = self.__PullPrec(agtkey, boxkey, direction, i) if actionParams is not None: child =",
"if obj_key.isnumeric() else \"boxes\" if obj_group == \"boxes\": prev_pos = self.getPos(getattr(self, obj_group), obj_key,",
"= pos else: return None def Free(self, pos): # checks if position in",
"minimalRep(self): # returns the minimal representation of the states return str([self.agents, self.boxes]) def",
"color of the agent self.map[pos] = key self.agents[key] = [[pos, color]] # This",
"easy access to agents by color if color not in self.agentColor: self.agentColor[color] =",
"def minimalRep(self): # returns the minimal representation of the states return str([self.agents, self.boxes])",
"t in self.concurrent: joint_concurrent = self.concurrent[t] # a state that it is being",
"def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent can stay at his position without",
"self.explored = set() def deleteAgent(self, external_key): \"\"\"Delete from `agents`, the `map` and `agent_color`.\"\"\"",
"boxdir not in self.dir: # # # print(\"Direction\", boxdir, \"does not exist\") return",
"self.map[self.map == \"Ñ\"] = \" \" def explore(self): \"\"\"Explore with 'NoOp's. The Preconditions",
"checks if position in map is free # returns true if it is",
"1), \"S\": (1, 0), \"W\": (0, -1)} self.deltaPos = { (-1, 0): \"N\",",
"# otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey,",
"as getPos, just for all agents with the given key # if key",
"the object with the given parameters # Does not check preconditions self.setPos(self.agents, agt,",
"put by a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] = \" \" def explore(self):",
"and to a hashtable # key is a letter key = key.upper() self.map[pos]",
"is possible it is appended to the the children actionParams = child_def._StateInit__PushPrec( agtkey,",
"list(self.agents.keys()) for external_agent in ext_agents: if external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key):",
"obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos, index) # introduce a ghost box",
"the agent for boxkey in self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1]",
"position, the index (if multiple)) # returns None if not in hashtable if",
"self.setPos(self.agents, agt, boxfrom, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, boxto,",
"# # print(\"Direction\", agtdir, \"does not exist\") return None agtto = self.__addPos(agtfrom, agtdir)",
"= key self.agents[key] = [[pos, color]] # This is only used to get",
"# same as getPos, just for all Boxes with the given key #",
"simply adds two positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto):",
"external_key): ext_goals = list(self.goals.keys()) for external_goal in ext_goals: if external_goal != external_key: self.deleteGoal(external_goal)",
"not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks",
"def deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for external_agent",
"setPos(self, objtype, obj, pos, i=0): # sets the position of an object #",
"self.concurrent = concurrent if concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for",
"to the the children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction, i ) if",
"children which just waits for the env to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t)",
"if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos else: return None def Free(self, pos):",
"wait if the next state is new and applies the concurrent changes to",
"obj_key, pos, index) # introduce a ghost box which will be removed on",
"\" (row,col)\") return True def Pull(self, agt, boxkey, boxdir, i): # moves the",
"hashtable # key is a letter key = key.lower() if key not in",
"that the environment was changed by another agent; i.e., there is an entry",
"def Move(self, agt, agtdir): # moves the object in the given direction, it",
"returns all the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state = self.prevState i",
"next_time = self.AdvancePrec() if not next_time: return self future_self = self while next_time",
"and actions schemas for the muli-PDDL framework.\"\"\" import copy import operator from typing",
"state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd == \"Push\": # (agtfrom, boxfrom, boxto) parm1",
"= self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1",
"!= external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for external_agent in boxes:",
"of actions used to reach the state path = [] state = copy.deepcopy(self)",
"actionParams = self.__PushPrec(agt, boxkey, boxdir, i) if actionParams is not None: return self.__PushEffect(*actionParams)",
"= parent.g + 1 self.h = None self.f = None self.t = parent.t",
"\" \" def explore(self): \"\"\"Explore with 'NoOp's. The Preconditions to a NoOp is",
"children = [] # Loop iterales through every possible action child_def = StateConcurrent(self)",
"key = key.upper() # same as getPos, just for all Boxes with the",
"not in self.goals: # return None return self.goals[key] def getGoalKeys(self): # returns all",
"and agent_pos[1] == pos[1]: return False return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for",
"muli-PDDL framework.\"\"\" import copy import operator from typing import Dict import numpy as",
"state.getPos(getattr(state, obj_group), looking_for, index), ] ) state = state.prevState else: # format used",
"format used by server while state.actionPerformed is not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd",
"actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children)",
"key, position, the index (if multiple)) # returns None if not in hashtable",
"# # # print(\"Direction\", agtdir, \"does not exist\") return None agtto = self.__addPos(agtfrom,",
"the # neighboring tiles of the agent for boxkey in self.boxes: for i",
"obj): pass def Neighbour(self, pos1, pos2): # Returns true if the 2 positions",
"the children # Checks a Move action if it is possible it is",
"state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif cmd",
"statements! # This can be perhaps be optimized by only looking at boxes",
"by only looking at boxes at the # neighboring tiles of the agent",
"True def Move(self, agt, agtdir): # moves the object in the given direction,",
"self.dir: # # # print(\"Direction\", boxdir, \"does not exist\") return None if self.Neighbour(agtfrom,",
"action if it is possible it is appended to the the children #",
"\"NoOp\" path.append(cmd) state = state.prevState # Reverse the order return path[::-1] def explore(self):",
"if key not in self.goals: self.goals[key] = [[pos, color]] else: self.goals[key].append([pos, color]) def",
"state = state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): # simply adds two positions together",
"is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) #",
"format=0, index=0): # function returns the list of actions used to reach the",
"not next_time: return self future_self = self while next_time > future_self.t: println(future_self) future_self",
"# Does not check preconditions self.setPos(self.agents, agt, agtto, 0) # agents are unique",
"movement parameters if the preconditions are met # otherwise it returns 0 agtfrom",
"just for all Goal with the given key # if key not in",
"= [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push action if it is",
"it is appended to the the children actionParams = self.__MovePrec(agtkey, direction) if actionParams",
"adds the state to the explored list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def",
"to concurrent actions at time `t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key in joint_concurrent:",
"self.h = None self.f = None self.explored = set() else: # if a",
"self.dir: # # # print(\"Direction\", agtdir, \"does not exist\") return None agtto =",
"self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] = \" \" for color in self.agentColor: if",
"self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t in self.concurrent: joint_concurrent = self.concurrent[t] # a",
"returns true if the state is explored return self.minimalRep() in self.explored def __addToExplored(self,",
"agents are unique thus 0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom]",
"rigid self.deltaPos = parent.deltaPos # rigid self.goals = parent.goals # rigid self.agentColor =",
"is guaranteed to have only one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos,",
"child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent number (0",
"a hashtable # key is the agent number and color is the color",
"the precondition and does the movemnt actionParams = self.__MovePrec(agt, agtdir) if actionParams is",
"= None self.t = parent.t + 1 self.explored = parent.explored super().__init__() def addMap(self,",
"None self.f = None self.t = parent.t + 1 self.explored = parent.explored super().__init__()",
"state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif",
"# returns all the keys return list(self.goals.keys()) def getAgentKeys(self): # returns all the",
"return (agt, boxkey, agtfrom, boxfrom, boxto, i) else: # # # print(\"Pos \"",
"agtdir): # moves the object in the given direction, it checks the precondition",
"with the given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom]",
"agtdir): # simply adds two positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self,",
"= None): \"\"\"Initialize by adding a time table to the usual `StateInit`. Parameters",
"= obj_key else: # agents don't leave ghosts behind and are not in",
"self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t in self.concurrent: joint_concurrent = self.concurrent[t]",
"the given parameters # Does not check preconditions self.setPos(self.agents, agt, boxfrom, 0) #",
"# print(\"agent\", agt, \"does not exist\") return None if boxfrom is None: #",
"hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos else: return None def Free(self,",
"\" (row,col) is not free\") return None def __PushEffect(self, agt, boxkey, agtfrom, boxfrom,",
"key.lower() # same as getPos, just for all Goal with the given key",
"total_cost + i state.f = state.g + state.h state = state.prevState\"\"\" def __addPos(self,",
"return (agt, boxkey, agtfrom, agtto, boxfrom, i) else: # # # print(\"Pos \"",
"addGoal(self, key, pos, color=None): # Adds a goal to a hashtable # key",
"not None: path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for, index), ] ) state =",
"0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] =",
"direction, it checks the precondition and does the movemnt actionParams = self.__PushPrec(agt, boxkey,",
"is not None: child = StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for",
"{box: [(row, col), index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent = concurrent if concurrent",
"= state.prevState # Reverse the order return path[::-1] def explore(self): # Explores unexplroed",
"= self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, boxkey, agtfrom, agtto, boxfrom, i) else:",
"parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd",
"def __PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom, i): # Moves the objects with",
"concurrent action by another agent. \"\"\" return self.t in self.concurrent def __ConcurrentEffect(self, t):",
"# Adds an agent to the map and to a hashtable # key",
"child_def.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it is possible it",
"agtto, boxfrom, i): # Moves the objects with the given parameters # Does",
"index (if multiple)) # returns None if not in hashtable if type(objtype[obj][i][0]) ==",
"key, pos, color=\"c\"): # Adds an agent to the map and to a",
"return self.__PullEffect(*actionParams) else: return None def minimalRep(self): # returns the minimal representation of",
"given parameters # Does not check preconditions agtfrom = self.getPos(self.agents, agt) boxfrom =",
"state = copy.deepcopy(self) if format == 1: # format used by actions while",
"key is a letter key = key.lower() if key not in self.goals: self.goals[key]",
"tuple: objtype[obj][i][0] = pos else: return None def Free(self, pos): # checks if",
"self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0], pos[1]] = obj_key return True def hunt_ghost(self):",
"\"S\", (0, -1): \"W\", } self.goals = {} # hashtable self.agentColor = {}",
"if a parent is present! self.dir = parent.dir # rigid self.deltaPos = parent.deltaPos",
"not free\") return None def __PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto, i): #",
"just wait if the next state is new and applies the concurrent changes",
"if agtfrom is None: # # # print(\"agent\", agt, \"does not exist\") return",
"the state to the explored list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self):",
"self.map]) + f\" t={self.t}\" class StateInit(Literals): def __init__(self, parent: \"Literals\" = None): #",
"+ str(agtto) + \" (row,col)\") # print(\"Box \" + str(box) + \" is",
"self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState = parent #",
"class Literals: def __init__(self, parent: \"Literals\" = None): # initializes the literals if",
"by other agent.\"\"\" next_time = self.AdvancePrec() if not next_time: return self future_self =",
"it is being solved is guaranteed to have only one agent agent_pos =",
"next_time > future_self.t: println(future_self) future_self = StateConcurrent(future_self) future_self.actionPerformed = [\"NoOp\", None] return future_self",
"# (agtfrom, agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir(",
"that it is being solved is guaranteed to have only one agent agent_pos",
"at time `t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key in joint_concurrent: pos, index =",
"for NoOp. Agent can stay at his position without doing anything. \"\"\" return",
"object with the given parameters # Does not check preconditions self.setPos(self.agents, agt, agtto)",
"child = StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents:",
"the objects with the given parameters # Does not check preconditions self.setPos(self.agents, agt,",
"def getGoalsByKey(self, key): key = key.lower() # same as getPos, just for all",
"key, the index (if multiple)) # returns None if not in hashtable if",
"print(\"Pos \" + str(boxto) + \" (row,col) is not free\") return None def",
"not None: return self.__PullEffect(*actionParams) else: return None def minimalRep(self): # returns the minimal",
"boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color] if",
"str(agtto) + \" (row,col)\") return True def Move(self, agt, agtdir): # moves the",
"child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction, i) if actionParams is not None:",
"boxdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1: # #",
"in self.dir: # # # print(\"Direction\", agtdir, \"does not exist\") return None agtto",
"return path[::-1] def explore(self): # Explores unexplroed states and returns a list of",
"\" is now at \" + str(agtto) + \" (row,col)\") return True def",
"agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom is None:",
"Debugging purposes return \"\\n\".join([\"\".join(line) for line in self.map]) + f\" t={self.t}\" class StateInit(Literals):",
"function child = StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return children class StateConcurrent(StateInit):",
"self.goals = parent.goals # rigid self.agentColor = parent.agentColor # rigid # TODO avoid",
"+= 1 state.h = total_cost + i state.f = state.g + state.h state",
"is that the environment was changed by another agent; i.e., there is an",
"agt) if agtfrom is None: # # # print(\"agent\", agt, \"does not exist\")",
"println class Literals: def __init__(self, parent: \"Literals\" = None): # initializes the literals",
"= parent.deltaPos # rigid self.goals = parent.goals # rigid self.agentColor = parent.agentColor #",
"state to the explored list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): #",
"None # gets defined when action is chosen self.g = parent.g + 1",
"str): # trace back an object looking_for = format obj_group = \"agents\" if",
"map and to a hashtable # key is the agent number and color",
"\" for color in self.agentColor: if external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del",
"= self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, agtfrom, agtto) else: # # #",
"\"E\", (1, 0): \"S\", (0, -1): \"W\", } self.goals = {} # hashtable",
"if boxdir not in self.dir: # # # print(\"Direction\", boxdir, \"does not exist\")",
"\"\"\"Is there some concurrent change in the future. It will be called by",
"only looking at boxes at # the neighboring tiles of the agent for",
"it is appended to the the children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction,",
"= None self.f = None self.explored = set() else: # if a parent",
"the agent for boxkey in child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor = child_def.boxes[boxkey][i][1]",
"in self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent number",
"according to concurrent actions at time `t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key in",
"pos): # checks if position in map is free # returns true if",
"\"boxes\" while state.actionPerformed is not None: path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for, index),",
"state.prevState elif isinstance(format, str): # trace back an object looking_for = format obj_group",
"else: return False def Color(self, obj): pass def Neighbour(self, pos1, pos2): # Returns",
"the state # it is (row, column) and not (x, y) super().__init__(parent) def",
"the given key # if key not in self.agents: # return None return",
"copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move action if",
"cmd == \"Push\": # (agtfrom, boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] )",
"def hunt_ghost(self): \"\"\"Remove ghosted positions put by a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"]",
"StateInit with concurrent literals.\"\"\" def __init__(self, parent: StateInit = None, concurrent: Dict =",
"= agt # print(\"Agent \" + agt + \" is now at \"",
"Checks a Move action if it is possible it is appended to the",
"copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is there",
"index) self.setPos(getattr(self, obj_group), obj_key, pos, index) # introduce a ghost box which will",
"agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, boxkey, agtfrom, agtto, boxfrom, i)",
"Dict Shared table that contains times where an object (box) in the environment",
"concurrent: Dict = None): \"\"\"Initialize by adding a time table to the usual",
"print(\"Box \" + str(box) + \" is now at \" + str(boxfrom) +",
"= [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents: # TODO make a",
"\" is now at \" + str(agtto) + \" (row,col)\") # print(\"Box \"",
"= child_def.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color] if child_def.agents[agtkey][0][1]",
"future: return min(future) return False def advance(self) -> StateInit: \"\"\"Advance in time until",
"= self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] = \" \" def deleteGoal(self, external_key): del",
"# print(\"Pos \" + str(boxto) + \" (row,col) is not free\") return None",
"# the neighboring tiles of the agent for boxkey in child_def.boxes: for i",
"elif cmd == \"Pull\": # (agtfrom, agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3]",
"return None return self.boxes[key] def getGoalsByKey(self, key): key = key.lower() # same as",
"# Moves the objects with the given parameters # Does not check preconditions",
"times where an object (box) in the environment has been changed by another",
") cmd = f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": # (agtfrom, agtto, boxfrom) parm1",
"boxkey, \"are not neighbors\") return None boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto): return",
"[[pos, color]] # This is only used to get easy access to agents",
"= copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push action",
"t={self.t}\" class StateInit(Literals): def __init__(self, parent: \"Literals\" = None): # initializes the state",
"concurrent changes to all children. \"\"\" children = [] # Loop iterales through",
"check preconditions agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom",
"1 self.h = None self.f = None self.t = parent.t + 1 self.explored",
"str([self.agents, self.boxes]) def isExplored(self): # returns true if the state is explored return",
"= 0 self.t = 0 self.h = None self.f = None self.explored =",
"in self.boxes: # return None return self.boxes[key] def getGoalsByKey(self, key): key = key.lower()",
"self.Neighbour(agtfrom, boxfrom) != 1: # # # print(\"agent\", agt, \"and box\", boxkey, \"are",
"but also append # a NoOp children which just waits for the env",
"to the usual `StateInit`. Parameters ---------- parent: StateInit concurrent: Dict Shared table that",
"\"Push\": # (agtfrom, boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 =",
"self.goals = {} # hashtable self.agentColor = {} # hashtable self.agents = {}",
"agtfrom, agtdir): # simply adds two positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def",
"Move action if it is possible it is appended to the the children",
"looking at boxes at # the neighboring tiles of the agent for boxkey",
"None def setPos(self, objtype, obj, pos, i=0): # sets the position of an",
"key # if key not in self.boxes: # return None return self.boxes[key] def",
"just for all Boxes with the given key # if key not in",
"parent: \"Literals\" = None): # initializes the literals if parent is None: #",
"[agent letter][agent number (0 since it is unique)][color] if self.agents[agtkey][0][1] == boxcolor: #",
"key.upper(): return False return True def bestPath(self, format=0, index=0): # function returns the",
"self.explored def __addToExplored(self, children): # adds the state to the explored list if",
"println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children)",
"be perhaps be optimized by only looking at boxes at # the neighboring",
"super().__init__(parent) def getAgentsByKey(self, key): # same as getPos, just for all agents with",
"def setPos(self, objtype, obj, pos, i=0): # sets the position of an object",
"(row,col)\") # print(\"Box \" + str(box) + \" is now at \" +",
"[agent letter][agent number (0 since it is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: #",
"rigid # TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes) self.map =",
"# print(\"Box\", boxkey, \"does not exist\") return None if boxdir not in self.dir:",
"rigid self.agentColor = parent.agentColor # rigid # TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents)",
"+ \" is now at \" + str(boxfrom) + \" (row,col)\") return True",
"Push(self, agt, boxkey, boxdir, i): # moves the objects in the given direction,",
"obj_key else: # agents don't leave ghosts behind and are not in the",
"is a goal state keys = self.getGoalKeys() for key in keys: goals =",
"cmd = \"NoOp\" path.append(cmd) state = state.prevState # Reverse the order return path[::-1]",
"str(agtto) + \" (row,col) is not free\") return None def __PullEffect(self, agt, boxkey,",
"'NoOp's. The Preconditions to a NoOp is that the environment was changed by",
"a goal to a hashtable # key is a letter key = key.lower()",
"in hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0] = pos else: return None def",
"agent moved dir = (agtto[0] - agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir] def",
"i) if agtfrom is None: # # # print(\"agent\", agt, \"does not exist\")",
"the muli-PDDL framework.\"\"\" import copy import operator from typing import Dict import numpy",
"(box) in the environment has been changed by another agent: {t: {box: [(row,",
"self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment according to concurrent actions at time `t`.\"\"\"",
"is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) #",
"key.upper() self.map[pos] = key if key not in self.boxes: self.boxes[key] = [[pos, color]]",
"# TODO make a noop function child = StateInit(self) child.actionPerformed = [\"NoOp\", None]",
"child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction, i) if",
"the children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not None: child =",
"return children def AdvancePrec(self): \"\"\"Is there some concurrent change in the future. It",
"future. It will be called by by strategy. \"\"\" future = [t for",
"None] child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\" def __init__(self,",
"false otherwise if self.map[pos] == chr(32) or self.map[pos].islower(): return True else: return False",
"\"are not neighbors\") return None boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt,",
"# checks if the state is a goal state keys = self.getGoalKeys() for",
"not None: child = StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey",
"def __str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line) for line in self.map]) + f\"",
"# returns all the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state = self.prevState",
"child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push action if it",
"direction the agent moved dir = (agtto[0] - agtfrom[0], agtto[1] - agtfrom[1]) return",
"i) self.map[agtfrom] = chr(32) self.map[boxfrom] = agt self.map[boxto] = boxkey # print(\"Agent \"",
"actionParams is not None: return self.__PullEffect(*actionParams) else: return None def minimalRep(self): # returns",
"if agent_pos[0] == pos[0] and agent_pos[1] == pos[1]: return False return True def",
"child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents: # TODO make a noop function child",
"# print(\"Direction\", agtdir, \"does not exist\") return None agtto = self.__addPos(agtfrom, agtdir) if",
"chr(32) or self.map[pos].islower(): return True else: return False def Color(self, obj): pass def",
"be called by by strategy. \"\"\" future = [t for t in self.concurrent",
"def advance(self) -> StateInit: \"\"\"Advance in time until the environment is changed by",
"# apply concurrent effects to all children but also append # a NoOp",
"agtdir, \"does not exist\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return",
"does the movemnt actionParams = self.__PushPrec(agt, boxkey, boxdir, i) if actionParams is not",
"agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4]",
"moves the objects in the given direction, it checks the precondition and does",
"= list(self.boxes.keys()) for external_agent in boxes: if external_agent != external_key: self.deleteBox(external_agent) def getPos(self,",
"future = [t for t in self.concurrent if t > self.t] if future:",
"in hashtable if obj in objtype: return objtype[obj][i][0] else: return None def setPos(self,",
"color]] else: self.goals[key].append([pos, color]) def addBox(self, key, pos, color=\"c\"): # Adds a box",
"or self.map[pos].islower(): return True else: return False def Color(self, obj): pass def Neighbour(self,",
"StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return children class StateConcurrent(StateInit): \"\"\"Extend StateInit with",
"children children = [] # Loop iterales through every possible action for direction",
"ghosts behind and are not in the StateInit self.map[self.map == obj_key] = \"Ñ\"",
"# # # print(\"agent\", agt, \"does not exist\") return None if boxfrom is",
"the next time `self.t`. This ensures that agents just wait if the next",
"exist\") return None if boxfrom is None: # # # print(\"Box\", boxkey, \"does",
"key): # same as getPos, just for all agents with the given key",
"in self.boxes: self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored",
"appended to the the children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction, i )",
"\"\"\"Modify environment according to concurrent actions at time `t`.\"\"\" joint_concurrent = self.concurrent[t] for",
"in joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric() else \"boxes\"",
"to the the children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey, direction, i ) if",
"reach the state path = [] state = copy.deepcopy(self) if format == 1:",
"actionParams = self.__MovePrec(agtkey, direction) if actionParams is not None: child = StateInit(self) child.actionPerformed",
"not neighbors\") return None boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt, boxkey,",
"= self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] = \" \" for color in self.agentColor:",
"addMap(self, map2): # initialized a map with only walls self.map = np.array(map2) def",
"self.map[pos] = \" \" for color in self.agentColor: if external_key in self.agentColor[color]: to_del",
"= self.getGoalKeys() for key in keys: goals = self.getGoalsByKey(key) for pos, color in",
"# rigid self.goals = parent.goals # rigid self.agentColor = parent.agentColor # rigid #",
"not (x, y) super().__init__(parent) def getAgentsByKey(self, key): # same as getPos, just for",
"# sets the position of an object # setPos(objecttype, the key, position, the",
"true if it is free and false otherwise if self.map[pos] == chr(32) or",
"return (agt, agtfrom, agtto) else: # # # print(\"Pos \" + str(agtto) +",
"returns a list of children children = [] # Loop iterales through every",
"entry in `self.concurrent` for the next time `self.t`. This ensures that agents just",
"_ in joint_concurrent.values(): if pos is None: continue if agent_pos[0] == pos[0] and",
"append # a NoOp children which just waits for the env to change",
"def Free(self, pos): # checks if position in map is free # returns",
"it is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: # Checks a pull action if",
"it is possible it is appended to the the children # Checks a",
"0 self.h = None self.f = None self.explored = set() else: # if",
"otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) if agtfrom is None: #",
"\" + str(agtto) + \" (row,col) is not free\") return None def __MoveEffect(self,",
"given direction, it checks the precondition and does the movemnt actionParams = self.__PullPrec(agt,",
"precondition and does the movemnt actionParams = self.__MovePrec(agt, agtdir) if actionParams is not",
"def deleteAgent(self, external_key): \"\"\"Delete from `agents`, the `map` and `agent_color`.\"\"\" pos = self.getPos(self.agents,",
"list(self.boxes.keys()) for external_agent in boxes: if external_agent != external_key: self.deleteBox(external_agent) def getPos(self, objtype,",
"if statements! # This can be perhaps be optimized by only looking at",
"agent self.map[pos] = key self.agents[key] = [[pos, color]] # This is only used",
"self.agentColor = parent.agentColor # rigid # TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes",
"obj, pos, i=0): # sets the position of an object # setPos(objecttype, the",
"if the 2 positions are neighbours, otherwise false if abs(pos1[0] - pos2[0]) +",
"agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto] = agt # print(\"Agent \" + agt",
"not exist\") return None if agtdir not in self.dir: # # # print(\"Direction\",",
"the the children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not None: child",
"def __addPos(self, agtfrom, agtdir): # simply adds two positions together return tuple(map(operator.add, agtfrom,",
"gets the position of an object getPos(objecttype, the key, the index (if multiple))",
"set() def deleteAgent(self, external_key): \"\"\"Delete from `agents`, the `map` and `agent_color`.\"\"\" pos =",
"None: return self.__MoveEffect(*actionParams) else: return None def __PushPrec(self, agt, boxkey, boxdir, i=0): #",
"box\", boxkey, \"are not neighbors\") return None boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto):",
"is appended to the the children actionParams = self.__PullPrec(agtkey, boxkey, direction, i) if",
"pos, _ in joint_concurrent.values(): if pos is None: continue if agent_pos[0] == pos[0]",
"obj_group), obj_key, pos, index) # introduce a ghost box which will be removed",
"of children children = [] # Loop iterales through every possible action for",
"a noop function child = StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return children",
"self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom is None: # #",
"from `agents`, the `map` and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos]",
"__PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom, i): # Moves the objects with the",
"1 self.explored = parent.explored super().__init__() def addMap(self, map2): # initialized a map with",
"a ghost box which will be removed on child nodes self.map[prev_pos[0], prev_pos[1]] =",
"getGoalsByKey(self, key): key = key.lower() # same as getPos, just for all Goal",
"the map and to a hashtable # key is the agent number and",
"self.agentColor[color] = [key] else: self.agentColor[color].append(key) def addGoal(self, key, pos, color=None): # Adds a",
"Explores unexplroed states and returns a list of children children = [] #",
"the state path = [] state = copy.deepcopy(self) if format == 1: #",
"prev_pos[1]] = \"Ñ\" if pos is not None: self.map[pos[0], pos[1]] = obj_key else:",
"for t in self.concurrent if t > self.t] if future: return min(future) return",
"children # Checks a Move action if it is possible it is appended",
"getPos, just for all agents with the given key return self.agentColor[color] def getBoxesByKey(self,",
"self.agents: # TODO reformat these nested loops and if statements! # This can",
"StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent effects to all children but also append",
"= self while next_time > future_self.t: println(future_self) future_self = StateConcurrent(future_self) future_self.actionPerformed = [\"NoOp\",",
"child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\",",
"actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push action if it is possible it",
"# agents are unique thus 0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] = chr(32)",
"a pull action if it is possible it is appended to the the",
"at # the neighboring tiles of the agent for boxkey in child_def.boxes: for",
"does the movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir, i) if actionParams is not",
"self.agentColor: if external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key):",
"color in self.agentColor: if external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def",
"= [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move action if it is",
"# key is the agent number and color is the color of the",
"for pos, _ in joint_concurrent.values(): if pos is None: continue if agent_pos[0] ==",
"same as getPos, just for all Goal with the given key # if",
"is possible it is appended to the the children actionParams = child_def._StateInit__MovePrec(agtkey, direction)",
"del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for external_agent in ext_agents: if",
"# Reverse the order return path[::-1] def explore(self): # Explores unexplroed states and",
"not in self.goals: self.goals[key] = [[pos, color]] else: self.goals[key].append([pos, color]) def addBox(self, key,",
"the StateInit self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0], pos[1]] = obj_key return True",
"None: # # # print(\"Box\", boxkey, \"does not exist\") return None if agtdir",
"NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for",
"+ \" (row,col) is not free\") return None def __MoveEffect(self, agt, agtfrom, agtto):",
"pos is None: continue if agent_pos[0] == pos[0] and agent_pos[1] == pos[1]: return",
"total_cost): state = self.prevState i = 0 while state is not None: i",
"\"\"\"Remove ghosted positions put by a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] = \"",
"in goals: if self.map[pos] != key.upper(): return False return True def bestPath(self, format=0,",
"def Neighbour(self, pos1, pos2): # Returns true if the 2 positions are neighbours,",
"None return self.goals[key] def getGoalKeys(self): # returns all the keys return list(self.goals.keys()) def",
"# # # print(\"Pos \" + str(agtto) + \" (row,col) is not free\")",
"= state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): # simply adds two positions together return",
"operator from typing import Dict import numpy as np from utils import println",
"obj_key in joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric() else",
"ensures that agents just wait if the next state is new and applies",
"apply concurrent effects to all children but also append # a NoOp children",
"which will be removed on child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos",
"i) else: # # # print(\"Pos \" + str(boxto) + \" (row,col) is",
"actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction, i) if actionParams is not",
"print(\"agent\", agt, \"does not exist\") return None if boxfrom is None: # #",
"present! self.dir = parent.dir # rigid self.deltaPos = parent.deltaPos # rigid self.goals =",
"boxkey self.map[agtto] = agt # print(\"Agent \" + agt + \" is now",
"object getPos(objecttype, the key, the index (if multiple)) # returns None if not",
"def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for external_goal in ext_goals: if external_goal !=",
"child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent effects to all children but",
"None if boxfrom is None: # # # print(\"Box\", boxkey, \"does not exist\")",
"is appended to the the children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams is",
"a hashtable # key is a letter key = key.upper() self.map[pos] = key",
"agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom is None: # # #",
"self.deltaPos = { (-1, 0): \"N\", (0, 1): \"E\", (1, 0): \"S\", (0,",
"free\") return None def __PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto, i): # Moves",
"self.h = None self.f = None self.t = parent.t + 1 self.explored =",
"number (0 since it is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: # Checks a",
"== obj_key] = \"Ñ\" self.map[pos[0], pos[1]] = obj_key return True def hunt_ghost(self): \"\"\"Remove",
"if no parent is present! self.dir = {\"N\": (-1, 0), \"E\": (0, 1),",
"return None if boxdir not in self.dir: # # # print(\"Direction\", boxdir, \"does",
"(agt, boxkey, agtfrom, boxfrom, boxto, i) else: # # # print(\"Pos \" +",
"parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif cmd == \"NoOp\":",
"+ i state.f = state.g + state.h state = state.prevState\"\"\" def __addPos(self, agtfrom,",
"agtfrom, agtto) else: # # # print(\"Pos \" + str(agtto) + \" (row,col)",
"just for all agents with the given key # if key not in",
"returns the minimal representation of the states return str([self.agents, self.boxes]) def isExplored(self): #",
"agt + \" is now at \" + str(agtto) + \" (row,col)\") #",
"self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0): # gets the position of an object",
"a goal state keys = self.getGoalKeys() for key in keys: goals = self.getGoalsByKey(key)",
"the usual `StateInit`. Parameters ---------- parent: StateInit concurrent: Dict Shared table that contains",
"is possible it is appended to the the children # Checks a Move",
"# setPos(objecttype, the key, position, the index (if multiple)) # returns None if",
"actionParams is not None: return self.__MoveEffect(*actionParams) else: return None def __PushPrec(self, agt, boxkey,",
"make a noop function child = StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children) return",
"the the children # Checks a Move action if it is possible it",
"possible it is appended to the the children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey,",
"for boxkey in self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent",
"is new and applies the concurrent changes to all children. \"\"\" children =",
"given parameters # Does not check preconditions self.setPos(self.agents, agt, boxfrom, 0) # agents",
"[key] else: self.agentColor[color].append(key) def addGoal(self, key, pos, color=None): # Adds a goal to",
"are met # otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) boxfrom =",
"return True def bestPath(self, format=0, index=0): # function returns the list of actions",
"a Push action if it is possible it is appended to the the",
"being solved is guaranteed to have only one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0])",
"return None boxto = self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom,",
"not None: path.append(state.actionPerformed) state = state.prevState elif isinstance(format, str): # trace back an",
"\"N\", (0, 1): \"E\", (1, 0): \"S\", (0, -1): \"W\", } self.goals =",
"external_key): \"\"\"Delete from `agents`, the `map` and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del",
"obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos, index) # introduce a ghost box which",
"a NoOp is that the environment was changed by another agent; i.e., there",
"nested loops and if statements! # This can be perhaps be optimized by",
"None: path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for, index), ] ) state = state.prevState",
"+ str(agtto) + \" (row,col)\") return True def Move(self, agt, agtdir): # moves",
"0), \"E\": (0, 1), \"S\": (1, 0), \"W\": (0, -1)} self.deltaPos = {",
"the index (if multiple)) # returns None if not in hashtable if obj",
"the precondition and does the movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir, i) if",
"children class StateConcurrent(StateInit): \"\"\"Extend StateInit with concurrent literals.\"\"\" def __init__(self, parent: StateInit =",
"t > self.t] if future: return min(future) return False def advance(self) -> StateInit:",
"agents are unique thus 0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom]",
"def addBox(self, key, pos, color=\"c\"): # Adds a box to the map and",
"state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd = f\"Push({parm1},{parm2})\" elif cmd",
"in keys: goals = self.getGoalsByKey(key) for pos, color in goals: if self.map[pos] !=",
"ghosted positions put by a Councurent Effect.\"\"\" self.map[self.map == \"Ñ\"] = \" \"",
"elif isinstance(format, str): # trace back an object looking_for = format obj_group =",
"self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent can stay at his position",
"to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key) del",
"if key not in self.goals: # return None return self.goals[key] def getGoalKeys(self): #",
"children. \"\"\" children = [] # Loop iterales through every possible action child_def",
"StateInit concurrent: Dict Shared table that contains times where an object (box) in",
"Goal with the given key # if key not in self.goals: # return",
"print(\"agent\", agt, \"does not exist\") return None if agtdir not in self.dir: #",
"child_def.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color] if child_def.agents[agtkey][0][1] ==",
"__PullPrec(self, agt, boxkey, agtdir, i=0): # Moves the object with the given parameters",
"exist\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, agtfrom, agtto)",
"actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed",
"multiple)) # returns None if not in hashtable if obj in objtype: return",
"[\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is there some concurrent change",
"\"W\": (0, -1)} self.deltaPos = { (-1, 0): \"N\", (0, 1): \"E\", (1,",
"preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto] = agt # print(\"Agent \"",
"> self.t] if future: return min(future) return False def advance(self) -> StateInit: \"\"\"Advance",
"self.agents[external_key] self.map[pos] = \" \" for color in self.agentColor: if external_key in self.agentColor[color]:",
"# if a parent is present! self.dir = parent.dir # rigid self.deltaPos =",
"[\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Move action if it is possible",
"is not None: path.append(state.actionPerformed) state = state.prevState elif isinstance(format, str): # trace back",
"preconditions self.setPos(self.agents, agt, boxfrom, 0) # agents are unique thus 0 self.setPos(self.boxes, boxkey,",
"Pull(self, agt, boxkey, boxdir, i): # moves the objects in the given direction,",
"children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not None: child = copy.deepcopy(child_def)",
"key, pos, color=None): # Adds a goal to a hashtable # key is",
"state = state.prevState # Reverse the order return path[::-1] def explore(self): # Explores",
"precondition and does the movemnt actionParams = self.__PullPrec(agt, boxkey, boxdir, i) if actionParams",
"None: child = StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in",
"the position of an object # setPos(objecttype, the key, position, the index (if",
"# print(\"Box \" + str(box) + \" is now at \" + str(agtfrom)",
"self.prevState = None self.actionPerformed = None self.g = 0 self.t = 0 self.h",
"given direction, it checks the precondition and does the movemnt actionParams = self.__MovePrec(agt,",
"\"\"\"Remove explored nodes.\"\"\" self.explored = set() def deleteAgent(self, external_key): \"\"\"Delete from `agents`, the",
"the concurrent changes to all children. \"\"\" children = [] # Loop iterales",
"= chr(32) self.map[agtto] = agt # print(\"Agent \" + agt + \" is",
"child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction, i) if actionParams is not None: child",
"return None def __PushPrec(self, agt, boxkey, boxdir, i=0): # returns the movement parameters",
"self.boxes = {} # hashtable self.prevState = None self.actionPerformed = None self.g =",
"= self.agentColor[color].index(external_key) del self.agentColor[color][to_del] def deleteBox(self, external_key): pos = self.getPos(self.boxes, external_key) del self.boxes[external_key]",
"# initialized a map with only walls self.map = np.array(map2) def addAgent(self, key,",
"list(self.goals.keys()) for external_goal in ext_goals: if external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key):",
"effects to all children but also append # a NoOp children which just",
"= StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents: #",
"f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd =",
"None: # if no parent is present! self.dir = {\"N\": (-1, 0), \"E\":",
"0 self.setPos(self.boxes, boxkey, boxto, i) self.map[agtfrom] = chr(32) self.map[boxfrom] = agt self.map[boxto] =",
"boxes at the # neighboring tiles of the agent for boxkey in self.boxes:",
"if future: return min(future) return False def advance(self) -> StateInit: \"\"\"Advance in time",
"import Dict import numpy as np from utils import println class Literals: def",
"= None self.f = None self.t = parent.t + 1 self.explored = parent.explored",
"boxkey, agtfrom, agtto, boxfrom, i) else: # # # print(\"Pos \" + str(agtto)",
"\" (row,col)\") return True def Push(self, agt, boxkey, boxdir, i): # moves the",
"list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values(): if pos is None: continue if agent_pos[0]",
"child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self):",
"key # if key not in self.goals: # return None return self.goals[key] def",
"(0, 1), \"S\": (1, 0), \"W\": (0, -1)} self.deltaPos = { (-1, 0):",
"= list(self.agents.keys()) for external_agent in ext_agents: if external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self,",
"False def Color(self, obj): pass def Neighbour(self, pos1, pos2): # Returns true if",
"pos, i=0): # sets the position of an object # setPos(objecttype, the key,",
"Move(self, agt, agtdir): # moves the object in the given direction, it checks",
"pos2): # Returns true if the 2 positions are neighbours, otherwise false if",
"given key return self.agentColor[color] def getBoxesByKey(self, key): key = key.upper() # same as",
"literals and actions schemas for the muli-PDDL framework.\"\"\" import copy import operator from",
"is now at \" + str(agtto) + \" (row,col)\") return True def Move(self,",
"letter key = key.upper() self.map[pos] = key if key not in self.boxes: self.boxes[key]",
"direction in self.dir: for agtkey in self.agents: # TODO reformat these nested loops",
"# Adds a box to the map and to a hashtable # key",
"for key in keys: goals = self.getGoalsByKey(key) for pos, color in goals: if",
"else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent can stay at",
"all children but also append # a NoOp children which just waits for",
"self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey self.map[agtto] = agt # print(\"Agent \" +",
"agtdir) if self.Free(agtto): return (agt, agtfrom, agtto) else: # # # print(\"Pos \"",
"range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color]",
"key is a letter key = key.upper() self.map[pos] = key if key not",
"addBox(self, key, pos, color=\"c\"): # Adds a box to the map and to",
"not None: child = StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams =",
"# moves the objects in the given direction, it checks the precondition and",
"for the muli-PDDL framework.\"\"\" import copy import operator from typing import Dict import",
"i) self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey self.map[agtto] = agt # print(\"Agent \"",
"pos[1]] = obj_key else: # agents don't leave ghosts behind and are not",
"are unique thus 0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom] =",
"since it is unique)][color] if child_def.agents[agtkey][0][1] == boxcolor: # Checks a pull action",
"check preconditions self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto] = agt # print(\"Agent",
"agt, boxkey, boxdir, i): # moves the objects in the given direction, it",
"it is possible it is appended to the the children actionParams = self.__PullPrec(agtkey,",
"if external_agent != external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0): # gets the",
"if external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for external_goal",
"agent_pos[1] == pos[1]: return False return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent",
"external_agent != external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0): # gets the position",
"None return self.agents[key] def getAgentsByColor(self, color): # same as getPos, just for all",
"state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif cmd == \"Move\": parm1 = self.__getDir(",
"be optimized by only looking at boxes at the # neighboring tiles of",
"if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for direction in",
"ext_agents: if external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for",
"boxkey, direction, i) if actionParams is not None: child = StateInit(self) child.actionPerformed =",
"= [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is there some concurrent",
"met # otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) if agtfrom is",
"return True def hunt_ghost(self): \"\"\"Remove ghosted positions put by a Councurent Effect.\"\"\" self.map[self.map",
"the object in the given direction, it checks the precondition and does the",
"hashtable if obj in objtype: return objtype[obj][i][0] else: return None def setPos(self, objtype,",
"self.dir: # # # print(\"Direction\", agtdir, \"does not exist\") return None if self.Neighbour(agtfrom,",
"set() else: # if a parent is present! self.dir = parent.dir # rigid",
"external_key): del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for external_agent in ext_agents:",
"external_goal in ext_goals: if external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes =",
"format == 1: # format used by actions while state.actionPerformed is not None:",
"the position of an object getPos(objecttype, the key, the index (if multiple)) #",
"the map and to a hashtable # key is a letter key =",
"print(\"Direction\", boxdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1: #",
"self.map[pos] = \" \" def deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents",
"# print(\"Box \" + str(box) + \" is now at \" + str(boxfrom)",
"The Preconditions to a NoOp is that the environment was changed by another",
"self.boxes: self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\"",
"i=0): # sets the position of an object # setPos(objecttype, the key, position,",
"the preconditions are met # otherwise it returns 0 agtfrom = self.getPos(self.agents, agt)",
"reformat these nested loops and if statements! # This can be perhaps be",
"def __PullPrec(self, agt, boxkey, agtdir, i=0): # Moves the object with the given",
"is not free\") return None def __PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom, i):",
"is None: # # # print(\"agent\", agt, \"does not exist\") return None if",
"# print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return None agtto =",
"color=\"c\"): # Adds an agent to the map and to a hashtable #",
"(-1, 0), \"E\": (0, 1), \"S\": (1, 0), \"W\": (0, -1)} self.deltaPos =",
"agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt, agtdir): # returns the",
"self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif cmd == \"NoOp\": cmd =",
"pos[0] and agent_pos[1] == pos[1]: return False return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition",
"and false otherwise if self.map[pos] == chr(32) or self.map[pos].islower(): return True else: return",
"return self.__PushEffect(*actionParams) else: return None def __PullPrec(self, agt, boxkey, agtdir, i=0): # Moves",
"key self.agents[key] = [[pos, color]] # This is only used to get easy",
"print(\"Box\", boxkey, \"does not exist\") return None if agtdir not in self.dir: #",
"without doing anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if t",
"return None def setPos(self, objtype, obj, pos, i=0): # sets the position of",
"\"\"\" future = [t for t in self.concurrent if t > self.t] if",
"if the state is explored return self.minimalRep() in self.explored def __addToExplored(self, children): #",
"# # print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return None boxto",
"is not None: return self.__PushEffect(*actionParams) else: return None def __PullPrec(self, agt, boxkey, agtdir,",
"path.append(state.actionPerformed) state = state.prevState elif isinstance(format, str): # trace back an object looking_for",
"# # # print(\"Box\", boxkey, \"does not exist\") return None if agtdir not",
"\"\"\" return self.t in self.concurrent def __ConcurrentEffect(self, t): \"\"\"Modify environment according to concurrent",
"in self.dir: for agtkey in self.agents: # TODO reformat these nested loops and",
"= None): # initializes the state # it is (row, column) and not",
"the minimal representation of the states return str([self.agents, self.boxes]) def isExplored(self): # returns",
"def isGoalState(self): # checks if the state is a goal state keys =",
"Dict import numpy as np from utils import println class Literals: def __init__(self,",
"agt, agtdir): # moves the object in the given direction, it checks the",
"is not None: return self.__PullEffect(*actionParams) else: return None def minimalRep(self): # returns the",
"agtfrom, agtto): # returns the direction the agent moved dir = (agtto[0] -",
"self.map[pos[0], pos[1]] = obj_key return True def hunt_ghost(self): \"\"\"Remove ghosted positions put by",
"\"\"\"Define literals and actions schemas for the muli-PDDL framework.\"\"\" import copy import operator",
"box\", boxkey, \"are not neighbors\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto):",
") parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif cmd ==",
"child_def._StateInit__PullPrec( agtkey, boxkey, direction, i ) if actionParams is not None: child =",
"self.map[pos].islower(): return True else: return False def Color(self, obj): pass def Neighbour(self, pos1,",
"by server while state.actionPerformed is not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0]",
"# # # print(\"Direction\", agtdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom)",
"as getPos, just for all agents with the given key return self.agentColor[color] def",
"# format used by actions while state.actionPerformed is not None: path.append(state.actionPerformed) state =",
"map is free # returns true if it is free and false otherwise",
"# moves the object in the given direction, it checks the precondition and",
"self.f = None self.explored = set() else: # if a parent is present!",
"\" (row,col) is not free\") return None def __PullEffect(self, agt, boxkey, agtfrom, agtto,",
"print(\"Box\", boxkey, \"does not exist\") return None if boxdir not in self.dir: #",
"# initializes the literals if parent is None: # if no parent is",
"direction) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams]",
"joint_concurrent = self.concurrent[t] # a state that it is being solved is guaranteed",
"Boxes with the given key # if key not in self.boxes: # return",
"not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd == \"Push\": #",
"del self.agents[external_key] self.map[pos] = \" \" for color in self.agentColor: if external_key in",
"== \"Pull\": # (agtfrom, agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2",
"abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) == 1: return True else: return",
"possible it is appended to the the children actionParams = child_def._StateInit__PushPrec( agtkey, boxkey,",
"super().__init__() def addMap(self, map2): # initialized a map with only walls self.map =",
"if parent is None: # if no parent is present! self.dir = {\"N\":",
"= {} # hashtable self.agentColor = {} # hashtable self.agents = {} #",
"\"\"\"Initialize by adding a time table to the usual `StateInit`. Parameters ---------- parent:",
"strategy. \"\"\" future = [t for t in self.concurrent if t > self.t]",
"self.setPos(self.agents, agt, agtto) self.map[agtfrom] = chr(32) self.map[agtto] = agt # print(\"Agent \" +",
"This can be perhaps be optimized by only looking at boxes at the",
"self.prevState i = 0 while state is not None: i += 1 state.h",
"prev_pos = self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos, index) # introduce",
"# Checks a Push action if it is possible it is appended to",
"= None # gets defined when action is chosen self.g = parent.g +",
"== \"Push\": # (agtfrom, boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2",
"appended to the the children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if actionParams is not",
"def getGoalKeys(self): # returns all the keys return list(self.goals.keys()) def getAgentKeys(self): # returns",
"with the given key # if key not in self.agents: # return None",
"it is possible it is appended to the the children actionParams = self.__MovePrec(agtkey,",
"= format obj_group = \"agents\" if format.isnumeric() else \"boxes\" while state.actionPerformed is not",
"abs(pos1[1] - pos2[1]) == 1: return True else: return False def __str__(self): #",
"boxcolor: # Checks a pull action if it is possible it is appended",
"typing import Dict import numpy as np from utils import println class Literals:",
"parent is present! self.dir = {\"N\": (-1, 0), \"E\": (0, 1), \"S\": (1,",
"the key, the index (if multiple)) # returns None if not in hashtable",
"self.getPos(self.boxes, boxkey, i) if agtfrom is None: # # # print(\"agent\", agt, \"does",
"= key.upper() # same as getPos, just for all Boxes with the given",
"= [\"NoOp\", None] child._StateInit__addToExplored(children) for direction in self.dir: for agtkey in self.agents: #",
"self.actionPerformed = None # gets defined when action is chosen self.g = parent.g",
"key return self.agentColor[color] def getBoxesByKey(self, key): key = key.upper() # same as getPos,",
"key = key.lower() # same as getPos, just for all Goal with the",
"= \" \" def deleteGoal(self, external_key): del self.goals[external_key] def keepJustAgent(self, external_key): ext_agents =",
"used by actions while state.actionPerformed is not None: path.append(state.actionPerformed) state = state.prevState elif",
"!= external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for external_goal in ext_goals:",
"joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group = \"agents\" if obj_key.isnumeric() else \"boxes\" if",
"dir = (agtto[0] - agtfrom[0], agtto[1] - agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt,",
"position without doing anything. \"\"\" return self.__WaitPrec_t(self.t) and self.__WaitPrec_t(self.t+1) def __WaitPrec_t(self, t): if",
"= None): # initializes the literals if parent is None: # if no",
"t): \"\"\"Modify environment according to concurrent actions at time `t`.\"\"\" joint_concurrent = self.concurrent[t]",
"boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] )",
"cmd == \"Pull\": # (agtfrom, agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] )",
"the movement parameters if the preconditions are met # otherwise it returns 0",
"def __PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto, i): # Moves the objects with",
"external_agent in boxes: if external_agent != external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0):",
"the keys return list(self.agents.keys()) \"\"\"def updateParentCost(self, total_cost): state = self.prevState i = 0",
") state = state.prevState else: # format used by server while state.actionPerformed is",
"\"agents\" if obj_key.isnumeric() else \"boxes\" if obj_group == \"boxes\": prev_pos = self.getPos(getattr(self, obj_group),",
"agtfrom, boxfrom, boxto, i) else: # # # print(\"Pos \" + str(boxto) +",
"return None def __MoveEffect(self, agt, agtfrom, agtto): # Moves the object with the",
"1: # format used by actions while state.actionPerformed is not None: path.append(state.actionPerformed) state",
"the given key return self.agentColor[color] def getBoxesByKey(self, key): key = key.upper() # same",
"agents don't leave ghosts behind and are not in the StateInit self.map[self.map ==",
"is None: continue if agent_pos[0] == pos[0] and agent_pos[1] == pos[1]: return False",
"return str([self.agents, self.boxes]) def isExplored(self): # returns true if the state is explored",
"actions while state.actionPerformed is not None: path.append(state.actionPerformed) state = state.prevState elif isinstance(format, str):",
"actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction, i ) if actionParams is not None:",
"None: self.map[pos[0], pos[1]] = obj_key else: # agents don't leave ghosts behind and",
"in `self.concurrent` for the next time `self.t`. This ensures that agents just wait",
"returns 0 agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom",
"boxcolor = child_def.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color] if",
"self.g = 0 self.t = 0 self.h = None self.f = None self.explored",
"None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a",
"free\") return None def __PullEffect(self, agt, boxkey, agtfrom, agtto, boxfrom, i): # Moves",
"one agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values(): if pos",
"agt + \" is now at \" + str(agtto) + \" (row,col)\") return",
"the given parameters # Does not check preconditions agtfrom = self.getPos(self.agents, agt) boxfrom",
"str(boxto) + \" (row,col)\") # print(\"Box \" + str(box) + \" is now",
"isGoalState(self): # checks if the state is a goal state keys = self.getGoalKeys()",
"= self.__PullPrec(agtkey, boxkey, direction, i) if actionParams is not None: child = StateInit(self)",
"# adds the state to the explored list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self)",
"Loop iterales through every possible action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply",
"the list of actions used to reach the state path = [] state",
"= StateInit(self) child.actionPerformed = [\"Pull\", actionParams] child.__PullEffect(*actionParams) child.__addToExplored(children) actionParams = self.__PushPrec(agtkey, boxkey, direction,",
"to the explored list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks",
"agt, boxkey, boxdir, i=0): # returns the movement parameters if the preconditions are",
"iterales through every possible action child_def = StateConcurrent(self) if child_def.__ConcurrentPrec(): # apply concurrent",
"self.goals[key] = [[pos, color]] else: self.goals[key].append([pos, color]) def addBox(self, key, pos, color=\"c\"): #",
"if position in map is free # returns true if it is free",
"parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd",
"nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos is not None: self.map[pos[0], pos[1]] =",
"# Checks a pull action if it is possible it is appended to",
"agtkey in self.agents: # TODO reformat these nested loops and if statements! #",
"the neighboring tiles of the agent for boxkey in child_def.boxes: for i in",
"Does not check preconditions agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i)",
"child._StateInit__addToExplored(children) # Checks a Push action if it is possible it is appended",
"self.agents[key] def getAgentsByColor(self, color): # same as getPos, just for all agents with",
"color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored = set() def deleteAgent(self, external_key): \"\"\"Delete",
"external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys()) for external_goal in",
"str(box) + \" is now at \" + str(boxfrom) + \" (row,col)\") return",
"the color of the agent self.map[pos] = key self.agents[key] = [[pos, color]] #",
"boxkey, agtfrom, agtto, boxfrom, i): # Moves the objects with the given parameters",
"# return None return self.boxes[key] def getGoalsByKey(self, key): key = key.lower() # same",
"for color in self.agentColor: if external_key in self.agentColor[color]: to_del = self.agentColor[color].index(external_key) del self.agentColor[color][to_del]",
"to reach the state path = [] state = copy.deepcopy(self) if format ==",
"joint_concurrent = self.concurrent[t] for obj_key in joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group =",
"of the agent for boxkey in child_def.boxes: for i in range(len(child_def.boxes[boxkey])): boxcolor =",
"else: # if a parent is present! self.dir = parent.dir # rigid self.deltaPos",
"child nodes self.map[prev_pos[0], prev_pos[1]] = \"Ñ\" if pos is not None: self.map[pos[0], pos[1]]",
"otherwise false if abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) == 1: return",
"= 0 while state is not None: i += 1 state.h = total_cost",
"by another agent: {t: {box: [(row, col), index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent",
"# gets the position of an object getPos(objecttype, the key, the index (if",
"chr(32) self.map[boxfrom] = agt self.map[boxto] = boxkey # print(\"Agent \" + agt +",
"child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for direction in self.dir: for",
"pos = self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] = \" \" def deleteGoal(self, external_key):",
"if pos is not None: self.map[pos[0], pos[1]] = obj_key else: # agents don't",
"unexplroed states and returns a list of children children = [] # Loop",
"} self.goals = {} # hashtable self.agentColor = {} # hashtable self.agents =",
"with 'NoOp's. The Preconditions to a NoOp is that the environment was changed",
"returns the list of actions used to reach the state path = []",
"for pos, color in goals: if self.map[pos] != key.upper(): return False return True",
"obj in objtype: return objtype[obj][i][0] else: return None def setPos(self, objtype, obj, pos,",
"boxdir, i): # moves the objects in the given direction, it checks the",
"None def __PushPrec(self, agt, boxkey, boxdir, i=0): # returns the movement parameters if",
"is now at \" + str(agtfrom) + \" (row,col)\") return True def Pull(self,",
"parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd = f\"Pull({parm1},{parm2})\" elif cmd == \"Move\":",
"state.f = state.g + state.h state = state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): #",
"multiple)) # returns None if not in hashtable if type(objtype[obj][i][0]) == tuple: objtype[obj][i][0]",
"boxkey, boxdir, i=0): # returns the movement parameters if the preconditions are met",
"= [] # Loop iterales through every possible action child_def = StateConcurrent(self) if",
"min(future) return False def advance(self) -> StateInit: \"\"\"Advance in time until the environment",
"state is explored return self.minimalRep() in self.explored def __addToExplored(self, children): # adds the",
"\" + str(agtfrom) + \" (row,col)\") return True def Pull(self, agt, boxkey, boxdir,",
"[(row, col), index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent = concurrent if concurrent else",
"self.goals[external_key] def keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for external_agent in ext_agents: if external_agent",
"def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored = set() def deleteAgent(self, external_key): \"\"\"Delete from",
"if child_def.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it is possible",
"== \"Move\": parm1 = self.__getDir( state.actionPerformed[1][1], state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif cmd",
"with only walls self.map = np.array(map2) def addAgent(self, key, pos, color=\"c\"): # Adds",
"t): if t in self.concurrent: joint_concurrent = self.concurrent[t] # a state that it",
"if actionParams is not None: return self.__MoveEffect(*actionParams) else: return None def __PushPrec(self, agt,",
"color=\"c\"): # Adds a box to the map and to a hashtable #",
"actions used to reach the state path = [] state = copy.deepcopy(self) if",
"self.setPos(getattr(self, obj_group), obj_key, pos, index) # introduce a ghost box which will be",
"deleteAgent(self, external_key): \"\"\"Delete from `agents`, the `map` and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key)",
"positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto): # returns the",
"agtfrom is None: # # # print(\"agent\", agt, \"does not exist\") return None",
"changed given a concurrent action by another agent. \"\"\" return self.t in self.concurrent",
"agt + \" is now at \" + str(boxto) + \" (row,col)\") #",
"= list(self.goals.keys()) for external_goal in ext_goals: if external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self,",
"index=0): # function returns the list of actions used to reach the state",
"i) if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Pull\", actionParams]",
"parent.t + 1 self.explored = parent.explored super().__init__() def addMap(self, map2): # initialized a",
"print(\"Agent \" + agt + \" is now at \" + str(boxto) +",
"self.Free(agtto): return (agt, agtfrom, agtto) else: # # # print(\"Pos \" + str(agtto)",
"None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, agtfrom, agtto) else: #",
"if pos is None: continue if agent_pos[0] == pos[0] and agent_pos[1] == pos[1]:",
"are neighbours, otherwise false if abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) ==",
"0) # agents are unique thus 0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] =",
"# # print(\"Box\", boxkey, \"does not exist\") return None if boxdir not in",
"= state.g + state.h state = state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): # simply",
"boxkey, agtdir, i=0): # Moves the object with the given parameters # Does",
"boxkey # print(\"Agent \" + agt + \" is now at \" +",
"external_key) del self.agents[external_key] self.map[pos] = \" \" for color in self.agentColor: if external_key",
"copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState = parent # reference to previous state self.actionPerformed",
"is appended to the the children actionParams = self.__MovePrec(agtkey, direction) if actionParams is",
"boxfrom, boxto, i) else: # # # print(\"Pos \" + str(boxto) + \"",
"boxkey, agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey self.map[agtto] = agt #",
"# (agtfrom, boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir(",
"self.map[agtfrom] = chr(32) self.map[boxfrom] = agt self.map[boxto] = boxkey # print(\"Agent \" +",
"it is possible it is appended to the the children actionParams = child_def._StateInit__PushPrec(",
"free\") return None def __MoveEffect(self, agt, agtfrom, agtto): # Moves the object with",
"f\"Push({parm1},{parm2})\" elif cmd == \"Pull\": # (agtfrom, agtto, boxfrom) parm1 = self.__getDir( state.actionPerformed[1][2],",
"is the color of the agent self.map[pos] = key self.agents[key] = [[pos, color]]",
"i) if actionParams is not None: return self.__PushEffect(*actionParams) else: return None def __PullPrec(self,",
"for direction in self.dir: for agtkey in self.agents: # TODO reformat these nested",
"str(agtto) + \" (row,col) is not free\") return None def __MoveEffect(self, agt, agtfrom,",
"= self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] ) cmd =",
"+ \" (row,col) is not free\") return None def __PushEffect(self, agt, boxkey, agtfrom,",
"objtype[obj][i][0] = pos else: return None def Free(self, pos): # checks if position",
"if self.Free(agtto): return (agt, boxkey, agtfrom, agtto, boxfrom, i) else: # # #",
"return None def Free(self, pos): # checks if position in map is free",
"0 agtfrom = self.getPos(self.agents, agt) if agtfrom is None: # # # print(\"agent\",",
"return False def __str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line) for line in self.map])",
"# print(\"Box\", boxkey, \"does not exist\") return None if agtdir not in self.dir:",
"child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed = [\"NoOp\", None] child._StateInit__addToExplored(children) for direction in self.dir:",
"Literals: def __init__(self, parent: \"Literals\" = None): # initializes the literals if parent",
"== chr(32) or self.map[pos].islower(): return True else: return False def Color(self, obj): pass",
"agt, \"does not exist\") return None if boxfrom is None: # # #",
"sets the position of an object # setPos(objecttype, the key, position, the index",
"parameters # Does not check preconditions self.setPos(self.agents, agt, agtto, 0) # agents are",
"agt # print(\"Agent \" + agt + \" is now at \" +",
"# # # print(\"agent\", agt, \"and box\", boxkey, \"are not neighbors\") return None",
"preconditions agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey, i) if agtfrom is",
"= None self.g = 0 self.t = 0 self.h = None self.f =",
"number and color is the color of the agent self.map[pos] = key self.agents[key]",
"behind and are not in the StateInit self.map[self.map == obj_key] = \"Ñ\" self.map[pos[0],",
"__ConcurrentEffect(self, t): \"\"\"Modify environment according to concurrent actions at time `t`.\"\"\" joint_concurrent =",
"get easy access to agents by color if color not in self.agentColor: self.agentColor[color]",
"+ str(agtto) + \" (row,col) is not free\") return None def __MoveEffect(self, agt,",
"be perhaps be optimized by only looking at boxes at the # neighboring",
"world. Something has changed given a concurrent action by another agent. \"\"\" return",
"i state.f = state.g + state.h state = state.prevState\"\"\" def __addPos(self, agtfrom, agtdir):",
"adds two positions together return tuple(map(operator.add, agtfrom, self.dir[agtdir])) def __getDir(self, agtfrom, agtto): #",
"# TODO reformat these nested loops and if statements! # This can be",
"is not None: self.map[pos[0], pos[1]] = obj_key else: # agents don't leave ghosts",
"for the env to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child =",
"if the preconditions are met # otherwise it returns 0 agtfrom = self.getPos(self.agents,",
"self.minimalRep() in self.explored def __addToExplored(self, children): # adds the state to the explored",
"with the given key # if key not in self.boxes: # return None",
"positions are neighbours, otherwise false if abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])",
"None: child = StateInit(self) child.actionPerformed = [\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a",
"parent.agentColor # rigid # TODO avoid deepcopies self.agents = copy.deepcopy(parent.agents) self.boxes = copy.deepcopy(parent.boxes)",
"False def advance(self) -> StateInit: \"\"\"Advance in time until the environment is changed",
"agtto) self.map[agtfrom] = chr(32) self.map[agtto] = agt # print(\"Agent \" + agt +",
"False return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes of the world.",
"format obj_group = \"agents\" if format.isnumeric() else \"boxes\" while state.actionPerformed is not None:",
"is not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd == \"Push\":",
"Color(self, obj): pass def Neighbour(self, pos1, pos2): # Returns true if the 2",
"return None if agtdir not in self.dir: # # # print(\"Direction\", agtdir, \"does",
"used by server while state.actionPerformed is not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd =",
"state is a goal state keys = self.getGoalKeys() for key in keys: goals",
"in boxes: if external_agent != external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0): #",
"(row,col) is not free\") return None def __PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto,",
"objtype: return objtype[obj][i][0] else: return None def setPos(self, objtype, obj, pos, i=0): #",
"None self.f = None self.explored = set() else: # if a parent is",
"def Color(self, obj): pass def Neighbour(self, pos1, pos2): # Returns true if the",
"and returns a list of children children = [] # Loop iterales through",
"if t > self.t] if future: return min(future) return False def advance(self) ->",
"if concurrent else parent.concurrent self.hunt_ghost() def __NoOpPrec(self): \"\"\"Evaluate precondition for NoOp. Agent can",
"possible it is appended to the the children actionParams = self.__MovePrec(agtkey, direction) if",
"= self.concurrent[t] for obj_key in joint_concurrent: pos, index = list(joint_concurrent[obj_key]) obj_group = \"agents\"",
"to a hashtable # key is a letter key = key.upper() self.map[pos] =",
"None: # # # print(\"Box\", boxkey, \"does not exist\") return None if boxdir",
"every possible action for direction in self.dir: for agtkey in self.agents: # TODO",
"pos is not None: self.map[pos[0], pos[1]] = obj_key else: # agents don't leave",
"boxes: if external_agent != external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj, i=0): # gets",
"__PushPrec(self, agt, boxkey, boxdir, i=0): # returns the movement parameters if the preconditions",
"initializes the state # it is (row, column) and not (x, y) super().__init__(parent)",
"goals = self.getGoalsByKey(key) for pos, color in goals: if self.map[pos] != key.upper(): return",
"# returns the minimal representation of the states return str([self.agents, self.boxes]) def isExplored(self):",
"self.__MoveEffect(*actionParams) else: return None def __PushPrec(self, agt, boxkey, boxdir, i=0): # returns the",
"def __getDir(self, agtfrom, agtto): # returns the direction the agent moved dir =",
"i=0): # returns the movement parameters if the preconditions are met # otherwise",
"copy.deepcopy(self) if format == 1: # format used by actions while state.actionPerformed is",
"pass def Neighbour(self, pos1, pos2): # Returns true if the 2 positions are",
"return False return True def __ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes of the",
"used to get easy access to agents by color if color not in",
"agtdir): # returns the movement parameters if the preconditions are met # otherwise",
"\" + str(boxto) + \" (row,col) is not free\") return None def __PushEffect(self,",
"# Does not check preconditions agtfrom = self.getPos(self.agents, agt) boxfrom = self.getPos(self.boxes, boxkey,",
"None: path.append(state.actionPerformed) state = state.prevState elif isinstance(format, str): # trace back an object",
"neighbors\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, boxkey, agtfrom,",
"returns all the keys return list(self.goals.keys()) def getAgentKeys(self): # returns all the keys",
"= chr(32) self.map[boxfrom] = agt self.map[boxto] = boxkey # print(\"Agent \" + agt",
"self.deltaPos = parent.deltaPos # rigid self.goals = parent.goals # rigid self.agentColor = parent.agentColor",
"child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push",
"not in self.dir: # # # print(\"Direction\", agtdir, \"does not exist\") return None",
"\"Literals\" = None): # initializes the state # it is (row, column) and",
"boxdir, i=0): # returns the movement parameters if the preconditions are met #",
"in self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key) def addGoal(self, key, pos, color=None): #",
"= total_cost + i state.f = state.g + state.h state = state.prevState\"\"\" def",
"pos1, pos2): # Returns true if the 2 positions are neighbours, otherwise false",
"server while state.actionPerformed is not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if",
"is chosen self.g = parent.g + 1 self.h = None self.f = None",
"self.dir = {\"N\": (-1, 0), \"E\": (0, 1), \"S\": (1, 0), \"W\": (0,",
"True def bestPath(self, format=0, index=0): # function returns the list of actions used",
"self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] = \" \" def deleteGoal(self, external_key): del self.goals[external_key]",
"+ f\" t={self.t}\" class StateInit(Literals): def __init__(self, parent: \"Literals\" = None): # initializes",
"boxfrom, boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4]",
"\"W\", } self.goals = {} # hashtable self.agentColor = {} # hashtable self.agents",
"to get easy access to agents by color if color not in self.agentColor:",
"None if boxdir not in self.dir: # # # print(\"Direction\", boxdir, \"does not",
"waits for the env to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child",
"the children actionParams = child_def._StateInit__PullPrec( agtkey, boxkey, direction, i ) if actionParams is",
"state.actionPerformed[1][2] ) cmd = f\"Move({parm1})\" elif cmd == \"NoOp\": cmd = \"NoOp\" path.append(cmd)",
"if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Push\", actionParams] child._StateInit__PushEffect(*actionParams)",
"with the given key return self.agentColor[color] def getBoxesByKey(self, key): key = key.upper() #",
"as np from utils import println class Literals: def __init__(self, parent: \"Literals\" =",
"boxto) parm1 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][3], state.actionPerformed[1][4] )",
"Preconditions to a NoOp is that the environment was changed by another agent;",
"None def __PushEffect(self, agt, boxkey, agtfrom, boxfrom, boxto, i): # Moves the objects",
"+ 1 self.explored = parent.explored super().__init__() def addMap(self, map2): # initialized a map",
"while state.actionPerformed is not None: # print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd",
"for agtkey in self.agents: # TODO reformat these nested loops and if statements!",
"# otherwise it returns 0 agtfrom = self.getPos(self.agents, agt) if agtfrom is None:",
"back an object looking_for = format obj_group = \"agents\" if format.isnumeric() else \"boxes\"",
"parent: StateInit concurrent: Dict Shared table that contains times where an object (box)",
"at boxes at # the neighboring tiles of the agent for boxkey in",
"has changed given a concurrent action by another agent. \"\"\" return self.t in",
"i) else: # # # print(\"Pos \" + str(agtto) + \" (row,col) is",
"actionParams = self.__PullPrec(agt, boxkey, boxdir, i) if actionParams is not None: return self.__PullEffect(*actionParams)",
"not exist\") return None agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, agtfrom,",
"to agents by color if color not in self.agentColor: self.agentColor[color] = [key] else:",
"pull action if it is possible it is appended to the the children",
"None: return self.__PullEffect(*actionParams) else: return None def minimalRep(self): # returns the minimal representation",
"index], ...}, ...} \"\"\" super().__init__(parent) self.concurrent = concurrent if concurrent else parent.concurrent self.hunt_ghost()",
"action is chosen self.g = parent.g + 1 self.h = None self.f =",
"+ \" (row,col)\") return True def Push(self, agt, boxkey, boxdir, i): # moves",
"= \"Ñ\" if pos is not None: self.map[pos[0], pos[1]] = obj_key else: #",
"= child_def._StateInit__PushPrec( agtkey, boxkey, direction, i ) if actionParams is not None: child",
"i=0): # Moves the object with the given parameters # Does not check",
"def keepJustBox(self, external_key): boxes = list(self.boxes.keys()) for external_agent in boxes: if external_agent !=",
"at \" + str(agtfrom) + \" (row,col)\") return True def Pull(self, agt, boxkey,",
"object with the given parameters # Does not check preconditions agtfrom = self.getPos(self.agents,",
"__MoveEffect(self, agt, agtfrom, agtto): # Moves the object with the given parameters #",
"access to agents by color if color not in self.agentColor: self.agentColor[color] = [key]",
"# returns true if it is free and false otherwise if self.map[pos] ==",
"self.map[pos] == chr(32) or self.map[pos].islower(): return True else: return False def Color(self, obj):",
"by color if color not in self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key) def",
"{\"N\": (-1, 0), \"E\": (0, 1), \"S\": (1, 0), \"W\": (0, -1)} self.deltaPos",
"import copy import operator from typing import Dict import numpy as np from",
"external_key): pos = self.getPos(self.boxes, external_key) del self.boxes[external_key] self.map[pos] = \" \" def deleteGoal(self,",
"thus 0 self.setPos(self.boxes, boxkey, agtfrom, i) self.map[boxfrom] = chr(32) self.map[agtfrom] = boxkey self.map[agtto]",
"the state is a goal state keys = self.getGoalKeys() for key in keys:",
"else: # format used by server while state.actionPerformed is not None: # print(state.actionPerformed,",
"self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom, boxto, i) else: #",
"NoOp children which just waits for the env to change # println(\"Applying NoOp\")",
"== 1: return True else: return False def __str__(self): # Debugging purposes return",
"it is (row, column) and not (x, y) super().__init__(parent) def getAgentsByKey(self, key): #",
"None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a",
"possible it is appended to the the children # Checks a Move action",
"possible it is appended to the the children actionParams = child_def._StateInit__MovePrec(agtkey, direction) if",
"TODO make a noop function child = StateInit(self) child.actionPerformed = [\"NoOp\", None] child.__addToExplored(children)",
"return self.boxes[key] def getGoalsByKey(self, key): key = key.lower() # same as getPos, just",
"agent agent_pos = self.getPos(self.agents, list(self.agents.keys())[0]) for pos, _ in joint_concurrent.values(): if pos is",
"# trace back an object looking_for = format obj_group = \"agents\" if format.isnumeric()",
"the next state is new and applies the concurrent changes to all children.",
"self.getPos(getattr(self, obj_group), obj_key, index) self.setPos(getattr(self, obj_group), obj_key, pos, index) # introduce a ghost",
"actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children) for agtkey in self.agents: # TODO make a noop function",
"keepJustAgent(self, external_key): ext_agents = list(self.agents.keys()) for external_agent in ext_agents: if external_agent != external_key:",
"false if abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) == 1: return True",
"None] child._StateInit__addToExplored(children) for direction in self.dir: for agtkey in self.agents: # TODO reformat",
"+ \" (row,col) is not free\") return None def __PullEffect(self, agt, boxkey, agtfrom,",
"direction) if actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Move\", actionParams]",
"\" + str(boxto) + \" (row,col)\") # print(\"Box \" + str(box) + \"",
"if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams)",
"actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed = [\"Move\", actionParams] child._StateInit__MoveEffect(*actionParams) child._StateInit__addToExplored(children)",
"= key.upper() self.map[pos] = key if key not in self.boxes: self.boxes[key] = [[pos,",
"initializes the literals if parent is None: # if no parent is present!",
"None def minimalRep(self): # returns the minimal representation of the states return str([self.agents,",
"agtkey in self.agents: # TODO make a noop function child = StateInit(self) child.actionPerformed",
"not exist\") return None if boxdir not in self.dir: # # # print(\"Direction\",",
"\" + str(box) + \" is now at \" + str(agtfrom) + \"",
"[\"Push\", actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push action if it is possible",
"is None: # if no parent is present! self.dir = {\"N\": (-1, 0),",
"\" + agt + \" is now at \" + str(agtto) + \"",
"hashtable self.agentColor = {} # hashtable self.agents = {} # hashtable self.boxes =",
"self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored = set() def deleteAgent(self, external_key):",
"self.f = None self.t = parent.t + 1 self.explored = parent.explored super().__init__() def",
"= self.boxes[boxkey][i][1] # [agent letter][agent number (0 since it is unique)][color] if self.agents[agtkey][0][1]",
"agtto = self.__addPos(agtfrom, agtdir) if self.Free(agtto): return (agt, agtfrom, agtto) else: # #",
"position in map is free # returns true if it is free and",
"return \"\\n\".join([\"\".join(line) for line in self.map]) + f\" t={self.t}\" class StateInit(Literals): def __init__(self,",
"key = key.upper() self.map[pos] = key if key not in self.boxes: self.boxes[key] =",
"the children actionParams = self.__MovePrec(agtkey, direction) if actionParams is not None: child =",
"only used to get easy access to agents by color if color not",
"child.__addToExplored(children) for agtkey in self.agents: # TODO make a noop function child =",
"print(\"Pos \" + str(agtto) + \" (row,col) is not free\") return None def",
"# key is a letter key = key.upper() self.map[pos] = key if key",
"in self.concurrent: joint_concurrent = self.concurrent[t] # a state that it is being solved",
"just waits for the env to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec():",
"is unique)][color] if self.agents[agtkey][0][1] == boxcolor: # Checks a pull action if it",
"\" (row,col) is not free\") return None def __MoveEffect(self, agt, agtfrom, agtto): #",
"by by strategy. \"\"\" future = [t for t in self.concurrent if t",
"the explored list if not self.isExplored(): self.explored.add(self.minimalRep()) children.append(self) def isGoalState(self): # checks if",
"= {\"N\": (-1, 0), \"E\": (0, 1), \"S\": (1, 0), \"W\": (0, -1)}",
"# [agent letter][agent number (0 since it is unique)][color] if self.agents[agtkey][0][1] == boxcolor:",
"boxdir) if self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom, boxto, i) else: # #",
"a map with only walls self.map = np.array(map2) def addAgent(self, key, pos, color=\"c\"):",
"= chr(32) self.map[agtfrom] = boxkey self.map[agtto] = agt # print(\"Agent \" + agt",
"agtfrom[1]) return self.deltaPos[dir] def __MovePrec(self, agt, agtdir): # returns the movement parameters if",
"else \"boxes\" while state.actionPerformed is not None: path.append( [ state.t, state.getPos(getattr(state, obj_group), looking_for,",
"== boxcolor: # Checks a pull action if it is possible it is",
"# print(\"Direction\", agtdir, \"does not exist\") return None if self.Neighbour(agtfrom, boxfrom) != 1:",
"# function returns the list of actions used to reach the state path",
"since it is unique)][color] if self.agents[agtkey][0][1] == boxcolor: # Checks a pull action",
"== tuple: objtype[obj][i][0] = pos else: return None def Free(self, pos): # checks",
"for external_agent in boxes: if external_agent != external_key: self.deleteBox(external_agent) def getPos(self, objtype, obj,",
"else: return False def __str__(self): # Debugging purposes return \"\\n\".join([\"\".join(line) for line in",
"state # it is (row, column) and not (x, y) super().__init__(parent) def getAgentsByKey(self,",
"None def __MoveEffect(self, agt, agtfrom, agtto): # Moves the object with the given",
"gets defined when action is chosen self.g = parent.g + 1 self.h =",
"__ConcurrentPrec(self): \"\"\"Evaluate precondition for concurrent changes of the world. Something has changed given",
"= self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][3] ) parm2 = self.__getDir( state.actionPerformed[1][2], state.actionPerformed[1][4] ) cmd =",
"not in self.agents: # return None return self.agents[key] def getAgentsByColor(self, color): # same",
"iterales through every possible action for direction in self.dir: for agtkey in self.agents:",
"that contains times where an object (box) in the environment has been changed",
"state.g + state.h state = state.prevState\"\"\" def __addPos(self, agtfrom, agtdir): # simply adds",
"\" is now at \" + str(agtfrom) + \" (row,col)\") return True def",
"child._StateInit__addToExplored(children) return children def AdvancePrec(self): \"\"\"Is there some concurrent change in the future.",
"= self.__addPos(boxfrom, boxdir) if self.Free(boxto): return (agt, boxkey, agtfrom, boxfrom, boxto, i) else:",
"self.__PushPrec(agtkey, boxkey, direction, i) if actionParams is not None: child = StateInit(self) child.actionPerformed",
"index), ] ) state = state.prevState else: # format used by server while",
"by strategy. \"\"\" future = [t for t in self.concurrent if t >",
"self.__PushPrec(agt, boxkey, boxdir, i) if actionParams is not None: return self.__PushEffect(*actionParams) else: return",
"`map` and `agent_color`.\"\"\" pos = self.getPos(self.agents, external_key) del self.agents[external_key] self.map[pos] = \" \"",
"i) if actionParams is not None: return self.__PullEffect(*actionParams) else: return None def minimalRep(self):",
"actions at time `t`.\"\"\" joint_concurrent = self.concurrent[t] for obj_key in joint_concurrent: pos, index",
"change in the future. It will be called by by strategy. \"\"\" future",
"# a NoOp children which just waits for the env to change #",
"used to reach the state path = [] state = copy.deepcopy(self) if format",
"the literals if parent is None: # if no parent is present! self.dir",
"return self.deltaPos[dir] def __MovePrec(self, agt, agtdir): # returns the movement parameters if the",
"check preconditions self.setPos(self.agents, agt, agtto, 0) # agents are unique thus 0 self.setPos(self.boxes,",
"= self.__PushPrec(agtkey, boxkey, direction, i) if actionParams is not None: child = StateInit(self)",
"print(state.actionPerformed, state.actionPerformed[0]) cmd = state.actionPerformed[0] if cmd == \"Push\": # (agtfrom, boxfrom, boxto)",
"goal state keys = self.getGoalKeys() for key in keys: goals = self.getGoalsByKey(key) for",
"object looking_for = format obj_group = \"agents\" if format.isnumeric() else \"boxes\" while state.actionPerformed",
"for line in self.map]) + f\" t={self.t}\" class StateInit(Literals): def __init__(self, parent: \"Literals\"",
"appended to the the children # Checks a Move action if it is",
"color not in self.agentColor: self.agentColor[color] = [key] else: self.agentColor[color].append(key) def addGoal(self, key, pos,",
"boxkey, direction, i ) if actionParams is not None: child = copy.deepcopy(child_def) child.actionPerformed",
"[\"Pull\", actionParams] child._StateInit__PullEffect(*actionParams) child._StateInit__addToExplored(children) # Checks a Push action if it is possible",
"precondition for NoOp. Agent can stay at his position without doing anything. \"\"\"",
"self.explored = parent.explored super().__init__() def addMap(self, map2): # initialized a map with only",
"parent.deltaPos # rigid self.goals = parent.goals # rigid self.agentColor = parent.agentColor # rigid",
"not None: return self.__MoveEffect(*actionParams) else: return None def __PushPrec(self, agt, boxkey, boxdir, i=0):",
"if it is possible it is appended to the the children # Checks",
"NoOp. Agent can stay at his position without doing anything. \"\"\" return self.__WaitPrec_t(self.t)",
"== \"NoOp\": cmd = \"NoOp\" path.append(cmd) state = state.prevState # Reverse the order",
"the direction the agent moved dir = (agtto[0] - agtfrom[0], agtto[1] - agtfrom[1])",
"= boxkey # print(\"Agent \" + agt + \" is now at \"",
"returns true if it is free and false otherwise if self.map[pos] == chr(32)",
"actionParams] child.__PushEffect(*actionParams) child.__addToExplored(children) # Checks a Push action if it is possible it",
"StateInit = None, concurrent: Dict = None): \"\"\"Initialize by adding a time table",
"return True def Move(self, agt, agtdir): # moves the object in the given",
"true if the 2 positions are neighbours, otherwise false if abs(pos1[0] - pos2[0])",
"= agt self.map[boxto] = boxkey # print(\"Agent \" + agt + \" is",
"== 1: # format used by actions while state.actionPerformed is not None: path.append(state.actionPerformed)",
"boxkey in self.boxes: for i in range(len(self.boxes[boxkey])): boxcolor = self.boxes[boxkey][i][1] # [agent letter][agent",
"self.boxes = copy.deepcopy(parent.boxes) self.map = parent.map.copy() self.prevState = parent # reference to previous",
"actionParams is not None: child = StateInit(self) child.actionPerformed = [\"Move\", actionParams] child.__MoveEffect(*actionParams) child.__addToExplored(children)",
"external_key): ext_agents = list(self.agents.keys()) for external_agent in ext_agents: if external_agent != external_key: self.deleteAgent(external_agent)",
"in ext_goals: if external_goal != external_key: self.deleteGoal(external_goal) def keepJustBox(self, external_key): boxes = list(self.boxes.keys())",
"env to change # println(\"Applying NoOp\") child_def.__ConcurrentEffect(child_def.t) if child_def.__NoOpPrec(): child = copy.deepcopy(child_def) child.actionPerformed",
"in ext_agents: if external_agent != external_key: self.deleteAgent(external_agent) def keepJustGoal(self, external_key): ext_goals = list(self.goals.keys())",
"agent.\"\"\" next_time = self.AdvancePrec() if not next_time: return self future_self = self while",
"self.boxes[key] = [[pos, color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored",
"(0, -1): \"W\", } self.goals = {} # hashtable self.agentColor = {} #",
"getBoxesByKey(self, key): key = key.upper() # same as getPos, just for all Boxes",
"+ str(agtto) + \" (row,col) is not free\") return None def __PullEffect(self, agt,",
"pos else: return None def Free(self, pos): # checks if position in map",
"= [[pos, color]] else: self.boxes[key].append([pos, color]) def forget_exploration(self): \"\"\"Remove explored nodes.\"\"\" self.explored =",
"table to the usual `StateInit`. Parameters ---------- parent: StateInit concurrent: Dict Shared table"
] |
[
"100]] # def forward(self, x): # logits = self.model(x) # y = logits.argmax(-1)",
"torch.nn as nn class Normalize(nn.Module): def __init__(self, mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean',",
"the desired colors (H, S, L) # WHITE = [[0, 0, 95], [360,",
"# self.model = model # self.color_dict = { # 'circle-750.0': ['white', 'blue', 'red'],",
"mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None, :,",
"'triangle-900.0': ['white', 'yellow'], # (1) white, (2) yellow # 'triangle_inverted-1220.0': [], # (1)",
"(x - self.mean) / self.std # class ColorDetectorWrapper(nn.Module): # def __init__(self, model): #",
"(1) white # 'pentagon-915.0': 13, # (1) yellow # 'octagon-915.0': 14, # (1)",
"(2) white # 'rect-762.0-915.0': [], # (1) white # 'rect-915.0-1220.0': [], # (1)",
"yellow # 'triangle_inverted-1220.0': 5, # (1) white+red # 'diamond-600.0': 6, # (1) white+yellow",
"# (1) yellow # 'square-600.0': 8, # (1) blue # 'rect-458.0-610.0': 9, #",
"(1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': 11, # (1) white #",
"'rect-762.0-915.0': 11, # (1) white # 'rect-915.0-1220.0': 12, # (1) white # 'pentagon-915.0':",
"(1) white # 'rect-915.0-1220.0': 12, # (1) white # 'pentagon-915.0': 13, # (1)",
"[], # (1) white # 'rect-915.0-1220.0': [], # (1) white # 'pentagon-915.0': [],",
"x): # logits = self.model(x) # y = logits.argmax(-1) # # Change image",
"to HSL color space # # Count pixels that satisfy the color range",
"(1) red # 'other': [], # } # self.class_list = list(self.color_dict.keys()) # self.class_idx",
"(1) yellow # 'square-600.0': [], # (1) blue # 'rect-458.0-610.0': ['white', 'other'], #",
"of the desired colors (H, S, L) # WHITE = [[0, 0, 95],",
"*args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None])",
"return (x - self.mean) / self.std # class ColorDetectorWrapper(nn.Module): # def __init__(self, model):",
"Change image to HSL color space # # Count pixels that satisfy the",
"def __init__(self, mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std',",
"'diamond-915.0': [], # (1) yellow # 'square-600.0': [], # (1) blue # 'rect-458.0-610.0':",
"(1) white+yellow # 'diamond-915.0': 7, # (1) yellow # 'square-600.0': 8, # (1)",
"white+red # 'diamond-600.0': 6, # (1) white+yellow # 'diamond-915.0': 7, # (1) yellow",
"logits = self.model(x) # y = logits.argmax(-1) # # Change image to HSL",
"= { # 'circle-750.0': ['white', 'blue', 'red'], # (1) white+red, (2) blue+white #",
"super().__init__() # self.model = model # self.color_dict = { # 'circle-750.0': ['white', 'blue',",
"[[0, 0, 95], [360, 360, 100]] # def forward(self, x): # logits =",
"(2) blue+white # 'triangle-900.0': ['white', 'yellow'], # (1) white, (2) yellow # 'triangle_inverted-1220.0':",
"__init__(self, mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None,",
"import forward import torch import torch.nn as nn class Normalize(nn.Module): def __init__(self, mean,",
"blue+white # 'triangle-900.0': ['white', 'yellow'], # (1) white, (2) yellow # 'triangle_inverted-1220.0': [],",
"(2) yellow # 'triangle_inverted-1220.0': [], # (1) white+red # 'diamond-600.0': [], # (1)",
"# 'diamond-915.0': [], # (1) yellow # 'square-600.0': [], # (1) blue #",
"# 'square-600.0': 8, # (1) blue # 'rect-458.0-610.0': 9, # (1) chevron (also",
"self.color_dict = { # 'circle-750.0': ['white', 'blue', 'red'], # (1) white+red, (2) blue+white",
"# (1) white+red, (2) blue+white # 'triangle-900.0': ['white', 'yellow'], # (1) white, (2)",
"white # 'rect-915.0-1220.0': [], # (1) white # 'pentagon-915.0': [], # (1) yellow",
"# 'other': [], # } # self.class_list = list(self.color_dict.keys()) # self.class_idx = {",
"**kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def",
"11, # (1) white # 'rect-915.0-1220.0': 12, # (1) white # 'pentagon-915.0': 13,",
"blue # 'rect-458.0-610.0': ['white', 'other'], # (1) chevron (also multi-color), (2) white #",
"super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def forward(self,",
"['white', 'blue', 'red'], # (1) white+red, (2) blue+white # 'triangle-900.0': ['white', 'yellow'], #",
"white+red, (2) blue+white # 'triangle-900.0': 3, # (1) white, (2) yellow # 'triangle_inverted-1220.0':",
":, None, None]) def forward(self, x): return (x - self.mean) / self.std #",
"blue+white # 'triangle-900.0': 3, # (1) white, (2) yellow # 'triangle_inverted-1220.0': 5, #",
"image to HSL color space # # Count pixels that satisfy the color",
"self.model = model # self.color_dict = { # 'circle-750.0': ['white', 'blue', 'red'], #",
"(1) yellow # 'octagon-915.0': [], # (1) red # 'other': [], # }",
"list(self.color_dict.keys()) # self.class_idx = { # 'circle-750.0': 0, # (1) white+red, (2) blue+white",
"model # self.color_dict = { # 'circle-750.0': ['white', 'blue', 'red'], # (1) white+red,",
"# 'rect-762.0-915.0': [], # (1) white # 'rect-915.0-1220.0': [], # (1) white #",
"# (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': 11, # (1) white",
"# 'rect-762.0-915.0': 11, # (1) white # 'rect-915.0-1220.0': 12, # (1) white #",
"(also multi-color), (2) white # 'rect-762.0-915.0': 11, # (1) white # 'rect-915.0-1220.0': 12,",
"'pentagon-915.0': [], # (1) yellow # 'octagon-915.0': [], # (1) red # 'other':",
"self.mean) / self.std # class ColorDetectorWrapper(nn.Module): # def __init__(self, model): # super().__init__() #",
"'square-600.0': 8, # (1) blue # 'rect-458.0-610.0': 9, # (1) chevron (also multi-color),",
"# # Change image to HSL color space # # Count pixels that",
"white # 'pentagon-915.0': 13, # (1) yellow # 'octagon-915.0': 14, # (1) red",
"(1) blue # 'rect-458.0-610.0': ['white', 'other'], # (1) chevron (also multi-color), (2) white",
"360, 100]] # def forward(self, x): # logits = self.model(x) # y =",
"white+yellow # 'diamond-915.0': 7, # (1) yellow # 'square-600.0': 8, # (1) blue",
"yellow # 'octagon-915.0': [], # (1) red # 'other': [], # } #",
"# (1) white+yellow # 'diamond-915.0': 7, # (1) yellow # 'square-600.0': 8, #",
"'diamond-915.0': 7, # (1) yellow # 'square-600.0': 8, # (1) blue # 'rect-458.0-610.0':",
"(1) white+red # 'diamond-600.0': 6, # (1) white+yellow # 'diamond-915.0': 7, # (1)",
"8, # (1) blue # 'rect-458.0-610.0': 9, # (1) chevron (also multi-color), (2)",
"# (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': [], # (1) white",
"0, 95], [360, 360, 100]] # def forward(self, x): # logits = self.model(x)",
"chevron (also multi-color), (2) white # 'rect-762.0-915.0': [], # (1) white # 'rect-915.0-1220.0':",
"# (1) white # 'rect-915.0-1220.0': 12, # (1) white # 'pentagon-915.0': 13, #",
"range of the desired colors (H, S, L) # WHITE = [[0, 0,",
"blue # 'rect-458.0-610.0': 9, # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0':",
"# logits = self.model(x) # y = logits.argmax(-1) # # Change image to",
"= model # self.color_dict = { # 'circle-750.0': ['white', 'blue', 'red'], # (1)",
"'yellow'], # (1) white, (2) yellow # 'triangle_inverted-1220.0': [], # (1) white+red #",
"'octagon-915.0': [], # (1) red # 'other': [], # } # self.class_list =",
"'triangle_inverted-1220.0': 5, # (1) white+red # 'diamond-600.0': 6, # (1) white+yellow # 'diamond-915.0':",
"95], [360, 360, 100]] # def forward(self, x): # logits = self.model(x) #",
"# 'other': 15, # } # # Define HSV range of the desired",
"None]) def forward(self, x): return (x - self.mean) / self.std # class ColorDetectorWrapper(nn.Module):",
"0, # (1) white+red, (2) blue+white # 'triangle-900.0': 3, # (1) white, (2)",
"# (1) white, (2) yellow # 'triangle_inverted-1220.0': 5, # (1) white+red # 'diamond-600.0':",
"nn class Normalize(nn.Module): def __init__(self, mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :,",
"12, # (1) white # 'pentagon-915.0': 13, # (1) yellow # 'octagon-915.0': 14,",
"[360, 360, 100]] # def forward(self, x): # logits = self.model(x) # y",
"= logits.argmax(-1) # # Change image to HSL color space # # Count",
"# 'rect-915.0-1220.0': 12, # (1) white # 'pentagon-915.0': 13, # (1) yellow #",
"white # 'rect-762.0-915.0': [], # (1) white # 'rect-915.0-1220.0': [], # (1) white",
"torch.tensor(std)[None, :, None, None]) def forward(self, x): return (x - self.mean) / self.std",
"# 'octagon-915.0': 14, # (1) red # 'other': 15, # } # #",
"['white', 'other'], # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': [], #",
"6, # (1) white+yellow # 'diamond-915.0': 7, # (1) yellow # 'square-600.0': 8,",
"# 'diamond-600.0': [], # (1) white+yellow # 'diamond-915.0': [], # (1) yellow #",
"white+yellow # 'diamond-915.0': [], # (1) yellow # 'square-600.0': [], # (1) blue",
"7, # (1) yellow # 'square-600.0': 8, # (1) blue # 'rect-458.0-610.0': 9,",
"yellow # 'square-600.0': [], # (1) blue # 'rect-458.0-610.0': ['white', 'other'], # (1)",
"self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def forward(self, x): return (x - self.mean) /",
"(1) yellow # 'octagon-915.0': 14, # (1) red # 'other': 15, # }",
"# (1) white, (2) yellow # 'triangle_inverted-1220.0': [], # (1) white+red # 'diamond-600.0':",
"HSV range of the desired colors (H, S, L) # WHITE = [[0,",
"chevron (also multi-color), (2) white # 'rect-762.0-915.0': 11, # (1) white # 'rect-915.0-1220.0':",
"import torch.nn as nn class Normalize(nn.Module): def __init__(self, mean, std, *args, **kwargs): super().__init__()",
"# (1) yellow # 'octagon-915.0': 14, # (1) red # 'other': 15, #",
"} # self.class_list = list(self.color_dict.keys()) # self.class_idx = { # 'circle-750.0': 0, #",
"'rect-458.0-610.0': 9, # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': 11, #",
"/ self.std # class ColorDetectorWrapper(nn.Module): # def __init__(self, model): # super().__init__() # self.model",
"# (1) white+yellow # 'diamond-915.0': [], # (1) yellow # 'square-600.0': [], #",
"# (1) white # 'rect-915.0-1220.0': [], # (1) white # 'pentagon-915.0': [], #",
"as nn class Normalize(nn.Module): def __init__(self, mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None,",
"[], # (1) white+yellow # 'diamond-915.0': [], # (1) yellow # 'square-600.0': [],",
"# 'rect-458.0-610.0': ['white', 'other'], # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0':",
"std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None,",
"[], # (1) yellow # 'square-600.0': [], # (1) blue # 'rect-458.0-610.0': ['white',",
"[], # (1) yellow # 'octagon-915.0': [], # (1) red # 'other': [],",
"self.class_list = list(self.color_dict.keys()) # self.class_idx = { # 'circle-750.0': 0, # (1) white+red,",
"# (1) white+red # 'diamond-600.0': 6, # (1) white+yellow # 'diamond-915.0': 7, #",
"[], # (1) white+red # 'diamond-600.0': [], # (1) white+yellow # 'diamond-915.0': [],",
"(1) white+red # 'diamond-600.0': [], # (1) white+yellow # 'diamond-915.0': [], # (1)",
"(1) white, (2) yellow # 'triangle_inverted-1220.0': 5, # (1) white+red # 'diamond-600.0': 6,",
"turtle import forward import torch import torch.nn as nn class Normalize(nn.Module): def __init__(self,",
"yellow # 'octagon-915.0': 14, # (1) red # 'other': 15, # } #",
"# # Define HSV range of the desired colors (H, S, L) #",
"# 'circle-750.0': 0, # (1) white+red, (2) blue+white # 'triangle-900.0': 3, # (1)",
"'other'], # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': [], # (1)",
"class ColorDetectorWrapper(nn.Module): # def __init__(self, model): # super().__init__() # self.model = model #",
"white # 'pentagon-915.0': [], # (1) yellow # 'octagon-915.0': [], # (1) red",
"# 'triangle-900.0': ['white', 'yellow'], # (1) white, (2) yellow # 'triangle_inverted-1220.0': [], #",
"forward(self, x): # logits = self.model(x) # y = logits.argmax(-1) # # Change",
"self.class_idx = { # 'circle-750.0': 0, # (1) white+red, (2) blue+white # 'triangle-900.0':",
"15, # } # # Define HSV range of the desired colors (H,",
"= self.model(x) # y = logits.argmax(-1) # # Change image to HSL color",
"# 'diamond-915.0': 7, # (1) yellow # 'square-600.0': 8, # (1) blue #",
"model): # super().__init__() # self.model = model # self.color_dict = { # 'circle-750.0':",
"= [[0, 0, 95], [360, 360, 100]] # def forward(self, x): # logits",
"self.register_buffer('mean', torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def forward(self, x):",
"None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def forward(self, x): return (x - self.mean)",
"# super().__init__() # self.model = model # self.color_dict = { # 'circle-750.0': ['white',",
"white # 'rect-762.0-915.0': 11, # (1) white # 'rect-915.0-1220.0': 12, # (1) white",
"[], # } # self.class_list = list(self.color_dict.keys()) # self.class_idx = { # 'circle-750.0':",
"'pentagon-915.0': 13, # (1) yellow # 'octagon-915.0': 14, # (1) red # 'other':",
"# (1) blue # 'rect-458.0-610.0': ['white', 'other'], # (1) chevron (also multi-color), (2)",
"# 'octagon-915.0': [], # (1) red # 'other': [], # } # self.class_list",
":, None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def forward(self, x): return (x",
"# (1) yellow # 'octagon-915.0': [], # (1) red # 'other': [], #",
"'other': [], # } # self.class_list = list(self.color_dict.keys()) # self.class_idx = { #",
"# self.class_list = list(self.color_dict.keys()) # self.class_idx = { # 'circle-750.0': 0, # (1)",
"# 'triangle_inverted-1220.0': [], # (1) white+red # 'diamond-600.0': [], # (1) white+yellow #",
"'blue', 'red'], # (1) white+red, (2) blue+white # 'triangle-900.0': ['white', 'yellow'], # (1)",
"5, # (1) white+red # 'diamond-600.0': 6, # (1) white+yellow # 'diamond-915.0': 7,",
"forward(self, x): return (x - self.mean) / self.std # class ColorDetectorWrapper(nn.Module): # def",
"# } # self.class_list = list(self.color_dict.keys()) # self.class_idx = { # 'circle-750.0': 0,",
"def forward(self, x): return (x - self.mean) / self.std # class ColorDetectorWrapper(nn.Module): #",
"(1) red # 'other': 15, # } # # Define HSV range of",
"S, L) # WHITE = [[0, 0, 95], [360, 360, 100]] # def",
"y = logits.argmax(-1) # # Change image to HSL color space # #",
"(1) white+red, (2) blue+white # 'triangle-900.0': 3, # (1) white, (2) yellow #",
"# def __init__(self, model): # super().__init__() # self.model = model # self.color_dict =",
"'rect-915.0-1220.0': 12, # (1) white # 'pentagon-915.0': 13, # (1) yellow # 'octagon-915.0':",
"'other': 15, # } # # Define HSV range of the desired colors",
"# (1) white+red, (2) blue+white # 'triangle-900.0': 3, # (1) white, (2) yellow",
"9, # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': 11, # (1)",
"# self.color_dict = { # 'circle-750.0': ['white', 'blue', 'red'], # (1) white+red, (2)",
"[], # (1) blue # 'rect-458.0-610.0': ['white', 'other'], # (1) chevron (also multi-color),",
"# (1) white # 'pentagon-915.0': [], # (1) yellow # 'octagon-915.0': [], #",
"# (1) red # 'other': 15, # } # # Define HSV range",
"from turtle import forward import torch import torch.nn as nn class Normalize(nn.Module): def",
"(1) white, (2) yellow # 'triangle_inverted-1220.0': [], # (1) white+red # 'diamond-600.0': [],",
"# (1) yellow # 'square-600.0': [], # (1) blue # 'rect-458.0-610.0': ['white', 'other'],",
"[], # (1) white # 'pentagon-915.0': [], # (1) yellow # 'octagon-915.0': [],",
"# 'pentagon-915.0': 13, # (1) yellow # 'octagon-915.0': 14, # (1) red #",
"= list(self.color_dict.keys()) # self.class_idx = { # 'circle-750.0': 0, # (1) white+red, (2)",
"- self.mean) / self.std # class ColorDetectorWrapper(nn.Module): # def __init__(self, model): # super().__init__()",
"['white', 'yellow'], # (1) white, (2) yellow # 'triangle_inverted-1220.0': [], # (1) white+red",
"white, (2) yellow # 'triangle_inverted-1220.0': [], # (1) white+red # 'diamond-600.0': [], #",
"None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def forward(self, x): return (x -",
"torch import torch.nn as nn class Normalize(nn.Module): def __init__(self, mean, std, *args, **kwargs):",
"# self.class_idx = { # 'circle-750.0': 0, # (1) white+red, (2) blue+white #",
"white, (2) yellow # 'triangle_inverted-1220.0': 5, # (1) white+red # 'diamond-600.0': 6, #",
"Define HSV range of the desired colors (H, S, L) # WHITE =",
"white+red, (2) blue+white # 'triangle-900.0': ['white', 'yellow'], # (1) white, (2) yellow #",
"L) # WHITE = [[0, 0, 95], [360, 360, 100]] # def forward(self,",
"# WHITE = [[0, 0, 95], [360, 360, 100]] # def forward(self, x):",
"WHITE = [[0, 0, 95], [360, 360, 100]] # def forward(self, x): #",
"class Normalize(nn.Module): def __init__(self, mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None,",
"colors (H, S, L) # WHITE = [[0, 0, 95], [360, 360, 100]]",
"def __init__(self, model): # super().__init__() # self.model = model # self.color_dict = {",
"(also multi-color), (2) white # 'rect-762.0-915.0': [], # (1) white # 'rect-915.0-1220.0': [],",
"multi-color), (2) white # 'rect-762.0-915.0': 11, # (1) white # 'rect-915.0-1220.0': 12, #",
"self.model(x) # y = logits.argmax(-1) # # Change image to HSL color space",
"(1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': [], # (1) white #",
"red # 'other': [], # } # self.class_list = list(self.color_dict.keys()) # self.class_idx =",
"white # 'rect-915.0-1220.0': 12, # (1) white # 'pentagon-915.0': 13, # (1) yellow",
"forward import torch import torch.nn as nn class Normalize(nn.Module): def __init__(self, mean, std,",
"# Change image to HSL color space # # Count pixels that satisfy",
"3, # (1) white, (2) yellow # 'triangle_inverted-1220.0': 5, # (1) white+red #",
"# } # # Define HSV range of the desired colors (H, S,",
"(2) blue+white # 'triangle-900.0': 3, # (1) white, (2) yellow # 'triangle_inverted-1220.0': 5,",
"# 'diamond-600.0': 6, # (1) white+yellow # 'diamond-915.0': 7, # (1) yellow #",
"# 'rect-458.0-610.0': 9, # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': 11,",
"'square-600.0': [], # (1) blue # 'rect-458.0-610.0': ['white', 'other'], # (1) chevron (also",
"'circle-750.0': ['white', 'blue', 'red'], # (1) white+red, (2) blue+white # 'triangle-900.0': ['white', 'yellow'],",
"'rect-458.0-610.0': ['white', 'other'], # (1) chevron (also multi-color), (2) white # 'rect-762.0-915.0': [],",
"'circle-750.0': 0, # (1) white+red, (2) blue+white # 'triangle-900.0': 3, # (1) white,",
"(1) white # 'pentagon-915.0': [], # (1) yellow # 'octagon-915.0': [], # (1)",
"# (1) blue # 'rect-458.0-610.0': 9, # (1) chevron (also multi-color), (2) white",
"torch.tensor(mean)[None, :, None, None]) self.register_buffer('std', torch.tensor(std)[None, :, None, None]) def forward(self, x): return",
"# (1) white # 'pentagon-915.0': 13, # (1) yellow # 'octagon-915.0': 14, #",
"desired colors (H, S, L) # WHITE = [[0, 0, 95], [360, 360,",
"(1) yellow # 'square-600.0': 8, # (1) blue # 'rect-458.0-610.0': 9, # (1)",
"'triangle-900.0': 3, # (1) white, (2) yellow # 'triangle_inverted-1220.0': 5, # (1) white+red",
"(1) white+red, (2) blue+white # 'triangle-900.0': ['white', 'yellow'], # (1) white, (2) yellow",
"# 'pentagon-915.0': [], # (1) yellow # 'octagon-915.0': [], # (1) red #",
"# (1) white+red # 'diamond-600.0': [], # (1) white+yellow # 'diamond-915.0': [], #",
"'octagon-915.0': 14, # (1) red # 'other': 15, # } # # Define",
"'rect-915.0-1220.0': [], # (1) white # 'pentagon-915.0': [], # (1) yellow # 'octagon-915.0':",
"# Define HSV range of the desired colors (H, S, L) # WHITE",
"__init__(self, model): # super().__init__() # self.model = model # self.color_dict = { #",
"None, None]) def forward(self, x): return (x - self.mean) / self.std # class",
"# class ColorDetectorWrapper(nn.Module): # def __init__(self, model): # super().__init__() # self.model = model",
"'triangle_inverted-1220.0': [], # (1) white+red # 'diamond-600.0': [], # (1) white+yellow # 'diamond-915.0':",
"{ # 'circle-750.0': 0, # (1) white+red, (2) blue+white # 'triangle-900.0': 3, #",
"def forward(self, x): # logits = self.model(x) # y = logits.argmax(-1) # #",
"'rect-762.0-915.0': [], # (1) white # 'rect-915.0-1220.0': [], # (1) white # 'pentagon-915.0':",
"(1) blue # 'rect-458.0-610.0': 9, # (1) chevron (also multi-color), (2) white #",
"# y = logits.argmax(-1) # # Change image to HSL color space #",
"Normalize(nn.Module): def __init__(self, mean, std, *args, **kwargs): super().__init__() self.register_buffer('mean', torch.tensor(mean)[None, :, None, None])",
"white+red # 'diamond-600.0': [], # (1) white+yellow # 'diamond-915.0': [], # (1) yellow",
"# 'triangle-900.0': 3, # (1) white, (2) yellow # 'triangle_inverted-1220.0': 5, # (1)",
"'red'], # (1) white+red, (2) blue+white # 'triangle-900.0': ['white', 'yellow'], # (1) white,",
"(2) yellow # 'triangle_inverted-1220.0': 5, # (1) white+red # 'diamond-600.0': 6, # (1)",
"yellow # 'square-600.0': 8, # (1) blue # 'rect-458.0-610.0': 9, # (1) chevron",
"} # # Define HSV range of the desired colors (H, S, L)",
"# 'rect-915.0-1220.0': [], # (1) white # 'pentagon-915.0': [], # (1) yellow #",
"self.std # class ColorDetectorWrapper(nn.Module): # def __init__(self, model): # super().__init__() # self.model =",
"(1) white+yellow # 'diamond-915.0': [], # (1) yellow # 'square-600.0': [], # (1)",
"[], # (1) red # 'other': [], # } # self.class_list = list(self.color_dict.keys())",
"red # 'other': 15, # } # # Define HSV range of the",
"logits.argmax(-1) # # Change image to HSL color space # # Count pixels",
"import torch import torch.nn as nn class Normalize(nn.Module): def __init__(self, mean, std, *args,",
"'diamond-600.0': 6, # (1) white+yellow # 'diamond-915.0': 7, # (1) yellow # 'square-600.0':",
"ColorDetectorWrapper(nn.Module): # def __init__(self, model): # super().__init__() # self.model = model # self.color_dict",
"# 'circle-750.0': ['white', 'blue', 'red'], # (1) white+red, (2) blue+white # 'triangle-900.0': ['white',",
"x): return (x - self.mean) / self.std # class ColorDetectorWrapper(nn.Module): # def __init__(self,",
"'diamond-600.0': [], # (1) white+yellow # 'diamond-915.0': [], # (1) yellow # 'square-600.0':",
"# 'triangle_inverted-1220.0': 5, # (1) white+red # 'diamond-600.0': 6, # (1) white+yellow #",
"14, # (1) red # 'other': 15, # } # # Define HSV",
"multi-color), (2) white # 'rect-762.0-915.0': [], # (1) white # 'rect-915.0-1220.0': [], #",
"yellow # 'triangle_inverted-1220.0': [], # (1) white+red # 'diamond-600.0': [], # (1) white+yellow",
"= { # 'circle-750.0': 0, # (1) white+red, (2) blue+white # 'triangle-900.0': 3,",
"(2) white # 'rect-762.0-915.0': 11, # (1) white # 'rect-915.0-1220.0': 12, # (1)",
"(1) white # 'rect-915.0-1220.0': [], # (1) white # 'pentagon-915.0': [], # (1)",
"13, # (1) yellow # 'octagon-915.0': 14, # (1) red # 'other': 15,",
"# 'square-600.0': [], # (1) blue # 'rect-458.0-610.0': ['white', 'other'], # (1) chevron",
"(H, S, L) # WHITE = [[0, 0, 95], [360, 360, 100]] #",
"# def forward(self, x): # logits = self.model(x) # y = logits.argmax(-1) #",
"{ # 'circle-750.0': ['white', 'blue', 'red'], # (1) white+red, (2) blue+white # 'triangle-900.0':",
"# (1) red # 'other': [], # } # self.class_list = list(self.color_dict.keys()) #"
] |
[
"print('\\t>>> Starting game') try: while not game.is_game_over(): # game.print_board() direction = await game_engine.next_move(game.state())",
"time.time() metrics = await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0)",
"', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min: ', min(scores)) print('max:",
"False, 'number_of_simulations': 3 } def create_initial_game_board(): state = random_initial_state() # print_grid(state) return Game(state)",
"', json.dumps(Cache().metrics())) if __name__ == '__main__': import asyncio loop = asyncio.new_event_loop() loop.run_until_complete(simulate_games(GAME_SETTINGS['number_of_simulations'])) loop.close()",
"simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores = [] max_tiles = [] execution_times = []",
"print('max: ', max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max",
"print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max tile stats ---')",
"from ai_oracle.game import Game from ai_oracle.game_cache import Cache from ai_utils import print_grid, random_initial_state",
"print('\\n') return game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores = [] max_tiles",
"not game.is_game_over(): # game.print_board() direction = await game_engine.next_move(game.state()) # print('selected move ', direction)",
"'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3 } def create_initial_game_board(): state =",
"game.print_board() direction = await game_engine.next_move(game.state()) # print('selected move ', direction) game.move(direction, add_random_tile=True) except:",
"play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary Report",
"t0 = time.time() metrics = await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1",
"ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from ai_oracle.game import Game from ai_oracle.game_cache import Cache",
"', max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max tile",
"create_initial_game_board(): state = random_initial_state() # print_grid(state) return Game(state) async def play_game(game_num): print('\\t>>> Setting",
"from ai_utils import print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax',",
"ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from ai_oracle.game",
"import statistics import time # from ai_engine.engine_best_score_v2 import BestScore as AIEngine # from",
"Expectimax as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from ai_oracle.game import Game",
"= [] execution_times = [] for index in range(0, number_of_games): t0 = time.time()",
"print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time stats ---') print('min: ', min(execution_times)) print('max: ',",
"print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n') return game.metrics() async def",
"= [] max_tiles = [] execution_times = [] for index in range(0, number_of_games):",
"print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max tile stats ---') print('min: ', min(max_tiles))",
"', min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles))",
"Summary Report ---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth'])",
"GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min: ', min(scores)) print('max: ', max(scores)) print('mean: ',",
"board for game ', game_num) game = create_initial_game_board() print('\\t>>> Starting game') try: while",
"import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from ai_oracle.oracle_python_impl import",
"ai_utils import print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax', #",
"scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n') print('games: ',",
"', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if __name__",
"print('cache metrics: ', json.dumps(Cache().metrics())) if __name__ == '__main__': import asyncio loop = asyncio.new_event_loop()",
"print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min: ', min(scores)) print('max: ', max(scores))",
"game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores = [] max_tiles = []",
"scores = [] max_tiles = [] execution_times = [] for index in range(0,",
"print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if",
"game.is_game_over(): # game.print_board() direction = await game_engine.next_move(game.state()) # print('selected move ', direction) game.move(direction,",
"[] for index in range(0, number_of_games): t0 = time.time() metrics = await play_game(game_num=index+1)",
"game_engine.next_move(game.state()) # print('selected move ', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>>",
"AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as",
"'heuristics_enabled': False, 'number_of_simulations': 3 } def create_initial_game_board(): state = random_initial_state() # print_grid(state) return",
"game board for game ', game_num) game = create_initial_game_board() print('\\t>>> Starting game') try:",
"for index in range(0, number_of_games): t0 = time.time() metrics = await play_game(game_num=index+1) t1",
"', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min:",
"print('\\n--- execution time stats ---') print('min: ', min(execution_times)) print('max: ', max(execution_times)) print('mean: ',",
"Report ---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled:",
"metrics = await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------')",
"return game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores = [] max_tiles =",
"stats ---') print('min: ', min(execution_times)) print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times))",
"= { 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth': 3,",
"max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time stats",
"print('min: ', min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ',",
"', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ',",
"from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from ai_oracle.game import Game from ai_oracle.game_cache import",
"max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max tile stats",
"time stats ---') print('min: ', min(execution_times)) print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:',",
"---') print('min: ', min(scores)) print('max: ', max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd:",
"max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics()))",
"[] max_tiles = [] execution_times = [] for index in range(0, number_of_games): t0",
"as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as",
"import Expectimax as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from ai_oracle.game import",
"- t0) print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ',",
"= [] for index in range(0, number_of_games): t0 = time.time() metrics = await",
"Cache from ai_utils import print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm':",
"game') try: while not game.is_game_over(): # game.print_board() direction = await game_engine.next_move(game.state()) # print('selected",
"= time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n')",
"print('>>> Starting simulations\\n') scores = [] max_tiles = [] execution_times = [] for",
"= await game_engine.next_move(game.state()) # print('selected move ', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation",
"print('\\n--- score stats ---') print('min: ', min(scores)) print('max: ', max(scores)) print('mean: ', statistics.mean(scores))",
"execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm:",
"Game from ai_oracle.game_cache import Cache from ai_utils import print_grid, random_initial_state game_engine = AIEngine(Oracle())",
"Game(state) async def play_game(game_num): print('\\t>>> Setting up the game board for game ',",
"add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n') return game.metrics()",
"direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n')",
"print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth:",
"print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time stats ---')",
"# print('selected move ', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game",
"play_game(game_num): print('\\t>>> Setting up the game board for game ', game_num) game =",
"as Oracle from ai_oracle.game import Game from ai_oracle.game_cache import Cache from ai_utils import",
"', min(execution_times)) print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times))",
"print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n---",
"', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score",
"---') print('min: ', min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd:",
"as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from ai_oracle.game import Game from",
"'number_of_simulations': 3 } def create_initial_game_board(): state = random_initial_state() # print_grid(state) return Game(state) async",
"min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n---",
"print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics:",
"from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from",
"time # from ai_engine.engine_best_score_v2 import BestScore as AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth",
"statistics.stdev(max_tiles)) print('\\n--- execution time stats ---') print('min: ', min(execution_times)) print('max: ', max(execution_times)) print('mean:",
"def play_game(game_num): print('\\t>>> Setting up the game board for game ', game_num) game",
"{ 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled':",
"async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores = [] max_tiles = [] execution_times",
"= random_initial_state() # print_grid(state) return Game(state) async def play_game(game_num): print('\\t>>> Setting up the",
"} def create_initial_game_board(): state = random_initial_state() # print_grid(state) return Game(state) async def play_game(game_num):",
"', min(scores)) print('max: ', max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores))",
"await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary",
"tile stats ---') print('min: ', min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:',",
"', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is over!') print_grid(game.state())",
"AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2',",
"OraclePythonImpl as Oracle from ai_oracle.game import Game from ai_oracle.game_cache import Cache from ai_utils",
"time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n') print('games:",
"execution time stats ---') print('min: ', min(execution_times)) print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times))",
"statistics import time # from ai_engine.engine_best_score_v2 import BestScore as AIEngine # from ai_engine.engine_best_score_with_depth",
"is over!') print_grid(game.state()) print('\\n') return game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores",
"number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats",
"import json import statistics import time # from ai_engine.engine_best_score_v2 import BestScore as AIEngine",
"Error') print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n') return game.metrics() async def simulate_games(number_of_games=1): print('>>>",
"BestScore as AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import",
"simulations\\n') scores = [] max_tiles = [] execution_times = [] for index in",
"index in range(0, number_of_games): t0 = time.time() metrics = await play_game(game_num=index+1) t1 =",
"direction = await game_engine.next_move(game.state()) # print('selected move ', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>>",
"print('\\t>>> Setting up the game board for game ', game_num) game = create_initial_game_board()",
"Game is over!') print_grid(game.state()) print('\\n') return game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n')",
"print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min: ', min(scores))",
"await game_engine.next_move(game.state()) # print('selected move ', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error')",
"GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min: ', min(scores)) print('max: ',",
"', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min: ', min(scores)) print('max: ', max(scores)) print('mean:",
"stats ---') print('min: ', min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles))",
"ai_oracle.game import Game from ai_oracle.game_cache import Cache from ai_utils import print_grid, random_initial_state game_engine",
"statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time stats ---') print('min: ',",
"ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from ai_oracle.oracle_python_impl",
"import OraclePythonImpl as Oracle from ai_oracle.game import Game from ai_oracle.game_cache import Cache from",
"Starting simulations\\n') scores = [] max_tiles = [] execution_times = [] for index",
"execution_times = [] for index in range(0, number_of_games): t0 = time.time() metrics =",
"range(0, number_of_games): t0 = time.time() metrics = await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score'])",
"= time.time() metrics = await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 -",
"print('min: ', min(execution_times)) print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ',",
"as AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax",
"Setting up the game board for game ', game_num) game = create_initial_game_board() print('\\t>>>",
"'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3 } def create_initial_game_board(): state",
"# from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine",
"# print_grid(state) return Game(state) async def play_game(game_num): print('\\t>>> Setting up the game board",
"', game_num) game = create_initial_game_board() print('\\t>>> Starting game') try: while not game.is_game_over(): #",
"print('\\n--- max tile stats ---') print('min: ', min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ',",
"state = random_initial_state() # print_grid(state) return Game(state) async def play_game(game_num): print('\\t>>> Setting up",
"import Game from ai_oracle.game_cache import Cache from ai_utils import print_grid, random_initial_state game_engine =",
"AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from ai_oracle.game import Game from ai_oracle.game_cache",
"# 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3",
"AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle",
"---') print('min: ', min(execution_times)) print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd:",
"random_initial_state() # print_grid(state) return Game(state) async def play_game(game_num): print('\\t>>> Setting up the game",
"print('min: ', min(scores)) print('max: ', max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ',",
"statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max tile stats ---') print('min: ',",
"print('--- Summary Report ---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ',",
"try: while not game.is_game_over(): # game.print_board() direction = await game_engine.next_move(game.state()) # print('selected move",
"t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary Report ---')",
"<filename>main_headless.py import json import statistics import time # from ai_engine.engine_best_score_v2 import BestScore as",
"print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution",
"= await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('---",
"json import statistics import time # from ai_engine.engine_best_score_v2 import BestScore as AIEngine #",
"max tile stats ---') print('min: ', min(max_tiles)) print('max: ', max(max_tiles)) print('mean: ', statistics.mean(max_tiles))",
"', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max tile stats ---') print('min:",
"from ai_oracle.game_cache import Cache from ai_utils import print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS",
"statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if __name__ == '__main__': import asyncio loop =",
"print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if __name__ == '__main__': import asyncio",
"move ', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is over!')",
"def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores = [] max_tiles = [] execution_times =",
"', statistics.stdev(max_tiles)) print('\\n--- execution time stats ---') print('min: ', min(execution_times)) print('max: ', max(execution_times))",
"random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', #",
"---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ',",
"print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled'])",
"print_grid(state) return Game(state) async def play_game(game_num): print('\\t>>> Setting up the game board for",
"game = create_initial_game_board() print('\\t>>> Starting game') try: while not game.is_game_over(): # game.print_board() direction",
"import time # from ai_engine.engine_best_score_v2 import BestScore as AIEngine # from ai_engine.engine_best_score_with_depth import",
"GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---') print('min: ',",
"over!') print_grid(game.state()) print('\\n') return game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores =",
"', statistics.stdev(scores)) print('\\n--- max tile stats ---') print('min: ', min(max_tiles)) print('max: ', max(max_tiles))",
"', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time stats ---') print('min:",
"except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n') return game.metrics() async",
"BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl",
"min(scores)) print('max: ', max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n---",
"stats ---') print('min: ', min(scores)) print('max: ', max(scores)) print('mean: ', statistics.mean(scores)) print('median:', statistics.median(scores))",
"Simulation Error') print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n') return game.metrics() async def simulate_games(number_of_games=1):",
"statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if __name__ ==",
"print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time stats ---') print('min: ', min(execution_times))",
"score stats ---') print('min: ', min(scores)) print('max: ', max(scores)) print('mean: ', statistics.mean(scores)) print('median:',",
"game ', game_num) game = create_initial_game_board() print('\\t>>> Starting game') try: while not game.is_game_over():",
"GAME_SETTINGS = { 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth':",
"'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations':",
"# game.print_board() direction = await game_engine.next_move(game.state()) # print('selected move ', direction) game.move(direction, add_random_tile=True)",
"min(execution_times)) print('max: ', max(execution_times)) print('mean: ', statistics.mean(execution_times)) print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache",
"from ai_engine.engine_best_score_v2 import BestScore as AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine",
"= create_initial_game_board() print('\\t>>> Starting game') try: while not game.is_game_over(): # game.print_board() direction =",
"statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time stats ---') print('min: ', min(execution_times)) print('max:",
"v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3 } def create_initial_game_board(): state = random_initial_state()",
"game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n') return",
"'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3 } def create_initial_game_board(): state = random_initial_state() #",
"ai_oracle.game_cache import Cache from ai_utils import print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS =",
"for game ', game_num) game = create_initial_game_board() print('\\t>>> Starting game') try: while not",
"in range(0, number_of_games): t0 = time.time() metrics = await play_game(game_num=index+1) t1 = time.time()",
"up the game board for game ', game_num) game = create_initial_game_board() print('\\t>>> Starting",
"print('sd: ', statistics.stdev(scores)) print('\\n--- max tile stats ---') print('min: ', min(max_tiles)) print('max: ',",
"import Cache from ai_utils import print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS = {",
"# 'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3 } def create_initial_game_board():",
"# from ai_engine.engine_best_score_v2 import BestScore as AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as",
"'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False,",
"= AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore",
"3 } def create_initial_game_board(): state = random_initial_state() # print_grid(state) return Game(state) async def",
"ai_engine.engine_best_score_v2 import BestScore as AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from",
"'algorithm': 'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3 }",
"async def play_game(game_num): print('\\t>>> Setting up the game board for game ', game_num)",
"def create_initial_game_board(): state = random_initial_state() # print_grid(state) return Game(state) async def play_game(game_num): print('\\t>>>",
"3, 'heuristics_enabled': False, 'number_of_simulations': 3 } def create_initial_game_board(): state = random_initial_state() # print_grid(state)",
"', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if __name__ == '__main__': import asyncio loop",
"import print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax', # 'algorithm':",
"statistics.median(scores)) print('sd: ', statistics.stdev(scores)) print('\\n--- max tile stats ---') print('min: ', min(max_tiles)) print('max:",
"max_tiles.append(metrics['max_tile']) execution_times.append(t1 - t0) print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n') print('games: ', number_of_games)",
"game_engine = AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth', # 'algorithm':",
"from ai_engine.engine_expectimax_with_heur_v1 import Expectimax as AIEngine from ai_oracle.oracle_python_impl import OraclePythonImpl as Oracle from",
"game_num) game = create_initial_game_board() print('\\t>>> Starting game') try: while not game.is_game_over(): # game.print_board()",
"Starting game') try: while not game.is_game_over(): # game.print_board() direction = await game_engine.next_move(game.state()) #",
"print('algorithm: ', GAME_SETTINGS['algorithm']) print('max_depth: ', GAME_SETTINGS['max_depth']) print('heuristics_enabled: ', GAME_SETTINGS['heuristics_enabled']) print('\\n--- score stats ---')",
"statistics.stdev(scores)) print('\\n--- max tile stats ---') print('min: ', min(max_tiles)) print('max: ', max(max_tiles)) print('mean:",
"metrics: ', json.dumps(Cache().metrics())) if __name__ == '__main__': import asyncio loop = asyncio.new_event_loop() loop.run_until_complete(simulate_games(GAME_SETTINGS['number_of_simulations']))",
"Oracle from ai_oracle.game import Game from ai_oracle.game_cache import Cache from ai_utils import print_grid,",
"create_initial_game_board() print('\\t>>> Starting game') try: while not game.is_game_over(): # game.print_board() direction = await",
"statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if __name__ == '__main__': import",
"print_grid(game.state()) print('\\n') return game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting simulations\\n') scores = []",
"print_grid, random_initial_state game_engine = AIEngine(Oracle()) GAME_SETTINGS = { 'algorithm': 'Expectimax', # 'algorithm': 'BestScoreWithDepth',",
"print('\\n\\t>>> Game is over!') print_grid(game.state()) print('\\n') return game.metrics() async def simulate_games(number_of_games=1): print('>>> Starting",
"the game board for game ', game_num) game = create_initial_game_board() print('\\t>>> Starting game')",
"', max(max_tiles)) print('mean: ', statistics.mean(max_tiles)) print('median:', statistics.median(max_tiles)) print('sd: ', statistics.stdev(max_tiles)) print('\\n--- execution time",
"max_tiles = [] execution_times = [] for index in range(0, number_of_games): t0 =",
"'BestScoreWithDepth', # 'algorithm': 'BestScore v2', 'max_depth': 3, 'heuristics_enabled': False, 'number_of_simulations': 3 } def",
"t0) print('\\n---------------------------') print('--- Summary Report ---') print('---------------------------\\n') print('games: ', number_of_games) print('algorithm: ', GAME_SETTINGS['algorithm'])",
"print('median:', statistics.median(execution_times)) print('sd: ', statistics.stdev(execution_times)) print('cache metrics: ', json.dumps(Cache().metrics())) if __name__ == '__main__':",
"while not game.is_game_over(): # game.print_board() direction = await game_engine.next_move(game.state()) # print('selected move ',",
"import BestScore as AIEngine # from ai_engine.engine_best_score_with_depth import BestScoreWithDepth as AIEngine from ai_engine.engine_expectimax_with_heur_v1",
"number_of_games): t0 = time.time() metrics = await play_game(game_num=index+1) t1 = time.time() scores.append(metrics['score']) max_tiles.append(metrics['max_tile'])",
"return Game(state) async def play_game(game_num): print('\\t>>> Setting up the game board for game",
"print('selected move ', direction) game.move(direction, add_random_tile=True) except: print('\\t\\t>>> Simulation Error') print('\\n\\t>>> Game is",
"[] execution_times = [] for index in range(0, number_of_games): t0 = time.time() metrics"
] |
[
"= {}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default = default def __getitem__(self, key): return",
"<gh_stars>0 class SafeDict(dict): def __init__(self, dictionary:dict = {}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default",
"class SafeDict(dict): def __init__(self, dictionary:dict = {}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default =",
"dictionary:dict = {}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default = default def __getitem__(self, key):",
"SafeDict(dict): def __init__(self, dictionary:dict = {}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default = default",
"{}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default = default def __getitem__(self, key): return self.get(key,",
"def __init__(self, dictionary:dict = {}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default = default def",
"default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default = default def __getitem__(self, key): return self.get(key, self.default)",
"__init__(self, dictionary:dict = {}, default=None, **kwargs): super().__init__(**dictionary, **kwargs) self.default = default def __getitem__(self,"
] |
[
"if __name__ == '__main__': args = getargs() sys.path.append(args.pyhbase) from hbase import Hbase from",
"TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def perr(msg): \"\"\" Print",
"sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True: try: item",
"help='python interface of hbase') return parser.parse_args() def main(args): \"\"\" Main entry. \"\"\" transport",
"import TBinaryProtocol def perr(msg): \"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush()",
"as err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\"",
"program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the",
"parser.add_argument('table', type=str, help='target table name in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address",
"100 == 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" %",
"ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists as err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1)",
"Created on: Sat Jun 7 13:36:03 2014 CST \"\"\" DESCRIPTION = \"\"\" This",
"command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def getargs(): \"\"\" Parse program arguments. \"\"\"",
"File Name: level2hbase.py Author: <NAME> E-mail: <EMAIL> Created on: Sat Jun 7 13:36:03",
"can transfer the data from LevelDB to HBase. \"\"\" import os import sys",
"import leveldb from thrift import Thrift from thrift.transport import TSocket from thrift.transport import",
"Print error message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print information",
"perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt)",
"thrift.protocol import TBinaryProtocol def perr(msg): \"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\" % msg)",
"Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol",
"CST \"\"\" DESCRIPTION = \"\"\" This program can transfer the data from LevelDB",
"on: Sat Jun 7 13:36:03 2014 CST \"\"\" DESCRIPTION = \"\"\" This program",
"value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ == '__main__': args = getargs() sys.path.append(args.pyhbase)",
"parser.parse_args() def main(args): \"\"\" Main entry. \"\"\" transport = TSocket.TSocket(args.host, args.port) transport =",
"name of hbase server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port number of hbase server')",
"help='path to the LevelDB database') parser.add_argument('table', type=str, help='target table name in hbase') parser.add_argument('host',",
"\"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def getargs(): \"\"\" Parse program arguments. \"\"\" parser",
"sys.stdout.flush() def runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def getargs():",
"server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port number of hbase server') parser.add_argument('pyhbase', type=str, nargs='?',",
"def runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def getargs(): \"\"\"",
"return parser.parse_args() def main(args): \"\"\" Main entry. \"\"\" transport = TSocket.TSocket(args.host, args.port) transport",
"data from LevelDB to HBase. \"\"\" import os import sys import argparse import",
"= ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists as err: perr(\"ERROR: %s\\n\" % err.message)",
"cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ == '__main__':",
"13:36:03 2014 CST \"\"\" DESCRIPTION = \"\"\" This program can transfer the data",
"type=str, help='path to the LevelDB database') parser.add_argument('table', type=str, help='target table name in hbase')",
"hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address / Host name of hbase server')",
"database') parser.add_argument('table', type=str, help='target table name in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP",
"StopIteration: break cnt += 1 if cnt % 100 == 0: pinfo(\"\\r\\t%d\" %",
"DESCRIPTION = \"\"\" This program can transfer the data from LevelDB to HBase.",
"transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:',",
"import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import",
"% msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\" % msg)",
"client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter =",
"hbase server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port number of hbase server') parser.add_argument('pyhbase', type=str,",
"cnt % 100 == 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None)",
"Parse program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to",
"contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table, [contents])",
"= TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open()",
"= leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists as err: perr(\"ERROR:",
"TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents",
"pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True: try: item = iter.next() except StopIteration:",
"ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists as err:",
"to HBase. \"\"\" import os import sys import argparse import leveldb from thrift",
"utf-8 ######################################################################### ######################################################################### \"\"\" File Name: level2hbase.py Author: <NAME> E-mail: <EMAIL> Created on:",
"Jun 7 13:36:03 2014 CST \"\"\" DESCRIPTION = \"\"\" This program can transfer",
"from LevelDB to HBase. \"\"\" import os import sys import argparse import leveldb",
"HBase. \"\"\" import os import sys import argparse import leveldb from thrift import",
"parser.add_argument('leveldb', type=str, help='path to the LevelDB database') parser.add_argument('table', type=str, help='target table name in",
"entry. \"\"\" transport = TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client",
"This program can transfer the data from LevelDB to HBase. \"\"\" import os",
"msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush()",
"cnt) while True: try: item = iter.next() except StopIteration: break cnt += 1",
"default=\"gen-py\", help='python interface of hbase') return parser.parse_args() def main(args): \"\"\" Main entry. \"\"\"",
"<EMAIL> Created on: Sat Jun 7 13:36:03 2014 CST \"\"\" DESCRIPTION = \"\"\"",
"item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ == '__main__': args =",
"#!/usr/bin/env python # coding: utf-8 ######################################################################### ######################################################################### \"\"\" File Name: level2hbase.py Author: <NAME>",
"Main entry. \"\"\" transport = TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport)",
"cnt) if __name__ == '__main__': args = getargs() sys.path.append(args.pyhbase) from hbase import Hbase",
"\"\"\" Main entry. \"\"\" transport = TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol =",
"= 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True: try: item = iter.next()",
"err.message) sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True: try:",
"\"\"\" Run command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def getargs(): \"\"\" Parse program",
"sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\" % cmd)",
"type=str, nargs='?', default=\"gen-py\", help='python interface of hbase') return parser.parse_args() def main(args): \"\"\" Main",
"2014 CST \"\"\" DESCRIPTION = \"\"\" This program can transfer the data from",
"thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def perr(msg):",
"import TTransport from thrift.protocol import TBinaryProtocol def perr(msg): \"\"\" Print error message. \"\"\"",
"server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface of hbase') return parser.parse_args() def main(args):",
"ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists",
"== 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt)",
"LevelDB database') parser.add_argument('table', type=str, help='target table name in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\",",
"/ Host name of hbase server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port number of",
"argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the LevelDB database') parser.add_argument('table', type=str, help='target table name",
"except StopIteration: break cnt += 1 if cnt % 100 == 0: pinfo(\"\\r\\t%d\"",
"\"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\"",
"Name: level2hbase.py Author: <NAME> E-mail: <EMAIL> Created on: Sat Jun 7 13:36:03 2014",
"pinfo(\"\\r\\t%d\" % cnt) while True: try: item = iter.next() except StopIteration: break cnt",
"cmd) os.system(cmd) def getargs(): \"\"\" Parse program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=",
"args.port) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents =",
"= TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1)",
"% msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd)",
"TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter",
"python # coding: utf-8 ######################################################################### ######################################################################### \"\"\" File Name: level2hbase.py Author: <NAME> E-mail:",
"def getargs(): \"\"\" Parse program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb',",
"to the LevelDB database') parser.add_argument('table', type=str, help='target table name in hbase') parser.add_argument('host', type=str,",
"if cnt % 100 == 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])],",
"table name in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address / Host name",
"transport = TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol)",
"iter = ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists as err: perr(\"ERROR: %s\\n\" %",
"Print information message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run command.",
"pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ == '__main__': args = getargs() sys.path.append(args.pyhbase) from hbase",
"maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists as",
"level2hbase.py Author: <NAME> E-mail: <EMAIL> Created on: Sat Jun 7 13:36:03 2014 CST",
"\"\"\" import os import sys import argparse import leveldb from thrift import Thrift",
"sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\" %",
"argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the LevelDB database') parser.add_argument('table', type=str, help='target",
"AlreadyExists as err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\")",
"__name__ == '__main__': args = getargs() sys.path.append(args.pyhbase) from hbase import Hbase from hbase.ttypes",
"import os import sys import argparse import leveldb from thrift import Thrift from",
"leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table, [contents]) except AlreadyExists as err: perr(\"ERROR: %s\\n\"",
"default=\"127.0.0.1\", help='IP address / Host name of hbase server') parser.add_argument('port', type=int, nargs='?', default=9090,",
"\"\"\" transport = TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client =",
"[contents]) except AlreadyExists as err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt = 0",
"from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from",
"######################################################################### \"\"\" File Name: level2hbase.py Author: <NAME> E-mail: <EMAIL> Created on: Sat Jun",
"parser.add_argument('port', type=int, nargs='?', default=9090, help='port number of hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\",",
"%s\\n\" % err.message) sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while",
"LevelDB to HBase. \"\"\" import os import sys import argparse import leveldb from",
"msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def",
"cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True: try: item =",
"transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table,",
"client.createTable(args.table, [contents]) except AlreadyExists as err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt =",
"\"\"\" File Name: level2hbase.py Author: <NAME> E-mail: <EMAIL> Created on: Sat Jun 7",
"0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True: try: item = iter.next() except",
"Sat Jun 7 13:36:03 2014 CST \"\"\" DESCRIPTION = \"\"\" This program can",
"nargs='?', default=9090, help='port number of hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface",
"\"\"\" This program can transfer the data from LevelDB to HBase. \"\"\" import",
"program can transfer the data from LevelDB to HBase. \"\"\" import os import",
"None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ == '__main__': args = getargs() sys.path.append(args.pyhbase) from",
"\"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run",
"item = iter.next() except StopIteration: break cnt += 1 if cnt % 100",
"transfer the data from LevelDB to HBase. \"\"\" import os import sys import",
"TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb",
"information message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run command. \"\"\"",
"<NAME> E-mail: <EMAIL> Created on: Sat Jun 7 13:36:03 2014 CST \"\"\" DESCRIPTION",
"Host name of hbase server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port number of hbase",
"from thrift.protocol import TBinaryProtocol def perr(msg): \"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\" %",
"True: try: item = iter.next() except StopIteration: break cnt += 1 if cnt",
"address / Host name of hbase server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port number",
"the data from LevelDB to HBase. \"\"\" import os import sys import argparse",
"7 13:36:03 2014 CST \"\"\" DESCRIPTION = \"\"\" This program can transfer the",
"E-mail: <EMAIL> Created on: Sat Jun 7 13:36:03 2014 CST \"\"\" DESCRIPTION =",
"type=str, nargs='?', default=\"127.0.0.1\", help='IP address / Host name of hbase server') parser.add_argument('port', type=int,",
"from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def perr(msg): \"\"\" Print error",
"nargs='?', default=\"127.0.0.1\", help='IP address / Host name of hbase server') parser.add_argument('port', type=int, nargs='?',",
"# coding: utf-8 ######################################################################### ######################################################################### \"\"\" File Name: level2hbase.py Author: <NAME> E-mail: <EMAIL>",
"name in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address / Host name of",
"coding: utf-8 ######################################################################### ######################################################################### \"\"\" File Name: level2hbase.py Author: <NAME> E-mail: <EMAIL> Created",
"try: item = iter.next() except StopIteration: break cnt += 1 if cnt %",
"% cnt) while True: try: item = iter.next() except StopIteration: break cnt +=",
"sys import argparse import leveldb from thrift import Thrift from thrift.transport import TSocket",
"\"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\" %",
"= Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter()",
"\"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the LevelDB database')",
"thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def perr(msg): \"\"\" Print error message.",
"\"\"\" DESCRIPTION = \"\"\" This program can transfer the data from LevelDB to",
"except AlreadyExists as err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt = 0 pinfo(\"Processed",
"argparse import leveldb from thrift import Thrift from thrift.transport import TSocket from thrift.transport",
"######################################################################### ######################################################################### \"\"\" File Name: level2hbase.py Author: <NAME> E-mail: <EMAIL> Created on: Sat",
"help='IP address / Host name of hbase server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port",
"parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface of hbase') return parser.parse_args() def main(args): \"\"\"",
"message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print information message. \"\"\"",
"TBinaryProtocol def perr(msg): \"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def",
"of hbase') return parser.parse_args() def main(args): \"\"\" Main entry. \"\"\" transport = TSocket.TSocket(args.host,",
"type=str, help='target table name in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address /",
"error message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print information message.",
"help='port number of hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface of hbase')",
"of hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface of hbase') return parser.parse_args()",
"def pinfo(msg): \"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd):",
"pinfo(msg): \"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd): \"\"\"",
"in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address / Host name of hbase",
"hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface of hbase') return parser.parse_args() def",
"image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True: try: item = iter.next() except StopIteration: break",
"arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the LevelDB",
"interface of hbase') return parser.parse_args() def main(args): \"\"\" Main entry. \"\"\" transport =",
"type=int, nargs='?', default=9090, help='port number of hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python",
"= TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb)",
"of hbase server') parser.add_argument('port', type=int, nargs='?', default=9090, help='port number of hbase server') parser.add_argument('pyhbase',",
"cnt += 1 if cnt % 100 == 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table,",
"formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the LevelDB database') parser.add_argument('table', type=str, help='target table",
"import argparse import leveldb from thrift import Thrift from thrift.transport import TSocket from",
"= ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try: client.createTable(args.table, [contents]) except",
"err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" %",
"Run command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def getargs(): \"\"\" Parse program arguments.",
"protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb =",
"perr(\"%s\\n\" % cmd) os.system(cmd) def getargs(): \"\"\" Parse program arguments. \"\"\" parser =",
"parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address / Host name of hbase server') parser.add_argument('port',",
"args = getargs() sys.path.append(args.pyhbase) from hbase import Hbase from hbase.ttypes import * main(args)",
"runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\" % cmd) os.system(cmd) def getargs(): \"\"\" Parse",
"\"\"\" Parse program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path",
"pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__",
"% cnt) if __name__ == '__main__': args = getargs() sys.path.append(args.pyhbase) from hbase import",
"= argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the LevelDB database') parser.add_argument('table', type=str,",
"getargs(): \"\"\" Parse program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str,",
"1 if cnt % 100 == 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\",",
"% 100 == 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\"",
"help='target table name in hbase') parser.add_argument('host', type=str, nargs='?', default=\"127.0.0.1\", help='IP address / Host",
"nargs='?', default=\"gen-py\", help='python interface of hbase') return parser.parse_args() def main(args): \"\"\" Main entry.",
"import sys import argparse import leveldb from thrift import Thrift from thrift.transport import",
"message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def runcmd(cmd): \"\"\" Run command. \"\"\" perr(\"%s\\n\"",
"def main(args): \"\"\" Main entry. \"\"\" transport = TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport)",
"Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) ldb = leveldb.LevelDB(args.leveldb) iter = ldb.RangeIter() try:",
"= \"\"\" This program can transfer the data from LevelDB to HBase. \"\"\"",
"iter.next() except StopIteration: break cnt += 1 if cnt % 100 == 0:",
"sys.stderr.flush() def pinfo(msg): \"\"\" Print information message. \"\"\" sys.stdout.write(\"%s\" % msg) sys.stdout.flush() def",
"leveldb from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport",
"os.system(cmd) def getargs(): \"\"\" Parse program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter)",
"default=9090, help='port number of hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface of",
"'__main__': args = getargs() sys.path.append(args.pyhbase) from hbase import Hbase from hbase.ttypes import *",
"[Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ == '__main__': args = getargs()",
"TTransport from thrift.protocol import TBinaryProtocol def perr(msg): \"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\"",
"client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ == '__main__': args",
"try: client.createTable(args.table, [contents]) except AlreadyExists as err: perr(\"ERROR: %s\\n\" % err.message) sys.exit(1) cnt",
"parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class= argparse.RawTextHelpFormatter) parser.add_argument('leveldb', type=str, help='path to the LevelDB database') parser.add_argument('table',",
"0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if",
"break cnt += 1 if cnt % 100 == 0: pinfo(\"\\r\\t%d\" % cnt)",
"def perr(msg): \"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg):",
"% cmd) os.system(cmd) def getargs(): \"\"\" Parse program arguments. \"\"\" parser = argparse.ArgumentParser(description=DESCRIPTION,",
"number of hbase server') parser.add_argument('pyhbase', type=str, nargs='?', default=\"gen-py\", help='python interface of hbase') return",
"import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def perr(msg): \"\"\"",
"main(args): \"\"\" Main entry. \"\"\" transport = TSocket.TSocket(args.host, args.port) transport = TTransport.TBufferedTransport(transport) protocol",
"\"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg): \"\"\" Print",
"% cnt) client.mutateRow(args.table, item[0], [Mutation(column=\"cf:data\", value=item[1])], None) pinfo(\"\\r\\t%d\\tDone!\\n\" % cnt) if __name__ ==",
"thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol",
"perr(msg): \"\"\" Print error message. \"\"\" sys.stderr.write(\"%s\" % msg) sys.stderr.flush() def pinfo(msg): \"\"\"",
"% err.message) sys.exit(1) cnt = 0 pinfo(\"Processed image:\\n\") pinfo(\"\\r\\t%d\" % cnt) while True:",
"os import sys import argparse import leveldb from thrift import Thrift from thrift.transport",
"== '__main__': args = getargs() sys.path.append(args.pyhbase) from hbase import Hbase from hbase.ttypes import",
"+= 1 if cnt % 100 == 0: pinfo(\"\\r\\t%d\" % cnt) client.mutateRow(args.table, item[0],",
"Author: <NAME> E-mail: <EMAIL> Created on: Sat Jun 7 13:36:03 2014 CST \"\"\"",
"while True: try: item = iter.next() except StopIteration: break cnt += 1 if",
"= iter.next() except StopIteration: break cnt += 1 if cnt % 100 ==",
"hbase') return parser.parse_args() def main(args): \"\"\" Main entry. \"\"\" transport = TSocket.TSocket(args.host, args.port)",
"the LevelDB database') parser.add_argument('table', type=str, help='target table name in hbase') parser.add_argument('host', type=str, nargs='?',",
"from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def"
] |
[
"return BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv): pixels = [] if tlv.l %",
"pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err = BigSize.pop(unextended) assert err is None art_no_content",
"if err: return None, err if parsed['format'] != \"tlv\": return None, \"non-tlv payload",
"Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward,",
"class Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for p in pixels]) return Tlv(PIXEL_TLV_TYPE,",
"from bolt.tlv import Tlv from bolt.namespace import Namespace from bolt.hop_payload import HopPayload, TlvHopPayload",
"tlv.l % 5 != 0: return None, \"unexpected length\" remainder = tlv.v while",
"in parsed['tlvs']: return None, \"no pixel data tlv in payload\" return parsed, None",
"bolt.bigsize import BigSize from bolt.tlv import Tlv from bolt.namespace import Namespace from bolt.hop_payload",
"Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443 class Extension: def _encode_pixels(pixels): encoded =",
"TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443 class Extension:",
"None, err if len(remainder) > 0: return None, \"unexpected extra bytes\" return {'tlv_type_name':",
"None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv): art_no, remainder,",
"def parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if err: return None, err",
"None, \"unexpected length\" remainder = tlv.v while len(remainder) > 0: pixel_hex, remainder, err",
"> 0: pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder) if err: return None, err",
"art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err = BigSize.pop(unextended) assert",
"return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward,",
"encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended",
"Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id)",
"extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err:",
"= content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv):",
"total_msat) old_len, content, err = BigSize.pop(unextended) assert err is None art_no_content = Extension._encode_art_no(art_no)",
"bolt.namespace import Namespace from bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE",
"return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv): art_no,",
"import HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443",
"old_len, content, err = BigSize.pop(unextended) assert err is None art_no_content = Extension._encode_art_no(art_no) pixel_content",
"= {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return",
"return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value,",
"None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string,",
"= content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value,",
"content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret,",
"err if parsed['format'] != \"tlv\": return None, \"non-tlv payload byte string\" if ART_TLV_TYPE",
"import BigSize from bolt.tlv import Tlv from bolt.namespace import Namespace from bolt.hop_payload import",
"if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def",
"if PIXEL_TLV_TYPE not in parsed['tlvs']: return None, \"no pixel data tlv in payload\"",
"def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content,",
"while len(remainder) > 0: pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder) if err: return",
"return None, \"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string):",
"from bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE",
"TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err = BigSize.pop(unextended) assert err is None art_no_content",
"payload byte string\" if ART_TLV_TYPE not in parsed['tlvs']: return None, \"no art tlv",
"bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels,",
"bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443 class Extension: def _encode_pixels(pixels):",
"import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443 class Extension: def _encode_pixels(pixels): encoded",
"None, err if parsed['format'] != \"tlv\": return None, \"non-tlv payload byte string\" if",
"None def parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if err: return None,",
"def parse_pixels(tlv): pixels = [] if tlv.l % 5 != 0: return None,",
"err: return None, err if len(remainder) > 0: return None, \"unexpected extra bytes\"",
"_encode_pixels(pixels): encoded = b''.join([p.to_bin() for p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no):",
"if len(remainder) > 0: return None, \"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no':",
"def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers)",
"extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE:",
"parsed['tlvs']: return None, \"no art tlv in payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']:",
"bolt.util import h2b from bolt.bigsize import BigSize from bolt.tlv import Tlv from bolt.namespace",
"art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content = content + art_no_content + pixel_content",
"% 5 != 0: return None, \"unexpected length\" remainder = tlv.v while len(remainder)",
"parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if",
"Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None, err if parsed['format']",
"pixel_content return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended",
"short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err = BigSize.pop(unextended)",
"44445 ART_TLV_TYPE = 44443 class Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for p",
"err = Namespace.pop_tu16(tlv.l, tlv.v) if err: return None, err if len(remainder) > 0:",
"from bolt.util import h2b from bolt.bigsize import BigSize from bolt.tlv import Tlv from",
"Namespace.pop_bytes(5, remainder) if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels},",
"Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None, err",
"def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no,",
"totol_msat= total_msat) old_len, content, err = BigSize.pop(unextended) assert err is None art_no_content =",
"None art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content = content + art_no_content +",
"BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv): pixels = [] if tlv.l % 5",
"err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None, err if parsed['format'] != \"tlv\":",
"err: return None, err if parsed['format'] != \"tlv\": return None, \"non-tlv payload byte",
"art tlv in payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']: return None, \"no pixel",
"content, err = BigSize.pop(unextended) assert err is None art_no_content = Extension._encode_art_no(art_no) pixel_content =",
"art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err =",
"+ new_content ########################################################################### def parse_pixels(tlv): pixels = [] if tlv.l % 5 !=",
"parse_pixels(tlv): pixels = [] if tlv.l % 5 != 0: return None, \"unexpected",
"[] if tlv.l % 5 != 0: return None, \"unexpected length\" remainder =",
"new_content = content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward,",
"art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if err: return None, err if len(remainder)",
"err = Namespace.pop_bytes(5, remainder) if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\",",
"string\" if ART_TLV_TYPE not in parsed['tlvs']: return None, \"no art tlv in payload\"",
"return None, \"unexpected length\" remainder = tlv.v while len(remainder) > 0: pixel_hex, remainder,",
"\"no art tlv in payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']: return None, \"no",
"not in parsed['tlvs']: return None, \"no pixel data tlv in payload\" return parsed,",
"b''.join([p.to_bin() for p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no)",
"is None art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content = content + art_no_content",
"pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def",
"Namespace.pop_tu16(tlv.l, tlv.v) if err: return None, err if len(remainder) > 0: return None,",
"art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv): pixels = []",
"0: return None, \"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def",
"h2b from bolt.bigsize import BigSize from bolt.tlv import Tlv from bolt.namespace import Namespace",
"outgoing_cltv_value, short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err =",
"= 44445 ART_TLV_TYPE = 44443 class Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for",
"import Namespace from bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE =",
"content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv): pixels",
"= b''.join([p.to_bin() for p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded =",
"\"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string): extension_parsers =",
"\"unexpected length\" remainder = tlv.v while len(remainder) > 0: pixel_hex, remainder, err =",
"if ART_TLV_TYPE not in parsed['tlvs']: return None, \"no art tlv in payload\" if",
"from bolt.bigsize import BigSize from bolt.tlv import Tlv from bolt.namespace import Namespace from",
"outgoing_cltv_value, short_channel_id) old_len, content, err = BigSize.pop(unextended) assert err is None art_no_content =",
"+ art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat,",
"HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443 class",
"= TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err = BigSize.pop(unextended) assert err is None",
"BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward,",
"def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def",
"> 0: return None, \"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None",
"= Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended =",
"return None, \"no art tlv in payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']: return",
"= tlv.v while len(remainder) > 0: pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder) if",
"{PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None,",
"<reponame>jarret/bannerpunk from bolt.util import h2b from bolt.bigsize import BigSize from bolt.tlv import Tlv",
"0: return None, \"unexpected length\" remainder = tlv.v while len(remainder) > 0: pixel_hex,",
"= Namespace.pop_bytes(5, remainder) if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels':",
"########################################################################### def parse_pixels(tlv): pixels = [] if tlv.l % 5 != 0: return",
"BigSize from bolt.tlv import Tlv from bolt.namespace import Namespace from bolt.hop_payload import HopPayload,",
"remainder = tlv.v while len(remainder) > 0: pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder)",
"err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv):",
"'pixels': pixels}, None def parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if err:",
"tlv.v) if err: return None, err if len(remainder) > 0: return None, \"unexpected",
"\"tlv\": return None, \"non-tlv payload byte string\" if ART_TLV_TYPE not in parsed['tlvs']: return",
"import Tlv from bolt.namespace import Namespace from bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel",
"ART_TLV_TYPE = 44443 class Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for p in",
"encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat)",
"= TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err = BigSize.pop(unextended) assert err",
"err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv): art_no, remainder, err",
"from bolt.namespace import Namespace from bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel",
"PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443 class Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin()",
"\"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if",
"= [] if tlv.l % 5 != 0: return None, \"unexpected length\" remainder",
"Extension._encode_pixels(pixels) new_content = content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content ###########################################################################",
"tlv.v while len(remainder) > 0: pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder) if err:",
"ART_TLV_TYPE: Extension.parse_art_no} parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None, err if",
"+ pixel_content return BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv): pixels = [] if",
"if parsed['format'] != \"tlv\": return None, \"non-tlv payload byte string\" if ART_TLV_TYPE not",
"Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content = content + art_no_content + pixel_content return BigSize.encode(len(new_content))",
"parsed, err = HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None, err if parsed['format'] !=",
"return None, err if len(remainder) > 0: return None, \"unexpected extra bytes\" return",
"pixel_content = Extension._encode_pixels(pixels) new_content = content + art_no_content + pixel_content return BigSize.encode(len(new_content)) +",
"unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err = BigSize.pop(unextended) assert",
"\"non-tlv payload byte string\" if ART_TLV_TYPE not in parsed['tlvs']: return None, \"no art",
"encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len,",
"unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err = BigSize.pop(unextended) assert err is",
"pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err = BigSize.pop(unextended)",
"pixel_content return BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv): pixels = [] if tlv.l",
"BigSize.pop(unextended) assert err is None art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content =",
"extension_parsers=extension_parsers) if err: return None, err if parsed['format'] != \"tlv\": return None, \"non-tlv",
"in payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']: return None, \"no pixel data tlv",
"err is None art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content = content +",
"5 != 0: return None, \"unexpected length\" remainder = tlv.v while len(remainder) >",
"TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err = BigSize.pop(unextended) assert err is",
"\"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed,",
"= Extension._encode_pixels(pixels) new_content = content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content",
"{'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no}",
"art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no,",
"def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat=",
"bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE =",
"+ art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content ########################################################################### def parse_pixels(tlv): pixels =",
"new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret,",
"PIXEL_TLV_TYPE not in parsed['tlvs']: return None, \"no pixel data tlv in payload\" return",
"Extension._encode_pixels(pixels) new_content = content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content def",
"Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value,",
"return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE:",
"44443 class Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for p in pixels]) return",
"err = BigSize.pop(unextended) assert err is None art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels)",
"encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err",
"new_content ########################################################################### def parse_pixels(tlv): pixels = [] if tlv.l % 5 != 0:",
"in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode()",
"bolt.tlv import Tlv from bolt.namespace import Namespace from bolt.hop_payload import HopPayload, TlvHopPayload from",
"len(remainder) > 0: pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder) if err: return None,",
"{'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v)",
"encoded = b''.join([p.to_bin() for p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded",
"Namespace from bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445",
"return None, err if parsed['format'] != \"tlv\": return None, \"non-tlv payload byte string\"",
"= Namespace.pop_tu16(tlv.l, tlv.v) if err: return None, err if len(remainder) > 0: return",
"short_channel_id) old_len, content, err = BigSize.pop(unextended) assert err is None art_no_content = Extension._encode_art_no(art_no)",
"pixels}, None def parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if err: return",
"for p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return",
"remainder) if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None",
"+ new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value,",
"ART_TLV_TYPE not in parsed['tlvs']: return None, \"no art tlv in payload\" if PIXEL_TLV_TYPE",
"byte string\" if ART_TLV_TYPE not in parsed['tlvs']: return None, \"no art tlv in",
"length\" remainder = tlv.v while len(remainder) > 0: pixel_hex, remainder, err = Namespace.pop_bytes(5,",
"= Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content = content + art_no_content + pixel_content return",
"= HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None, err if parsed['format'] != \"tlv\": return",
"pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv): art_no, remainder, err =",
"remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if err: return None, err if len(remainder) >",
"return None, \"non-tlv payload byte string\" if ART_TLV_TYPE not in parsed['tlvs']: return None,",
"payment_secret, total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content,",
"from bannerpunk.pixel import Pixel PIXEL_TLV_TYPE = 44445 ART_TLV_TYPE = 44443 class Extension: def",
"total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err",
"encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id,",
"pixels): unextended = TlvHopPayload.encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id) old_len, content, err = BigSize.pop(unextended) assert err",
"0: pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder) if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex)))",
"return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended =",
"None, \"no art tlv in payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']: return None,",
"p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode() def _encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE,",
"= BigSize.pop(unextended) assert err is None art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content",
"HopPayload.parse(byte_string, extension_parsers=extension_parsers) if err: return None, err if parsed['format'] != \"tlv\": return None,",
"not in parsed['tlvs']: return None, \"no art tlv in payload\" if PIXEL_TLV_TYPE not",
"parsed['format'] != \"tlv\": return None, \"non-tlv payload byte string\" if ART_TLV_TYPE not in",
"return {'tlv_type_name': \"bannerpunk_pixels\", 'pixels': pixels}, None def parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l,",
"= 44443 class Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for p in pixels])",
"_encode_art_no(art_no): encoded = Namespace.encode_tu16(art_no) return Tlv(ART_TLV_TYPE, encoded).encode() def encode_non_final(amt_to_forward, outgoing_cltv_value, short_channel_id, art_no, pixels):",
"len(remainder) > 0: return None, \"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no},",
"if err: return None, err if len(remainder) > 0: return None, \"unexpected extra",
"+ pixel_content return BigSize.encode(len(new_content)) + new_content def encode_final(amt_to_forward, outgoing_cltv_value, payment_secret, total_msat, art_no, pixels):",
"Tlv from bolt.namespace import Namespace from bolt.hop_payload import HopPayload, TlvHopPayload from bannerpunk.pixel import",
"err if len(remainder) > 0: return None, \"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\",",
"Extension: def _encode_pixels(pixels): encoded = b''.join([p.to_bin() for p in pixels]) return Tlv(PIXEL_TLV_TYPE, encoded).encode()",
"new_content = content + art_no_content + pixel_content return BigSize.encode(len(new_content)) + new_content ########################################################################### def",
"None, \"unexpected extra bytes\" return {'tlv_type_name': \"bannerpunk_art_no\", 'art_no': art_no}, None def parse(byte_string): extension_parsers",
"outgoing_cltv_value, payment_secret, total_msat, art_no, pixels): unextended = TlvHopPayload.encode_final(amt_to_forward, outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len,",
"art_no}, None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err =",
"in parsed['tlvs']: return None, \"no art tlv in payload\" if PIXEL_TLV_TYPE not in",
"import h2b from bolt.bigsize import BigSize from bolt.tlv import Tlv from bolt.namespace import",
"assert err is None art_no_content = Extension._encode_art_no(art_no) pixel_content = Extension._encode_pixels(pixels) new_content = content",
"remainder, err = Namespace.pop_bytes(5, remainder) if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return {'tlv_type_name':",
"'art_no': art_no}, None def parse(byte_string): extension_parsers = {PIXEL_TLV_TYPE: Extension.parse_pixels, ART_TLV_TYPE: Extension.parse_art_no} parsed, err",
"None, \"non-tlv payload byte string\" if ART_TLV_TYPE not in parsed['tlvs']: return None, \"no",
"!= 0: return None, \"unexpected length\" remainder = tlv.v while len(remainder) > 0:",
"tlv in payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']: return None, \"no pixel data",
"!= \"tlv\": return None, \"non-tlv payload byte string\" if ART_TLV_TYPE not in parsed['tlvs']:",
"parse_art_no(tlv): art_no, remainder, err = Namespace.pop_tu16(tlv.l, tlv.v) if err: return None, err if",
"payload\" if PIXEL_TLV_TYPE not in parsed['tlvs']: return None, \"no pixel data tlv in",
"outgoing_cltv_value, pament_secret=payment_secret, totol_msat= total_msat) old_len, content, err = BigSize.pop(unextended) assert err is None",
"if tlv.l % 5 != 0: return None, \"unexpected length\" remainder = tlv.v",
"pixels = [] if tlv.l % 5 != 0: return None, \"unexpected length\"",
"pixel_hex, remainder, err = Namespace.pop_bytes(5, remainder) if err: return None, err pixels.append(Pixel.from_bin(h2b(pixel_hex))) return"
] |
[] |
[
"MPI comm = MPI.COMM_WORLD size = comm.size rank = comm.rank array_size = 10",
"from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.size rank = comm.rank",
"%s sending %s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM) print ('on task',rank,'after Reduce: data",
"sending %s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM) print ('on task',rank,'after Reduce: data =",
"process %s sending %s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM) print ('on task',rank,'after Reduce:",
"import numpy from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.size rank",
"comm = MPI.COMM_WORLD size = comm.size rank = comm.rank array_size = 10 recvdata",
"= MPI.COMM_WORLD size = comm.size rank = comm.rank array_size = 10 recvdata =",
"= 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s",
"%s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM) print ('on task',rank,'after Reduce: data = ',recvdata)",
"senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM)",
"numpy from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.size rank =",
"= (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM) print",
"size = comm.size rank = comm.rank array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata",
"numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s \" %(rank , senddata))",
"(rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM) print ('on",
"rank = comm.rank array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\"",
"comm.size rank = comm.rank array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int)",
"MPI.COMM_WORLD size = comm.size rank = comm.rank array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int)",
"10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s \"",
"= numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s \" %(rank ,",
"print(\" process %s sending %s \" %(rank , senddata)) comm.Reduce(senddata,recvdata,root=0,op=MPI.SUM) print ('on task',rank,'after",
"import MPI comm = MPI.COMM_WORLD size = comm.size rank = comm.rank array_size =",
"array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending",
"mpi4py import MPI comm = MPI.COMM_WORLD size = comm.size rank = comm.rank array_size",
"= comm.rank array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process",
"recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s sending %s \" %(rank",
"<reponame>DzulJalali/Python-Pararel_SISTER import numpy from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.size",
"= comm.size rank = comm.rank array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata =",
"comm.rank array_size = 10 recvdata = numpy.zeros(array_size,dtype=numpy.int) senddata = (rank+1)*numpy.arange(array_size,dtype=numpy.int) print(\" process %s"
] |
[] |
[
"y else: return X def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's first csv",
"image dimension in format CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path = images_path self.dim",
"numpy as np from tensorflow import keras import pandas as pd import os",
"csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238",
"to images location :param dim: tuple indicating image dimension in format CHW \"\"\"",
"np.load(image_path, allow_pickle=True) if self.window: lb = self.window[0] ub = self.window[1] img[img < lb]",
"os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names))",
"X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n'] X_patient =",
"= self.window[0] ub = self.window[1] img[img < lb] = lb img[img > ub]",
"return merged_gen # def gen_train_test_split(datagen): # datagen. # gen = create_datagen(shuffle=True) # x1,",
"Suitable for building data generator for training and prediction. \"\"\" def __init__(self, images_path,",
"= next(csv_flow) dcm_data = next(dcm_flow) csv_X = csv_data[0] dcm_X_img = dcm_data[0] csv_y =",
"> ub] = ub img = (img - lb) / (ub - lb)",
"number of batches per epoch :return: number of batches per epoch \"\"\" return",
"\"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True to normalize, False",
"data :param index: index of the patient :return: X \"\"\" # Find list",
"+= 1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that yields [csv_X, dcm_X_img], csv_y,",
"'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC']",
"format CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path = images_path self.dim = dim self.indexes",
"of the patient :return: patient's first csv record \"\"\" X = np.empty(shape=(1, 7),",
"= images_path self.dim = dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def",
"- 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient =",
"the patient :return: X_dcm \"\"\" # Find list of IDs patient_ID = self.list_IDs[index]",
"\"\"\"Returns generator that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen",
"img[img > ub] = ub img = (img - lb) / (ub -",
"dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen #",
"lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator.",
"path to images location :param dim: tuple indicating image dimension in format CHW",
"csv_path: path to csv file with weeks and FVC file to load :return:",
"= next(dcm_flow) csv_X = csv_data[0] dcm_X_img = dcm_data[0] csv_y = csv_data[1][:, :, 0]",
"of the patient :return: X_dcm \"\"\" # Find list of IDs patient_ID =",
"= np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate data y[0] = self._load_y(self.csv_path, patient_ID) return",
"X_patient def _generate_y(self, patient_ID): \"\"\"Generates data containing patient's [1:] csv records :param patient_ID:",
"2), dtype=np.float32) # Generate data y[0] = self._load_y(self.csv_path, patient_ID) return y def _load_y(self,",
"shuffle: seed += 1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that yields [csv_X,",
"self.__len__()) i += 1 def __getitem__(self, index): \"\"\"Generate one patient's data :param index:",
"= weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] = 1 for i in",
"1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\"",
"lb img[img > ub] = ub img = (img - lb) / (ub",
"X_dcm = np.moveaxis(X_dcm, 1, -1) return X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale image",
"return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs))",
"weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC =",
"to_normalize=True): \"\"\"Initialization :param to_normalize: True to normalize, False otherwise :param csv_path: path to",
"break if shuffle: seed += 1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that",
"if is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y patient_num",
"inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756) /",
"index): \"\"\"Generate one patient's data :param index: index of the patient :return: X_dcm",
"self.__len__(), size=(1,))) while True: yield self.__getitem__(i % self.__len__()) i += 1 def __getitem__(self,",
"dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int)",
"csv_data = next(csv_flow) dcm_data = next(dcm_flow) csv_X = csv_data[0] dcm_X_img = dcm_data[0] csv_y",
"to return X and y, False to return X only \"\"\" self.to_normalize =",
"self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end()",
"(X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient",
"image_path: path to image to load :return: loaded image \"\"\" img = np.load(image_path,",
"weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def pad_y(self,",
":param index: index of the patient :return: X_dcm \"\"\" # Find list of",
"csv record \"\"\" X = np.empty(shape=(1, 7), dtype=np.float32) # Generate data X[0] =",
"def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed = 0 while True: csv_flow = csv_gen.flow(seed)",
"csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y patient_num += 1 if patient_num >",
"dtype=np.float32) # Generate data y[0] = self._load_y(self.csv_path, patient_ID) return y def _load_y(self, csv_path,",
"tensorflow import keras import pandas as pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data",
"with weeks and FVC file to load \"\"\" patients_df = pd.read_csv(csv_path) patient =",
"patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths",
"y[0] = self._load_y(self.csv_path, patient_ID) return y def _load_y(self, csv_path, patient_ID): \"\"\"Load csv with",
"def gen_train_test_split(datagen): # datagen. # gen = create_datagen(shuffle=True) # x1, y1, is_p_r1 =",
"= csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:, :, 1] if is_patient_record: yield [csv_X,",
"csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num = 1 while True: csv_data =",
"= np.empty(shape=(1, 7), dtype=np.float32) # Generate data X[0] = self._load_X(self.csv_path, patient_ID) return X",
"normalize, False otherwise :param csv_path: path to csv file location :param to_fit: True",
"images_path self.dim = dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def __len__(self):",
"= ub img = (img - lb) / (ub - lb) return img",
"Suitable for building data generator for training and prediction. \"\"\" def __init__(self, csv_path,",
"y def _load_y(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC",
"dcm_X_img = dcm_data[0] csv_y = csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:, :, 1]",
"True: csv_data = next(csv_flow) dcm_data = next(dcm_flow) csv_X = csv_data[0] dcm_X_img = dcm_data[0]",
"int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield self.__getitem__(i % self.__len__()) i += 1 def",
"on_epoch_end(self): \"\"\"Updates indexes after each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed):",
"= dcm_gen.flow(seed) patient_num = 1 while True: csv_data = next(csv_flow) dcm_data = next(dcm_flow)",
"generator for training and prediction. \"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param",
"weeks and FVC file to load :return: loaded csv file with weeks and",
"'Never smoked', 'Currently smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] =",
"7), dtype=np.float32) # Generate data X[0] = self._load_X(self.csv_path, patient_ID) return X def _load_X(self,",
"lb = self.window[0] ub = self.window[1] img[img < lb] = lb img[img >",
"np.empty(shape=(1, 7), dtype=np.float32) # Generate data X[0] = self._load_X(self.csv_path, patient_ID) return X def",
"return X, y else: return X def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's",
"data containing patient's images :param patient_ID: ID of the patient :return: patient's images",
"= self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1) return X_dcm def _load_dcm(self, image_path): \"\"\"Load",
"datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed = 0 while True: csv_flow =",
"patient's weeks and corresponding FVC :param csv_path: path to csv file with weeks",
"== patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes',",
"data containing patient's [1:] csv records :param patient_ID: ID of the patient :return:",
"and FVC file to load :return: loaded csv file with weeks and FVC",
"= patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy()",
":, 1] if is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img],",
"is_patient_record=True): seed = 0 while True: csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num",
"'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:,",
"= (img - lb) / (ub - lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates",
"= self.window[1] img[img < lb] = lb img[img > ub] = ub img",
"lb) / (ub - lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras",
"each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0,",
"and prediction. \"\"\" def __init__(self, images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization :param images_path:",
"self.window[1] img[img < lb] = lb img[img > ub] = ub img =",
"X, y else: return X def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's first",
"csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize:",
"csv_y patient_num += 1 if patient_num > 175: break if shuffle: seed +=",
"yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window)",
"data X = self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID) return X, y else:",
"weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] = 1 for i in range(-12,",
"csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen,",
":return: loaded image \"\"\" img = np.load(image_path, allow_pickle=True) if self.window: lb = self.window[0]",
"patient_ID: ID of the patient :return: patient's first csv record \"\"\" X =",
"/ 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy() return",
"file to load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True)",
"self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's images",
"next(dcm_flow) csv_X = csv_data[0] dcm_X_img = dcm_data[0] csv_y = csv_data[1][:, :, 0] csv_is_patient_record",
":param patient_ID: ID of the patient :return: patient's first csv record \"\"\" X",
"patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC'] =",
"patient's [1:] csv records \"\"\" y = np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate",
"X_patient = X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID): \"\"\"Generates data containing patient's [1:]",
"_merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen): # datagen. # gen",
"inplace=True) return csv_df # ==================================# # Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True):",
"DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable for building data",
"= self.list_IDs[index] # Generate data X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def",
"Keras Sequence based data generator. Suitable for building data generator for training and",
"pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC",
"0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] =",
"to load :return: loaded image \"\"\" img = np.load(image_path, allow_pickle=True) if self.window: lb",
"generator for training and prediction. \"\"\" def __init__(self, images_path, dim=(15, 512, 512), window=None):",
":param patient_ID: ID of the patient :return: patient's images \"\"\" # Initialization X_dcm",
"\"\"\"Generate one patient's data :param index: index of the patient :return: X \"\"\"",
"1 for i in range(-12, 134): if not np.any(csv_df['Weeks'] == i): csv_df =",
"\"\"\" # Find list of IDs patient_ID = self.list_IDs[index] # Generate data X",
"create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen =",
"Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4]",
"j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1) return X_dcm def _load_dcm(self, image_path):",
"ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] -",
"==================================# # Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed = 0 while",
"= 1 for i in range(-12, 134): if not np.any(csv_df['Weeks'] == i): csv_df",
"with weeks and FVC file to load :return: loaded csv file with weeks",
"Generate data X[0] = self._load_X(self.csv_path, patient_ID) return X def _load_X(self, csv_path, patient_ID): \"\"\"Load",
"after each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i =",
"= CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record)",
"X_patient = patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) / 7.055116199848975",
"to load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC",
"next(csv_flow) dcm_data = next(dcm_flow) csv_X = csv_data[0] dcm_X_img = dcm_data[0] csv_y = csv_data[1][:,",
"load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns =",
"csv_path self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the number",
"= self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] = 1",
"i, 'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:,",
"seed = 0 while True: csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num =",
"\"\"\" def __init__(self, images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization :param images_path: path to",
"for building data generator for training and prediction. \"\"\" def __init__(self, csv_path, to_fit=True,",
":param csv_path: path to csv file with weeks and FVC file to load",
"weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord']",
"Sequence based data generator. Suitable for building data generator for training and prediction.",
"gen_train_test_split(datagen): # datagen. # gen = create_datagen(shuffle=True) # x1, y1, is_p_r1 = next(gen)",
"if patient_num > 175: break if shuffle: seed += 1 def create_datagen(shuffle=True, window=None,",
"of the patient :return: X \"\"\" # Find list of IDs patient_ID =",
"def __getitem__(self, index): \"\"\"Generate one patient's data :param index: index of the patient",
"else: return X def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's first csv record",
"csv_df = csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True)",
"= 1 while True: csv_data = next(csv_flow) dcm_data = next(dcm_flow) csv_X = csv_data[0]",
"return X def _load_X(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding",
":param dim: tuple indicating image dimension in format CHW \"\"\" self.list_IDs = os.listdir(images_path)",
"= self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's",
"def __init__(self, images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization :param images_path: path to images",
"patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC",
"Find list of IDs patient_ID = self.list_IDs[index] # Generate data X = self._generate_X(patient_ID)",
"patient's images :param patient_ID: ID of the patient :return: patient's images \"\"\" #",
"path to image to load :return: loaded image \"\"\" img = np.load(image_path, allow_pickle=True)",
"seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield self.__getitem__(i % self.__len__())",
"csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle,",
"dcm_gen.flow(seed) patient_num = 1 while True: csv_data = next(csv_flow) dcm_data = next(dcm_flow) csv_X",
"csv with patient's weeks and corresponding FVC :param csv_path: path to csv file",
"dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen =",
"np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield",
"(csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================# #",
"np.moveaxis(X_dcm, 1, -1) return X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale image :param image_path:",
"if not np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0},",
"list of IDs patient_ID = self.list_IDs[index] # Generate data X = self._generate_X(patient_ID) if",
"= (X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238",
"self._load_X(self.csv_path, patient_ID) return X def _load_X(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks",
"0] csv_is_patient_record = csv_data[1][:, :, 1] if is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record",
"1 while True: csv_data = next(csv_flow) dcm_data = next(dcm_flow) csv_X = csv_data[0] dcm_X_img",
"location :param to_fit: True to return X and y, False to return X",
"= patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])]",
"[csv_X, dcm_X_img], csv_y patient_num += 1 if patient_num > 175: break if shuffle:",
"index of the patient :return: X_dcm \"\"\" # Find list of IDs patient_ID",
"= to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the number of batches",
"patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC :param csv_path: path to",
"merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen): # datagen.",
"self._load_y(self.csv_path, patient_ID) return y def _load_y(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks",
"image :param image_path: path to image to load :return: loaded image \"\"\" img",
"Generate data X = self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID) return X, y",
"data :param index: index of the patient :return: X_dcm \"\"\" # Find list",
"FVC file to load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID]",
"self.csv_path = csv_path self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes",
"dtype=np.float32) # Generate data X[0] = self._load_X(self.csv_path, patient_ID) return X def _load_X(self, csv_path,",
"patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC',",
"def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's first csv record :param patient_ID: ID",
"first csv record \"\"\" X = np.empty(shape=(1, 7), dtype=np.float32) # Generate data X[0]",
"_load_dcm(self, image_path): \"\"\"Load grayscale image :param image_path: path to image to load :return:",
"IDs patient_ID = self.list_IDs[index] # Generate data X = self._generate_X(patient_ID) if self.to_fit: y",
"per epoch :return: number of batches per epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self):",
"to load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns",
"def pad_y(self, csv_df): csv_df['isRecord'] = 1 for i in range(-12, 134): if not",
"self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit = to_fit self.indexes",
"__getitem__(self, index): \"\"\"Generate one patient's data :param index: index of the patient :return:",
"# Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names =",
"ID of the patient :return: patient's first csv record \"\"\" X = np.empty(shape=(1,",
"# Generate data X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def _generate_X(self, patient_ID):",
"y = self._generate_y(patient_ID) return X, y else: return X def _generate_X(self, patient_ID): \"\"\"Generates",
"'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df #",
"self.on_epoch_end() def __len__(self): \"\"\"Denotes the number of batches per epoch :return: number of",
"dcm_flow = dcm_gen.flow(seed) patient_num = 1 while True: csv_data = next(csv_flow) dcm_data =",
"patient's first csv record :param patient_ID: ID of the patient :return: patient's first",
":, 0] csv_is_patient_record = csv_data[1][:, :, 1] if is_patient_record: yield [csv_X, dcm_X_img], csv_y,",
"dcm_names = np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths =",
"enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1) return X_dcm def",
"weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] =",
"dcm_data = next(dcm_flow) csv_X = csv_data[0] dcm_X_img = dcm_data[0] csv_y = csv_data[1][:, :,",
"= int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield self.__getitem__(i % self.__len__()) i += 1",
"patient :return: patient's [1:] csv records \"\"\" y = np.empty(shape=(1, 146, 2), dtype=np.float32)",
"(X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID):",
"(ub - lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based",
"image to load :return: loaded image \"\"\" img = np.load(image_path, allow_pickle=True) if self.window:",
"False otherwise :param csv_path: path to csv file location :param to_fit: True to",
"csv_is_patient_record = csv_data[1][:, :, 1] if is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else:",
"ub img = (img - lb) / (ub - lb) return img class",
"with patient's weeks and corresponding FVC :param csv_path: path to csv file with",
"= ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n'] X_patient = patient.loc[0,",
"'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================# # Creating",
"= np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def __len__(self): \"\"\"Denotes the number of batches",
"dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen): # datagen. # gen =",
"prediction. \"\"\" def __init__(self, images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization :param images_path: path",
"return X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale image :param image_path: path to image",
"allow_pickle=True) if self.window: lb = self.window[0] ub = self.window[1] img[img < lb] =",
"\"\"\"Generate one patient's data :param index: index of the patient :return: X_dcm \"\"\"",
"134): if not np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord':",
"patient_ID = self.list_IDs[index] # Generate data X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1, ])",
"number of batches per epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after",
"= os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def",
"csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:, :, 1] if is_patient_record: yield [csv_X, dcm_X_img],",
"self.__getitem__(i % self.__len__()) i += 1 def __getitem__(self, index): \"\"\"Generate one patient's data",
"as np from tensorflow import keras import pandas as pd import os class",
"file to load :return: loaded csv file with weeks and FVC file to",
"def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's images :param patient_ID: ID of the",
"is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen): # datagen. # gen = create_datagen(shuffle=True) #",
"X_dcm, np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's images :param patient_ID:",
"if self.to_fit: y = self._generate_y(patient_ID) return X, y else: return X def _generate_X(self,",
"= 0 while True: csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num = 1",
"*self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)],",
"window def __len__(self): \"\"\"Denotes the number of batches per epoch :return: number of",
"file location :param to_fit: True to return X and y, False to return",
"pad_y(self, csv_df): csv_df['isRecord'] = 1 for i in range(-12, 134): if not np.any(csv_df['Weeks']",
"ub = self.window[1] img[img < lb] = lb img[img > ub] = ub",
"pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator.",
"patient_path = os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names",
"self.window: lb = self.window[0] ub = self.window[1] img[img < lb] = lb img[img",
"\"\"\"Generates data containing patient's images :param patient_ID: ID of the patient :return: patient's",
"img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable for",
"patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently",
"images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization :param images_path: path to images location :param",
"to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the number of batches per",
"# Generate data X[0] = self._load_X(self.csv_path, patient_ID) return X def _load_X(self, csv_path, patient_ID):",
"False to return X only \"\"\" self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path",
"X = np.empty(shape=(1, 7), dtype=np.float32) # Generate data X[0] = self._load_X(self.csv_path, patient_ID) return",
"os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] #",
":param images_path: path to images location :param dim: tuple indicating image dimension in",
"\"\"\" self.list_IDs = os.listdir(images_path) self.images_path = images_path self.dim = dim self.indexes = np.arange(len(self.list_IDs))",
"[f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] # Generate data for j, dcm_path in enumerate(patient_dcm_paths):",
"img[img < lb] = lb img[img > ub] = ub img = (img",
"img = (img - lb) / (ub - lb) return img class CsvDataGenerator(keras.utils.Sequence):",
"load :return: loaded image \"\"\" img = np.load(image_path, allow_pickle=True) if self.window: lb =",
"csv records :param patient_ID: ID of the patient :return: patient's [1:] csv records",
"file with weeks and FVC file to load :return: loaded csv file with",
"FVC file to load :return: loaded csv file with weeks and FVC file",
"import numpy as np from tensorflow import keras import pandas as pd import",
"X[0] = self._load_X(self.csv_path, patient_ID) return X def _load_X(self, csv_path, patient_ID): \"\"\"Load csv with",
"patient_ID) return y def _load_y(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and",
"patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return",
"self.list_IDs[index] # Generate data X = self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID) return",
"inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True,",
"index of the patient :return: X \"\"\" # Find list of IDs patient_ID",
"= dcm_data[0] csv_y = csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:, :, 1] if",
"self._generate_y(patient_ID) return X, y else: return X def _generate_X(self, patient_ID): \"\"\"Generates data containing",
"np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield self.__getitem__(i % self.__len__()) i",
"= np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name",
"index): \"\"\"Generate one patient's data :param index: index of the patient :return: X",
"to load :return: loaded csv file with weeks and FVC file to load",
"/ 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] -",
"= np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy'",
"smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019)",
"\"\"\"Initialization :param to_normalize: True to normalize, False otherwise :param csv_path: path to csv",
"_load_X(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC :param csv_path:",
"return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable",
"data generator. Suitable for building data generator for training and prediction. \"\"\" def",
"patient_ID = self.list_IDs[index] # Generate data X = self._generate_X(patient_ID) if self.to_fit: y =",
"(img - lb) / (ub - lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data",
"path to csv file with weeks and FVC file to load :return: loaded",
"csv_df['isRecord'] = 1 for i in range(-12, 134): if not np.any(csv_df['Weeks'] == i):",
"/ 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================# # Creating datagen def _merge_datagens(csv_gen,",
"csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y patient_num += 1 if patient_num > 175:",
"+= 1 if patient_num > 175: break if shuffle: seed += 1 def",
"self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756)",
"record \"\"\" X = np.empty(shape=(1, 7), dtype=np.float32) # Generate data X[0] = self._load_X(self.csv_path,",
"1 if patient_num > 175: break if shuffle: seed += 1 def create_datagen(shuffle=True,",
"patient_ID): \"\"\"Generates data containing patient's first csv record :param patient_ID: ID of the",
"patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks',",
"otherwise :param csv_path: path to csv file location :param to_fit: True to return",
"patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC)",
"% self.__len__()) i += 1 def __getitem__(self, index): \"\"\"Generate one patient's data :param",
"patient :return: patient's images \"\"\" # Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path",
"X_dcm \"\"\" # Find list of IDs patient_ID = self.list_IDs[index] # Generate data",
"the patient :return: patient's images \"\"\" # Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32)",
"as pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data",
"np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks',",
"location :param dim: tuple indicating image dimension in format CHW \"\"\" self.list_IDs =",
"# Find list of IDs patient_ID = self.list_IDs[index] # Generate data X =",
"and prediction. \"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True to",
"= (csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================#",
"os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable for",
"def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True to normalize, False otherwise",
"'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns] if",
"loaded image \"\"\" img = np.load(image_path, allow_pickle=True) if self.window: lb = self.window[0] ub",
"to return X only \"\"\" self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path =",
"ID of the patient :return: patient's [1:] csv records \"\"\" y = np.empty(shape=(1,",
"while True: csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num = 1 while True:",
"of IDs patient_ID = self.list_IDs[index] # Generate data X = self._generate_X(patient_ID) if self.to_fit:",
"first csv record :param patient_ID: ID of the patient :return: patient's first csv",
"# Generate data X = self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID) return X,",
"512, 512), window=None): \"\"\"Initialization :param images_path: path to images location :param dim: tuple",
"dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] # Generate data",
"\"\"\"Load grayscale image :param image_path: path to image to load :return: loaded image",
"self.dim = dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def __len__(self): \"\"\"Denotes",
"= weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df):",
"keras import pandas as pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras",
"load :return: loaded csv file with weeks and FVC file to load \"\"\"",
"- lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data",
"146, 2), dtype=np.float32) # Generate data y[0] = self._load_y(self.csv_path, patient_ID) return y def",
"if self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] -",
"patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC",
"def _generate_y(self, patient_ID): \"\"\"Generates data containing patient's [1:] csv records :param patient_ID: ID",
"self.on_epoch_end() self.window = window def __len__(self): \"\"\"Denotes the number of batches per epoch",
"\"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,)))",
"batches per epoch :return: number of batches per epoch \"\"\" return len(self.list_IDs) def",
"dim: tuple indicating image dimension in format CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path",
"np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the number of batches per epoch :return: number",
"return X_dcm, np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's images :param",
"# Find list of IDs patient_ID = self.list_IDs[index] # Generate data X_dcm =",
"DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen):",
"\"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after each epoch \"\"\" self.indexes =",
"patient :return: X_dcm \"\"\" # Find list of IDs patient_ID = self.list_IDs[index] #",
"def flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield self.__getitem__(i",
"the patient :return: patient's first csv record \"\"\" X = np.empty(shape=(1, 7), dtype=np.float32)",
"__init__(self, images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization :param images_path: path to images location",
"flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield self.__getitem__(i %",
"= lb img[img > ub] = ub img = (img - lb) /",
"for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1,",
"images_path: path to images location :param dim: tuple indicating image dimension in format",
"patient :return: patient's first csv record \"\"\" X = np.empty(shape=(1, 7), dtype=np.float32) #",
"in dcm_names] # Generate data for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] =",
"31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID): \"\"\"Generates data",
"tuple indicating image dimension in format CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path =",
"for building data generator for training and prediction. \"\"\" def __init__(self, images_path, dim=(15,",
"csv_data[1][:, :, 1] if is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X,",
"= self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID) return X, y else: return X",
"range(-12, 134): if not np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks': i, 'FVC': 0,",
"in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names]",
":return: X \"\"\" # Find list of IDs patient_ID = self.list_IDs[index] # Generate",
"X def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's first csv record :param patient_ID:",
"smoked', 'Currently smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age']",
"== patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC =",
"image \"\"\" img = np.load(image_path, allow_pickle=True) if self.window: lb = self.window[0] ub =",
"# Generate data y[0] = self._load_y(self.csv_path, patient_ID) return y def _load_y(self, csv_path, patient_ID):",
"patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']] weeks_FVC =",
"= np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,))) while True:",
"= self._load_X(self.csv_path, patient_ID) return X def _load_X(self, csv_path, patient_ID): \"\"\"Load csv with patient's",
"= csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num = 1 while True: csv_data = next(csv_flow)",
"= sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] # Generate data for",
"for dcm_num in dcm_names] # Generate data for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0,",
"self.list_IDs = os.listdir(images_path) self.images_path = images_path self.dim = dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end()",
"building data generator for training and prediction. \"\"\" def __init__(self, images_path, dim=(15, 512,",
"the number of batches per epoch :return: number of batches per epoch \"\"\"",
"> 175: break if shuffle: seed += 1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns",
"= os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names =",
"self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID) return X, y else: return X def",
"patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n'] X_patient",
"dcm_data[0] csv_y = csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:, :, 1] if is_patient_record:",
":param to_normalize: True to normalize, False otherwise :param csv_path: path to csv file",
"window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen): #",
"generator. Suitable for building data generator for training and prediction. \"\"\" def __init__(self,",
"data y[0] = self._load_y(self.csv_path, patient_ID) return y def _load_y(self, csv_path, patient_ID): \"\"\"Load csv",
":return: patient's images \"\"\" # Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path =",
"X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates data containing",
"csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================# # Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True,",
"X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale image :param image_path: path to image to",
"records \"\"\" y = np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate data y[0] =",
"data generator for training and prediction. \"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization",
"\"\"\" y = np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate data y[0] = self._load_y(self.csv_path,",
"_generate_X(self, patient_ID): \"\"\"Generates data containing patient's images :param patient_ID: ID of the patient",
"[1:] csv records :param patient_ID: ID of the patient :return: patient's [1:] csv",
"2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy()",
"for i in range(-12, 134): if not np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks':",
"images location :param dim: tuple indicating image dimension in format CHW \"\"\" self.list_IDs",
"one patient's data :param index: index of the patient :return: X \"\"\" #",
"= DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def",
"dcm_X_img], csv_y patient_num += 1 if patient_num > 175: break if shuffle: seed",
"]) def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's images :param patient_ID: ID of",
"ub] = ub img = (img - lb) / (ub - lb) return",
"__len__(self): \"\"\"Denotes the number of batches per epoch :return: number of batches per",
"csv file with weeks and FVC file to load \"\"\" patients_df = pd.read_csv(csv_path)",
"np from tensorflow import keras import pandas as pd import os class DcmDataGenerator(keras.utils.Sequence):",
"patient_ID: ID of the patient :return: patient's [1:] csv records \"\"\" y =",
"['Weeks', 'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC",
"weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] = 1 for i in range(-12, 134): if",
"CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable for building data",
"img = np.load(image_path, allow_pickle=True) if self.window: lb = self.window[0] ub = self.window[1] img[img",
"1] if is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y",
"\"\"\"Generates data containing patient's [1:] csv records :param patient_ID: ID of the patient",
"= patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC']",
"images \"\"\" # Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID)",
":param csv_path: path to csv file location :param to_fit: True to return X",
"patient's images \"\"\" # Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path,",
"merged_gen # def gen_train_test_split(datagen): # datagen. # gen = create_datagen(shuffle=True) # x1, y1,",
"data for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm,",
"True: csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num = 1 while True: csv_data",
"patient_num += 1 if patient_num > 175: break if shuffle: seed += 1",
"dcm_name in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in",
"csv file location :param to_fit: True to return X and y, False to",
"i = int(np.random.randint(0, self.__len__(), size=(1,))) while True: yield self.__getitem__(i % self.__len__()) i +=",
"self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the number of",
"patient's data :param index: index of the patient :return: X_dcm \"\"\" # Find",
"corresponding FVC :param csv_path: path to csv file with weeks and FVC file",
"-1) return X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale image :param image_path: path to",
"= patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked',",
"y = np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate data y[0] = self._load_y(self.csv_path, patient_ID)",
"indicating image dimension in format CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path = images_path",
"_load_y(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC :param csv_path:",
"\"\"\" # Find list of IDs patient_ID = self.list_IDs[index] # Generate data X_dcm",
"def __len__(self): \"\"\"Denotes the number of batches per epoch :return: number of batches",
"records :param patient_ID: ID of the patient :return: patient's [1:] csv records \"\"\"",
"= [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] # Generate data for j, dcm_path in",
"patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] # Generate data for j, dcm_path",
"indexes after each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i",
"pandas as pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based",
"only \"\"\" self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit =",
"np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate data y[0] = self._load_y(self.csv_path, patient_ID) return y",
"shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen): # datagen. # gen = create_datagen(shuffle=True)",
"patient_ID): \"\"\"Generates data containing patient's images :param patient_ID: ID of the patient :return:",
"# ==================================# # Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed = 0",
"if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True)",
"1, -1) return X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale image :param image_path: path",
"- lb) / (ub - lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for",
"self.images_path = images_path self.dim = dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window",
"__init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True to normalize, False otherwise :param",
"building data generator for training and prediction. \"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True):",
"X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for",
"import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable",
"= X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID): \"\"\"Generates data containing patient's [1:] csv",
"= self.list_IDs[index] # Generate data X = self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID)",
"return X only \"\"\" self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path",
"while True: csv_data = next(csv_flow) dcm_data = next(dcm_flow) csv_X = csv_data[0] dcm_X_img =",
"= csv_path self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the",
"X def _load_X(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC",
"self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(), size=(1,))) while",
"based data generator. Suitable for building data generator for training and prediction. \"\"\"",
"Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed = 0 while True: csv_flow",
"epoch :return: number of batches per epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates",
"# Generate data for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm",
"= csv_data[1][:, :, 1] if is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield",
"to image to load :return: loaded image \"\"\" img = np.load(image_path, allow_pickle=True) if",
"FVC :param csv_path: path to csv file with weeks and FVC file to",
"# Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed = 0 while True:",
"CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return",
"self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1) return X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale",
"data generator for training and prediction. \"\"\" def __init__(self, images_path, dim=(15, 512, 512),",
"\"\"\" img = np.load(image_path, allow_pickle=True) if self.window: lb = self.window[0] ub = self.window[1]",
"to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs))",
"dim=(15, 512, 512), window=None): \"\"\"Initialization :param images_path: path to images location :param dim:",
"\"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks',",
"self.window = window def __len__(self): \"\"\"Denotes the number of batches per epoch :return:",
"from tensorflow import keras import pandas as pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates",
"- 31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID): \"\"\"Generates",
"data X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates data",
"def _load_dcm(self, image_path): \"\"\"Load grayscale image :param image_path: path to image to load",
"patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n']",
"generator that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen =",
"i += 1 def __getitem__(self, index): \"\"\"Generate one patient's data :param index: index",
"and y, False to return X only \"\"\" self.to_normalize = to_normalize self.list_IDs =",
"0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC']",
"def on_epoch_end(self): \"\"\"Updates indexes after each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self,",
"dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] # Generate",
"CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path = images_path self.dim = dim self.indexes =",
"_generate_X(self, patient_ID): \"\"\"Generates data containing patient's first csv record :param patient_ID: ID of",
"path to csv file location :param to_fit: True to return X and y,",
"csv_df): csv_df['isRecord'] = 1 for i in range(-12, 134): if not np.any(csv_df['Weeks'] ==",
"Generate data X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates",
"= pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age',",
"not np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0}, ignore_index=True)",
"csv_y = csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:, :, 1] if is_patient_record: yield",
"X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1) return X_dcm def _load_dcm(self,",
"training and prediction. \"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True",
"the patient :return: X \"\"\" # Find list of IDs patient_ID = self.list_IDs[index]",
"= os.listdir(images_path) self.images_path = images_path self.dim = dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window",
"csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num = 1 while True: csv_data = next(csv_flow) dcm_data",
"= _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen # def gen_train_test_split(datagen): # datagen. #",
"[csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen",
"epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after each epoch \"\"\" self.indexes",
"IDs patient_ID = self.list_IDs[index] # Generate data X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1,",
"/ (ub - lb) return img class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence",
"patient_ID) return X def _load_X(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and",
"weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] = 1 for i",
"os.listdir(images_path) self.images_path = images_path self.dim = dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window =",
"y, False to return X only \"\"\" self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4])",
"[csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y patient_num += 1 if",
"512), window=None): \"\"\"Initialization :param images_path: path to images location :param dim: tuple indicating",
"else: yield [csv_X, dcm_X_img], csv_y patient_num += 1 if patient_num > 175: break",
"seed += 1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that yields [csv_X, dcm_X_img],",
"class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable for building",
"= np.moveaxis(X_dcm, 1, -1) return X_dcm def _load_dcm(self, image_path): \"\"\"Load grayscale image :param",
"7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475)",
"containing patient's first csv record :param patient_ID: ID of the patient :return: patient's",
"and corresponding FVC :param csv_path: path to csv file with weeks and FVC",
"data X[0] = self._load_X(self.csv_path, patient_ID) return X def _load_X(self, csv_path, patient_ID): \"\"\"Load csv",
"X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) /",
"patient's data :param index: index of the patient :return: X \"\"\" # Find",
"np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def __len__(self): \"\"\"Denotes the number of batches per",
"# def gen_train_test_split(datagen): # datagen. # gen = create_datagen(shuffle=True) # x1, y1, is_p_r1",
"Generate data y[0] = self._load_y(self.csv_path, patient_ID) return y def _load_y(self, csv_path, patient_ID): \"\"\"Load",
"X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy() return X_patient def",
"for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num",
"self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the number of batches per epoch",
"csv record :param patient_ID: ID of the patient :return: patient's first csv record",
"patient_num = 1 while True: csv_data = next(csv_flow) dcm_data = next(dcm_flow) csv_X =",
"of batches per epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after each",
"patient_ID: ID of the patient :return: patient's images \"\"\" # Initialization X_dcm =",
"dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def __len__(self): \"\"\"Denotes the number",
"= csv_data[0] dcm_X_img = dcm_data[0] csv_y = csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:,",
"self.window[0] ub = self.window[1] img[img < lb] = lb img[img > ub] =",
"window=None, is_patient_record=True): \"\"\"Returns generator that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv',",
"Generate data for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm =",
"of the patient :return: patient's images \"\"\" # Initialization X_dcm = np.empty((1, *self.dim),",
":return: loaded csv file with weeks and FVC file to load \"\"\" patients_df",
"= np.load(image_path, allow_pickle=True) if self.window: lb = self.window[0] ub = self.window[1] img[img <",
"X \"\"\" # Find list of IDs patient_ID = self.list_IDs[index] # Generate data",
"load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC =",
"to csv file location :param to_fit: True to return X and y, False",
"dcm_gen, shuffle=True, is_patient_record=True): seed = 0 while True: csv_flow = csv_gen.flow(seed) dcm_flow =",
"data containing patient's first csv record :param patient_ID: ID of the patient :return:",
"= csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if",
"return X_patient def _generate_y(self, patient_ID): \"\"\"Generates data containing patient's [1:] csv records :param",
":param patient_ID: ID of the patient :return: patient's [1:] csv records \"\"\" y",
"len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def",
"prediction. \"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True to normalize,",
":param image_path: path to image to load :return: loaded image \"\"\" img =",
"67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks']",
"for training and prediction. \"\"\" def __init__(self, images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization",
":return: number of batches per epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes",
"csv file with weeks and FVC file to load :return: loaded csv file",
"'FVC']] weeks_FVC = weeks_FVC[~weeks_FVC.duplicated(['Weeks'])] weeks_FVC = self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def",
"np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names = np.array([dcm_name[:-4] for dcm_name in",
"- 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================# # Creating datagen",
"image_path): \"\"\"Load grayscale image :param image_path: path to image to load :return: loaded",
"ID of the patient :return: patient's images \"\"\" # Initialization X_dcm = np.empty((1,",
"= np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self): \"\"\"Denotes the number of batches per epoch :return:",
"[1:] csv records \"\"\" y = np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate data",
":param to_fit: True to return X and y, False to return X only",
"'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns] if self.to_normalize: X_patient['Age']",
"X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID): \"\"\"Generates data containing patient's [1:] csv records",
"loaded csv file with weeks and FVC file to load \"\"\" patients_df =",
"_merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed = 0 while True: csv_flow = csv_gen.flow(seed) dcm_flow",
"\"\"\"Generates data for Keras Sequence based data generator. Suitable for building data generator",
"for training and prediction. \"\"\" def __init__(self, csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize:",
"return y def _load_y(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding",
"175: break if shuffle: seed += 1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator",
"dcm_num in dcm_names] # Generate data for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j]",
"/ 23.265510111399017 X_patient = X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID): \"\"\"Generates data containing",
"if shuffle: seed += 1 def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that yields",
"csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks', inplace=True) if self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756)",
"yield self.__getitem__(i % self.__len__()) i += 1 def __getitem__(self, index): \"\"\"Generate one patient's",
"patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never",
"of batches per epoch :return: number of batches per epoch \"\"\" return len(self.list_IDs)",
"return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] = 1 for i in range(-12, 134):",
"\"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:,",
"np.array([dcm_name[:-4] for dcm_name in os.listdir(patient_path)], dtype=int) dcm_names = sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for",
"weeks and FVC file to load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient']",
"'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns] if self.to_normalize:",
"['Weeks', 'FVC', 'Age', 'Ex-smoker', 'Never smoked', 'Currently smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns]",
"of the patient :return: patient's [1:] csv records \"\"\" y = np.empty(shape=(1, 146,",
"i): csv_df = csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True) csv_df.drop(columns='Weeks',",
"one patient's data :param index: index of the patient :return: X_dcm \"\"\" #",
"csv_path: path to csv file location :param to_fit: True to return X and",
"lb] = lb img[img > ub] = ub img = (img - lb)",
"(X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks']",
"index: index of the patient :return: X \"\"\" # Find list of IDs",
":return: patient's [1:] csv records \"\"\" y = np.empty(shape=(1, 146, 2), dtype=np.float32) #",
"X and y, False to return X only \"\"\" self.to_normalize = to_normalize self.list_IDs",
":param index: index of the patient :return: X \"\"\" # Find list of",
"dcm_names] # Generate data for j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path)",
"to csv file with weeks and FVC file to load :return: loaded csv",
"csv_data[0] dcm_X_img = dcm_data[0] csv_y = csv_data[1][:, :, 0] csv_is_patient_record = csv_data[1][:, :,",
"\"\"\"Initialization :param images_path: path to images location :param dim: tuple indicating image dimension",
"2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================# # Creating datagen def",
"weeks and corresponding FVC :param csv_path: path to csv file with weeks and",
"\"\"\" self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit = to_fit",
"X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) /",
"in range(-12, 134): if not np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks': i, 'FVC':",
"- 67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] =",
"class CsvDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence based data generator. Suitable for building",
"patient_num > 175: break if shuffle: seed += 1 def create_datagen(shuffle=True, window=None, is_patient_record=True):",
"patient :return: X \"\"\" # Find list of IDs patient_ID = self.list_IDs[index] #",
"per epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after each epoch \"\"\"",
"'Currently smokes', 'Sex_n'] X_patient = patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age'] -",
"'Sex_n'] X_patient = patient.loc[0, X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) /",
"= (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy() return X_patient def _generate_y(self,",
"to_normalize: True to normalize, False otherwise :param csv_path: path to csv file location",
"Find list of IDs patient_ID = self.list_IDs[index] # Generate data X_dcm = self._generate_X(patient_ID)",
"True: yield self.__getitem__(i % self.__len__()) i += 1 def __getitem__(self, index): \"\"\"Generate one",
"pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) X_columns = ['Weeks', 'FVC', 'Age', 'Ex-smoker',",
"832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df # ==================================# # Creating datagen def _merge_datagens(csv_gen, dcm_gen,",
"grayscale image :param image_path: path to image to load :return: loaded image \"\"\"",
"23.265510111399017 X_patient = X_patient.to_numpy() return X_patient def _generate_y(self, patient_ID): \"\"\"Generates data containing patient's",
"import pandas as pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for Keras Sequence",
"return X and y, False to return X only \"\"\" self.to_normalize = to_normalize",
"yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y patient_num += 1",
"training and prediction. \"\"\" def __init__(self, images_path, dim=(15, 512, 512), window=None): \"\"\"Initialization :param",
"containing patient's images :param patient_ID: ID of the patient :return: patient's images \"\"\"",
"to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True to normalize, False otherwise :param csv_path: path",
"832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017 X_patient = X_patient.to_numpy() return X_patient",
"csv_X = csv_data[0] dcm_X_img = dcm_data[0] csv_y = csv_data[1][:, :, 0] csv_is_patient_record =",
"dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y patient_num += 1 if patient_num",
":return: patient's first csv record \"\"\" X = np.empty(shape=(1, 7), dtype=np.float32) # Generate",
"j, dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1)",
"\"\"\"Denotes the number of batches per epoch :return: number of batches per epoch",
"the patient :return: patient's [1:] csv records \"\"\" y = np.empty(shape=(1, 146, 2),",
"def _load_y(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC :param",
"return X def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's first csv record :param",
"X_columns] if self.to_normalize: X_patient['Age'] = (X_patient['Age'] - 67.18850871530019) / 7.055116199848975 X_patient['FVC'] = (X_patient['FVC']",
"shuffle=True, is_patient_record=True): seed = 0 while True: csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed)",
"= pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] == patient_ID] patient.reset_index(inplace=True) weeks_FVC = patient.loc[1:, ['Weeks', 'FVC']]",
"csv_path, to_fit=True, to_normalize=True): \"\"\"Initialization :param to_normalize: True to normalize, False otherwise :param csv_path:",
"0 while True: csv_flow = csv_gen.flow(seed) dcm_flow = dcm_gen.flow(seed) patient_num = 1 while",
"_generate_y(self, patient_ID): \"\"\"Generates data containing patient's [1:] csv records :param patient_ID: ID of",
"dcm_path in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1) return",
"is_patient_record=True): \"\"\"Returns generator that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True)",
"self.list_IDs[index] # Generate data X_dcm = self._generate_X(patient_ID) return X_dcm, np.array([1, ]) def _generate_X(self,",
"def _load_X(self, csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC :param",
"index: index of the patient :return: X_dcm \"\"\" # Find list of IDs",
"yield [csv_X, dcm_X_img], csv_y patient_num += 1 if patient_num > 175: break if",
"self.pad_y(weeks_FVC) weeks_FVC = weeks_FVC.to_numpy() return weeks_FVC def pad_y(self, csv_df): csv_df['isRecord'] = 1 for",
"+= 1 def __getitem__(self, index): \"\"\"Generate one patient's data :param index: index of",
"= (X_patient['FVC'] - 2690.479018721756) / 832.5021066817238 X_patient['Weeks'] = (X_patient['Weeks'] - 31.861846352485475) / 23.265510111399017",
"csv_path, patient_ID): \"\"\"Load csv with patient's weeks and corresponding FVC :param csv_path: path",
"csv_df # ==================================# # Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed =",
"1 def __getitem__(self, index): \"\"\"Generate one patient's data :param index: index of the",
"in enumerate(patient_dcm_paths): X_dcm[0, j] = self._load_dcm(dcm_path) X_dcm = np.moveaxis(X_dcm, 1, -1) return X_dcm",
"\"\"\" X = np.empty(shape=(1, 7), dtype=np.float32) # Generate data X[0] = self._load_X(self.csv_path, patient_ID)",
"True to normalize, False otherwise :param csv_path: path to csv file location :param",
"to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen, dcm_datagen, shuffle=shuffle, is_patient_record=is_patient_record) return merged_gen",
"window=None): \"\"\"Initialization :param images_path: path to images location :param dim: tuple indicating image",
"that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train',",
"batches per epoch \"\"\" return len(self.list_IDs) def on_epoch_end(self): \"\"\"Updates indexes after each epoch",
"= to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit = to_fit self.indexes =",
"is_patient_record: yield [csv_X, dcm_X_img], csv_y, csv_is_patient_record else: yield [csv_X, dcm_X_img], csv_y patient_num +=",
"csv records \"\"\" y = np.empty(shape=(1, 146, 2), dtype=np.float32) # Generate data y[0]",
"and FVC file to load \"\"\" patients_df = pd.read_csv(csv_path) patient = patients_df[patients_df['Patient'] ==",
"dimension in format CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path = images_path self.dim =",
"size=(1,))) while True: yield self.__getitem__(i % self.__len__()) i += 1 def __getitem__(self, index):",
"sorted(list(dcm_names)) patient_dcm_paths = [f'{self.images_path}/{patient_ID}/{dcm_num}.npy' for dcm_num in dcm_names] # Generate data for j,",
"os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit = to_fit self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() def __len__(self):",
"\"\"\"Updates indexes after each epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed)",
"containing patient's [1:] csv records :param patient_ID: ID of the patient :return: patient's",
"< lb] = lb img[img > ub] = ub img = (img -",
"self.to_fit: y = self._generate_y(patient_ID) return X, y else: return X def _generate_X(self, patient_ID):",
"patient_ID): \"\"\"Generates data containing patient's [1:] csv records :param patient_ID: ID of the",
"to_fit: True to return X and y, False to return X only \"\"\"",
"data for Keras Sequence based data generator. Suitable for building data generator for",
"while True: yield self.__getitem__(i % self.__len__()) i += 1 def __getitem__(self, index): \"\"\"Generate",
"epoch \"\"\" self.indexes = np.arange(len(self.list_IDs)) def flow(self, seed): np.random.seed(seed) i = int(np.random.randint(0, self.__len__(),",
"if self.window: lb = self.window[0] ub = self.window[1] img[img < lb] = lb",
"list of IDs patient_ID = self.list_IDs[index] # Generate data X_dcm = self._generate_X(patient_ID) return",
"return csv_df # ==================================# # Creating datagen def _merge_datagens(csv_gen, dcm_gen, shuffle=True, is_patient_record=True): seed",
"\"\"\"Generates data containing patient's first csv record :param patient_ID: ID of the patient",
"X only \"\"\" self.to_normalize = to_normalize self.list_IDs = os.listdir(csv_path[:-4]) self.csv_path = csv_path self.to_fit",
"patient's first csv record \"\"\" X = np.empty(shape=(1, 7), dtype=np.float32) # Generate data",
"def create_datagen(shuffle=True, window=None, is_patient_record=True): \"\"\"Returns generator that yields [csv_X, dcm_X_img], csv_y, csv_is_patient_record\"\"\" csv_datagen",
"images :param patient_ID: ID of the patient :return: patient's images \"\"\" # Initialization",
"of IDs patient_ID = self.list_IDs[index] # Generate data X_dcm = self._generate_X(patient_ID) return X_dcm,",
"for Keras Sequence based data generator. Suitable for building data generator for training",
"\"\"\" # Initialization X_dcm = np.empty((1, *self.dim), dtype=np.float32) patient_path = os.path.join(self.images_path, patient_ID) dcm_names",
"to normalize, False otherwise :param csv_path: path to csv file location :param to_fit:",
"X = self._generate_X(patient_ID) if self.to_fit: y = self._generate_y(patient_ID) return X, y else: return",
"self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def __len__(self): \"\"\"Denotes the number of",
"\"\"\"Load csv with patient's weeks and corresponding FVC :param csv_path: path to csv",
"record :param patient_ID: ID of the patient :return: patient's first csv record \"\"\"",
"i in range(-12, 134): if not np.any(csv_df['Weeks'] == i): csv_df = csv_df.append({'Weeks': i,",
"csv_y, csv_is_patient_record\"\"\" csv_datagen = CsvDataGenerator('../../data/processed/train.csv', to_normalize=True) dcm_datagen = DcmDataGenerator('../../data/processed/train', window=window) merged_gen = _merge_datagens(csv_datagen,",
"= self._load_y(self.csv_path, patient_ID) return y def _load_y(self, csv_path, patient_ID): \"\"\"Load csv with patient's",
"patient's [1:] csv records :param patient_ID: ID of the patient :return: patient's [1:]",
"= dim self.indexes = np.arange(len(self.list_IDs)) self.on_epoch_end() self.window = window def __len__(self): \"\"\"Denotes the",
"== i): csv_df = csv_df.append({'Weeks': i, 'FVC': 0, 'isRecord': 0}, ignore_index=True) csv_df.sort_values('Weeks', inplace=True)",
"= self._generate_y(patient_ID) return X, y else: return X def _generate_X(self, patient_ID): \"\"\"Generates data",
"self.to_normalize: csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return",
"True to return X and y, False to return X only \"\"\" self.to_normalize",
":return: X_dcm \"\"\" # Find list of IDs patient_ID = self.list_IDs[index] # Generate",
"= window def __len__(self): \"\"\"Denotes the number of batches per epoch :return: number",
"file with weeks and FVC file to load \"\"\" patients_df = pd.read_csv(csv_path) patient",
"in format CHW \"\"\" self.list_IDs = os.listdir(images_path) self.images_path = images_path self.dim = dim",
"np.array([1, ]) def _generate_X(self, patient_ID): \"\"\"Generates data containing patient's images :param patient_ID: ID",
"csv_df.loc[:, 'FVC'] = (csv_df.loc[:, 'FVC'] - 2690.479018721756) / 832.5021066817238 csv_df.reset_index(drop=True, inplace=True) return csv_df",
"import keras import pandas as pd import os class DcmDataGenerator(keras.utils.Sequence): \"\"\"Generates data for"
] |
[
"'print_results()'. If FuzzySearch is initiated with a properly formated JSON file, calling 'run()'",
"JSON file, calling 'run()' with run through the class methods and print out",
"test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word search' on",
"+1} Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except KeyError: pass def",
"the results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict",
"except KeyError: pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is",
"print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy",
"as the argument. Once initiated, the 'run()' method will execute the 'fuzzy search'",
"formated string \"\"\" for query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for",
"in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" )",
"'run()' method will execute the 'fuzzy search' and print the results. \"\"\" def",
"-*- coding: utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a 'fuzzy search'",
"for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy",
"class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word search' on given JSON. See test_input.json",
"def print_results(self): \"\"\" Prints fuzzy_search_dict data in formated string \"\"\" for query in",
"See test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word search'",
"word search' on given JSON. See test_input.json for JSON format. Instantiate FuzzyWordSearch with",
"results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict data",
"to the JSON file as the argument. Once initiated, the 'run()' method will",
"# -*- coding: utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a 'fuzzy",
"execute the 'fuzzy search' and print the results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self,",
"the 'fuzzy search' and print the results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath)",
"'fuzzy word search' on given JSON. See test_input.json for JSON format. Instantiate FuzzyWordSearch",
"initiated, the 'run()' method will execute the 'fuzzy search' and print the results.",
"phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\"",
"python # -*- coding: utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a",
"Performs a 'fuzzy search' on given JSON. # See test_input.json for JSON format",
"Search: {phrase['fuzzy match']}\"\"\" ) except KeyError: pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and",
"print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except KeyError:",
"format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word search' on given JSON. See",
"for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word search' on given",
"print the results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints",
"pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is initiated with",
"print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is initiated with a properly",
"utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a 'fuzzy search' on given",
"a 'fuzzy search' on given JSON. # See test_input.json for JSON format class",
"string \"\"\" for query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase",
"search' and print the results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self):",
"formated JSON file, calling 'run()' with run through the class methods and print",
"on given JSON. # See test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs",
"lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a 'fuzzy search' on given JSON. # See",
"Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except KeyError: pass def print_results_dict(self):",
"on given JSON. See test_input.json for JSON format. Instantiate FuzzyWordSearch with the path",
"calling 'run()' with run through the class methods and print out the result.",
"FuzzySearch is initiated with a properly formated JSON file, calling 'run()' with run",
"{query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy Search:",
"is initiated with a properly formated JSON file, calling 'run()' with run through",
"for query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]:",
"Instantiate FuzzyWordSearch with the path to the JSON file as the argument. Once",
"JSON file\"\"\" #!/usr/bin/env python # -*- coding: utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork",
"argument. Once initiated, the 'run()' method will execute the 'fuzzy search' and print",
"self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1}",
"{phrase['fuzzy match']}\"\"\" ) except KeyError: pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'.",
"the argument. Once initiated, the 'run()' method will execute the 'fuzzy search' and",
"'run()' with run through the class methods and print out the result. \"\"\"",
"def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is initiated with a",
"from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a 'fuzzy search' on given JSON. #",
"a 'fuzzy word search' on given JSON. See test_input.json for JSON format. Instantiate",
"a 'fuzzy search on on JSON file\"\"\" #!/usr/bin/env python # -*- coding: utf-8",
"fuzzy_search_dict data in formated string \"\"\" for query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]:",
"f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except KeyError: pass",
"properly formated JSON file, calling 'run()' with run through the class methods and",
"'fuzzy search' on given JSON. # See test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork):",
"'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is initiated with a properly formated JSON file,",
"{phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except KeyError: pass def print_results_dict(self): \"\"\"",
"def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict data in formated",
"and 'print_results()'. If FuzzySearch is initiated with a properly formated JSON file, calling",
"# See test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word",
"the 'run()' method will execute the 'fuzzy search' and print the results. \"\"\"",
"path to the JSON file as the argument. Once initiated, the 'run()' method",
"a properly formated JSON file, calling 'run()' with run through the class methods",
"\"\"\" for query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in",
"Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is initiated with a properly formated JSON",
"file, calling 'run()' with run through the class methods and print out the",
"query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print(",
"if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original",
"phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except KeyError: pass def print_results_dict(self): \"\"\" Calls",
"json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict data in formated string \"\"\" for query",
"# Performs a 'fuzzy search' on given JSON. # See test_input.json for JSON",
"match']}\"\"\" ) except KeyError: pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If",
") except KeyError: pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch",
"format. Instantiate FuzzyWordSearch with the path to the JSON file as the argument.",
"given JSON. See test_input.json for JSON format. Instantiate FuzzyWordSearch with the path to",
"JSON. # See test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy",
"\"\"\" Prints fuzzy_search_dict data in formated string \"\"\" for query in self.fuzzy_search_dict: try:",
"in formated string \"\"\" for query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\")",
"will execute the 'fuzzy search' and print the results. \"\"\" def __init__(self, json_filepath):",
"FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word search' on given JSON. See test_input.json for",
"#!/usr/bin/env python # -*- coding: utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs",
"JSON format. Instantiate FuzzyWordSearch with the path to the JSON file as the",
"'fuzzy search' and print the results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def",
"in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase)",
"on JSON file\"\"\" #!/usr/bin/env python # -*- coding: utf-8 -*- from lib.fuzzy_word_search_work import",
"the path to the JSON file as the argument. Once initiated, the 'run()'",
"with run through the class methods and print out the result. \"\"\" print(self.fuzzy_search_dict)",
"search' on given JSON. See test_input.json for JSON format. Instantiate FuzzyWordSearch with the",
"import FuzzyWordSearchWork # Performs a 'fuzzy search' on given JSON. # See test_input.json",
"\"\"\" Performs a 'fuzzy word search' on given JSON. See test_input.json for JSON",
"\"\"\"This module performs a 'fuzzy search on on JSON file\"\"\" #!/usr/bin/env python #",
"<filename>lib/fuzzy_word_search_results.py \"\"\"This module performs a 'fuzzy search on on JSON file\"\"\" #!/usr/bin/env python",
"test_input.json for JSON format. Instantiate FuzzyWordSearch with the path to the JSON file",
"for JSON format. Instantiate FuzzyWordSearch with the path to the JSON file as",
"search' on given JSON. # See test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\"",
"json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict data in formated string \"\"\"",
"Prints fuzzy_search_dict data in formated string \"\"\" for query in self.fuzzy_search_dict: try: if",
"JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a 'fuzzy word search' on given JSON.",
"See test_input.json for JSON format. Instantiate FuzzyWordSearch with the path to the JSON",
"'fuzzy search on on JSON file\"\"\" #!/usr/bin/env python # -*- coding: utf-8 -*-",
"initiated with a properly formated JSON file, calling 'run()' with run through the",
"JSON. See test_input.json for JSON format. Instantiate FuzzyWordSearch with the path to the",
"FuzzyWordSearchWork # Performs a 'fuzzy search' on given JSON. # See test_input.json for",
"coding: utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a 'fuzzy search' on",
"self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']}",
"-*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork # Performs a 'fuzzy search' on given JSON.",
"with a properly formated JSON file, calling 'run()' with run through the class",
"try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery: {query}\") for phrase in self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase:",
"file\"\"\" #!/usr/bin/env python # -*- coding: utf-8 -*- from lib.fuzzy_word_search_work import FuzzyWordSearchWork #",
"method will execute the 'fuzzy search' and print the results. \"\"\" def __init__(self,",
"FuzzyWordSearch with the path to the JSON file as the argument. Once initiated,",
"\"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is initiated with a properly formated",
"FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict data in formated string \"\"\" for",
"file as the argument. Once initiated, the 'run()' method will execute the 'fuzzy",
"Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except KeyError: pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()'",
"with the path to the JSON file as the argument. Once initiated, the",
"module performs a 'fuzzy search on on JSON file\"\"\" #!/usr/bin/env python # -*-",
"self.fuzzy_search_dict[query][\"phrases\"]: print( f\"\"\"{self.fuzzy_search_dict[query]['phrases'].index(phrase) +1} Phrase: {phrase['original phrase']} Fuzzy Search: {phrase['fuzzy match']}\"\"\" ) except",
"the JSON file as the argument. Once initiated, the 'run()' method will execute",
"If FuzzySearch is initiated with a properly formated JSON file, calling 'run()' with",
"print_results(self): \"\"\" Prints fuzzy_search_dict data in formated string \"\"\" for query in self.fuzzy_search_dict:",
"Once initiated, the 'run()' method will execute the 'fuzzy search' and print the",
"on on JSON file\"\"\" #!/usr/bin/env python # -*- coding: utf-8 -*- from lib.fuzzy_word_search_work",
"given JSON. # See test_input.json for JSON format class FuzzyWordSearch(FuzzyWordSearchWork): \"\"\" Performs a",
"JSON file as the argument. Once initiated, the 'run()' method will execute the",
"performs a 'fuzzy search on on JSON file\"\"\" #!/usr/bin/env python # -*- coding:",
"KeyError: pass def print_results_dict(self): \"\"\" Calls 'add_phrases_to_fuzzy_search_dict()' and 'print_results()'. If FuzzySearch is initiated",
"\"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict data in",
"data in formated string \"\"\" for query in self.fuzzy_search_dict: try: if self.fuzzy_search_dict[query][\"phrases\"]: print(f\"\\nQuery:",
"search on on JSON file\"\"\" #!/usr/bin/env python # -*- coding: utf-8 -*- from",
"and print the results. \"\"\" def __init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\"",
"__init__(self, json_filepath): FuzzyWordSearchWork.__init__(self, json_filepath) def print_results(self): \"\"\" Prints fuzzy_search_dict data in formated string",
"Performs a 'fuzzy word search' on given JSON. See test_input.json for JSON format."
] |
[
"in range(N): for idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans =",
"in range(N)] ans = 10**9 for idx_a in range(N): for idx_b in range(N):",
"range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans = min(ans,A+B) else: ans = min(ans,max(A,B))",
"[list(map(int,input().split())) for i in range(N)] ans = 10**9 for idx_a in range(N): for",
"for i in range(N)] ans = 10**9 for idx_a in range(N): for idx_b",
"N = int(input()) li = [list(map(int,input().split())) for i in range(N)] ans = 10**9",
"<gh_stars>1-10 N = int(input()) li = [list(map(int,input().split())) for i in range(N)] ans =",
"= int(input()) li = [list(map(int,input().split())) for i in range(N)] ans = 10**9 for",
"int(input()) li = [list(map(int,input().split())) for i in range(N)] ans = 10**9 for idx_a",
"li = [list(map(int,input().split())) for i in range(N)] ans = 10**9 for idx_a in",
"10**9 for idx_a in range(N): for idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1] if",
"for idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans = min(ans,A+B) else:",
"in range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans = min(ans,A+B) else: ans =",
"for idx_a in range(N): for idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b:",
"idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans = min(ans,A+B) else: ans",
"range(N)] ans = 10**9 for idx_a in range(N): for idx_b in range(N): A,B",
"A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans = min(ans,A+B) else: ans = min(ans,max(A,B)) print(ans)",
"ans = 10**9 for idx_a in range(N): for idx_b in range(N): A,B =",
"idx_a in range(N): for idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans",
"range(N): for idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1] if idx_a==idx_b: ans = min(ans,A+B)",
"= 10**9 for idx_a in range(N): for idx_b in range(N): A,B = li[idx_a][0],li[idx_b][1]",
"= [list(map(int,input().split())) for i in range(N)] ans = 10**9 for idx_a in range(N):",
"i in range(N)] ans = 10**9 for idx_a in range(N): for idx_b in"
] |
[
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"\"ok\", \"code\": \"1500200\", } \"\"\" task_id = 0 try: task_id = int(id) except",
"= {\"source\": [], \"dest\": []} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info",
"common.log import logger from common.transaction import auto_meta_sync from common.views import APIViewSet from datahub.common.const",
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"\"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } ) # 目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]:",
"def get_tasks(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam",
"@list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription",
"更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\" :",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights",
"{json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\",",
"args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label = migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return",
"Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\",",
"[{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\",",
"args[\"dest\"], } ) task_label = migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def",
"起始时间 @apiParam {string} end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据",
"this software and associated documentation files (the \"Software\"), to deal in the Software",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup migration @api",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise",
") @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/",
"200 OK { \"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", }",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status in",
"= int(id) except Exception: pass if task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\")",
"models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\",",
"{json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\",",
"# -*- coding: utf-8 -*- \"\"\" Tencent is pleased to support the open",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"= models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request, id): \"\"\" @apiGroup migration @api {patch}",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup",
"@apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}],",
"the Software without restriction, including without limitation the rights to use, copy, modify,",
"update_task_status(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int}",
"person obtaining a copy of this software and associated documentation files (the \"Software\"),",
"task_obj[\"dest_config\"] = \"\" return Response(tasks) def retrieve(self, request, id): \"\"\" @apiGroup migration @api",
"the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"/databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample",
"-*- \"\"\" Tencent is pleased to support the open source community by making",
"migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"{\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result =",
"\"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status 状态",
"2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is",
"without restriction, including without limitation the rights to use, copy, modify, merge, publish,",
"merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit",
"args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"],",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\": []}",
"License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to",
"@apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id 任务id @apiParam",
"创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam {string} source 源存储 @apiParam {string}",
"args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self,",
"@apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"rts = [obj.processing_id for obj in objects] elif \"result_table_id\" in args: rts =",
"request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json}",
"} \"\"\" task_id = 0 try: task_id = int(id) except Exception: pass if",
"lookup_field = \"id\" def create(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/ 创建迁移任务",
"== 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\",",
"\"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args =",
"} \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"],",
"result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request):",
"return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/",
"= 0 try: task_id = int(id) except Exception: pass if task_id == 0:",
"Exception: pass if task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\",",
"self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\": []} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if",
"\"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def",
"{ \"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args",
"@apiParam {string} status 状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited,",
"= args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup migration @api {patch}",
"Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id): \"\"\" @apiGroup migration @api {post}",
"in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup migration",
"args[\"status\"] obj.input = args[\"input\"] obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update",
"200 OK { \"result\": true, \"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\",",
"in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED",
"import DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth",
"task_label = migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request, id):",
"\"result\": true, \"data\": True, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer)",
"args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup migration @api {get}",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: # query",
"\"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not",
"\"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", ) for task_obj in tasks: if",
"sublicense, and/or sell copies of the Software, and to permit persons to whom",
"this permission notice shall be included in all copies or substantial portions of",
"rts = [args[\"result_table_id\"]] else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\",",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to",
"output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {{}},",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"if not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]: raise",
"\"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) else:",
"IN THE SOFTWARE. \"\"\" import time from common.decorators import detail_route, list_route from common.log",
"Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表",
"WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"{string} start 起始时间 @apiParam {string} end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean}",
"import check_task_auth from django.forms import model_to_dict from rest_framework.response import Response from datahub.databus import",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"True, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id)",
"{get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"@apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": True,",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A",
"Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the",
"models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", )",
"status 状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response:",
"} \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError()",
"elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\"",
"self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: # query by raw_data_id raw_data_id = args[\"raw_data_id\"] objects",
"notice and this permission notice shall be included in all copies or substantial",
"状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"OTHER DEALINGS IN THE SOFTWARE. \"\"\" import time from common.decorators import detail_route, list_route",
"status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self,",
"args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def",
"Response(objs) def partial_update(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup migration @api {get}",
"@api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status 状态 @apiParam {int} parallelism",
"# 源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\":",
"migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json}",
"\"created_at\", \"created_by\", \"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\"",
"@apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"\"dest\": []} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not rt_info.get(\"storages\"):",
"charge, to any person obtaining a copy of this software and associated documentation",
"Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]},",
"MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of",
"OK { \"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\"",
"\"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) else: obj",
"更新迁移任务 @apiParam {string} status 状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"@apiParam {string} result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"{int} input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if",
"{json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": True, \"message\": \"ok\", \"code\":",
"self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj,",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [],",
"\"\"\" Tencent is pleased to support the open source community by making BK-BASE",
"MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为",
"\"\" task_obj[\"dest_config\"] = \"\" return Response(tasks) def retrieve(self, request, id): \"\"\" @apiGroup migration",
"\"created_by\", \"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup",
"models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input = args[\"input\"]",
"{ \"result\": true, \"data\": {}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args =",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except",
"= models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input =",
"if args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request):",
"with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input = args[\"input\"] obj.output = args[\"output\"] obj.updated_at =",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person",
"@apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {{}}, \"message\": \"ok\",",
"rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={",
"{json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\":",
"args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } )",
"exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"],",
"Response(result) storages = rt_info.get(\"storages\") for storage_type in storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type)",
"获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response:",
"persons to whom the Software is furnished to do so, subject to the",
"obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup",
"@apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": True,",
"logger from common.transaction import auto_meta_sync from common.views import APIViewSet from datahub.common.const import DEFAULT",
"Software is furnished to do so, subject to the following conditions: The above",
"args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not rt_info:",
") task_label = migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request,",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"\"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id):",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info =",
"licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby",
"{patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}], \"message\":",
"[选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"get_tasks(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string}",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"0: obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup migration",
"\"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) )",
"@apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam",
"if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\" return Response(tasks) def",
"parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json}",
"停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"obj.input = args[\"input\"] obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{}",
"MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth from django.forms import model_to_dict from rest_framework.response",
"django.forms import model_to_dict from rest_framework.response import Response from datahub.databus import exceptions, migration, models,",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args:",
"\"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\",",
"true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\",",
"to deal in the Software without restriction, including without limitation the rights to",
"migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"@apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/",
"\"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", )",
"= args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def",
"import Response from datahub.databus import exceptions, migration, models, rt, serializers, settings class MigrationViewset(APIViewSet):",
"\"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id): \"\"\" @apiGroup migration @api",
"to whom the Software is furnished to do so, subject to the following",
"@apiParam {string} start 起始时间 @apiParam {string} end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam",
"import exceptions, migration, models, rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在",
"documentation files (the \"Software\"), to deal in the Software without restriction, including without",
"\"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\")",
"else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\",",
"{boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"@apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status 状态 @apiParam",
"serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def create(self, request): \"\"\"",
"@api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"目标存储 @apiParam {string} start 起始时间 @apiParam {string} end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3",
"files (the \"Software\"), to deal in the Software without restriction, including without limitation",
"/databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status 状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample",
"Software without restriction, including without limitation the rights to use, copy, modify, merge,",
"if args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], }",
"获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample",
"storage_type in storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type)",
"to do so, subject to the following conditions: The above copyright notice and",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\",",
"{string} raw_data_id 数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"OK { \"result\": true, \"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\":",
"def partial_update(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status",
"\"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\"",
"Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态",
"company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License",
"in the Software without restriction, including without limitation the rights to use, copy,",
"raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } ) # 目的存储配置检查 if args[\"dest\"]",
"\"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\",",
"\"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: # query by raw_data_id raw_data_id",
"source 源存储 @apiParam {string} dest 目标存储 @apiParam {string} start 起始时间 @apiParam {string} end",
"id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response:",
"更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id 任务id @apiParam {string} status 状态 @apiParam {int}",
"the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"to any person obtaining a copy of this software and associated documentation files",
"raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id): \"\"\"",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\" return Response(tasks) def retrieve(self, request, id): \"\"\"",
"id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status",
"\"1500200\", } \"\"\" task_id = 0 try: task_id = int(id) except Exception: pass",
"self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status = args[\"status\"]",
"查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":{}, \"sink\":{}},",
"raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\":",
"{post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not rt_info.get(\"storages\"): return Response(result) storages",
"查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"query by raw_data_id raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for",
"Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id): \"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/",
"\"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id): \"\"\"",
"\"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink",
"Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台",
"url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态",
"@apiParam {string} raw_data_id 数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"200 OK { \"result\": true, \"data\": True, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\"",
"@api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"a copy of this software and associated documentation files (the \"Software\"), to deal",
"\"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\")",
"Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input = args[\"input\"] obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d",
"self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {}, \"message\":",
"def start_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务",
"from datahub.databus import exceptions, migration, models, rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源",
"raw_data_id 数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"except Exception: pass if task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values(",
"\"data\": {}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj =",
"task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self,",
"migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam {string}",
"200 OK { \"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\"",
"rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE",
"args[\"result_table_id\"], \"storage\": args[\"source\"], } ) # 目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]: raise",
"@api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam {string} type",
"\"storage\": args[\"dest\"], } ) task_label = migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs)",
"Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if",
"migration, models, rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口",
"THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed",
"free of charge, to any person obtaining a copy of this software and",
"and this permission notice shall be included in all copies or substantial portions",
"对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field",
"and to permit persons to whom the Software is furnished to do so,",
"\"code\": \"1500200\", } \"\"\" task_id = 0 try: task_id = int(id) except Exception:",
"{int} task_id 任务id @apiParam {string} status 状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int}",
"obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup migration @api {get}",
"datahub.databus.task.task_utils import check_task_auth from django.forms import model_to_dict from rest_framework.response import Response from datahub.databus",
"Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": True, \"message\": \"ok\", \"code\": \"1500200\",",
"\"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" return Response( { \"source\": settings.migration_source_supported,",
"support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021",
"\"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"[obj.processing_id for obj in objects] elif \"result_table_id\" in args: rts = [args[\"result_table_id\"]] else:",
"args[\"input\"] obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{}",
"return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/",
"raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label = migration.create_task(rt_info, args)",
"args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\"",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: # query by",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表",
"return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id): \"\"\" @apiGroup migration @api",
"{string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError()",
"\"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return",
"MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth from django.forms import model_to_dict from rest_framework.response import",
"pk lookup_field = \"id\" def create(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/",
"reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台:",
"APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def",
"{string} end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json}",
"import detail_route, list_route from common.log import logger from common.transaction import auto_meta_sync from common.views",
"def retrieve(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务",
") else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\",",
"exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label = migration.create_task(rt_info, args) objs",
"not rt_info or not rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\") for storage_type in",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"return Response(tasks) def retrieve(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务",
"= args[\"input\"] obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{}",
"[\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id):",
"\"start\", \"end\", \"status\", ) for task_obj in tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"]",
"type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":{},",
"result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"for storage_type in storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported:",
"蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission",
"with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status = args[\"status\"] if args[\"parallelism\"] > 0:",
"\"updated_at\", \"status\", ) ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\",",
"= self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\": []} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"])",
"associated documentation files (the \"Software\"), to deal in the Software without restriction, including",
"request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json}",
"detail_route, list_route from common.log import logger from common.transaction import auto_meta_sync from common.views import",
"\"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response(",
"# query by raw_data_id raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id",
"true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" task_id = 0 try:",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"} ) # 目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\":",
"\"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\":",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,",
"{int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id",
"} ) task_label = migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self,",
"for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any",
"url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态",
"input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"notice shall be included in all copies or substantial portions of the Software.",
"in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label =",
"is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is",
"@detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务",
"\"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result)",
"result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"\"\"\" @apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\")",
"id): \"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type",
"{int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge,",
"models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"copy of this software and associated documentation files (the \"Software\"), to deal in",
"models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj in objects] elif \"result_table_id\" in args: rts",
"substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup migration @api {patch} /databus/migrations/",
"{get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam {string} result_table_id result_table_id,",
"@apiParam {string} source 源存储 @apiParam {string} dest 目标存储 @apiParam {string} start 起始时间 @apiParam",
"rt_info = rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id):",
"获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1",
"@apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"\"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"@apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam {string} source 源存储 @apiParam {string} dest",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result =",
"obtaining a copy of this software and associated documentation files (the \"Software\"), to",
"pass if task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\",",
"\"ok\", \"code\": \"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\",",
"@api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam {string} source",
"= args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj in objects] elif",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"\"\"\" task_id = 0 try: task_id = int(id) except Exception: pass if task_id",
"@apiParam {string} status 状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample",
"auto_meta_sync from common.views import APIViewSet from datahub.common.const import DEFAULT from datahub.databus.exceptions import (",
"} \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] !=",
"HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\":",
"available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.",
"\"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id 任务id",
"@apiDescription 更新迁移任务 @apiParam {string} status 状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response:",
"rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label = migration.create_task(rt_info,",
"args: rts = [args[\"result_table_id\"]] else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\",",
"the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free",
"@apiParam {string} result_table_id result_table_id @apiParam {string} source 源存储 @apiParam {string} dest 目标存储 @apiParam",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"= self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: # query by raw_data_id raw_data_id = args[\"raw_data_id\"]",
"args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: # query by raw_data_id raw_data_id =",
".order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\",",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"} \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\": []} # 查询已配置存储集群列表",
"\"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values(",
"return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\",",
"obj in objects] elif \"result_table_id\" in args: rts = [args[\"result_table_id\"]] else: return Response([])",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"from common.decorators import detail_route, list_route from common.log import logger from common.transaction import auto_meta_sync",
"url_path=\"start\") def start_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription",
"@apiGroup migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam",
"args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj in objects] elif \"result_table_id\"",
"\"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) return Response(result)",
"publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons",
"是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}], \"message\":",
"@api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id 任务id @apiParam {string} status",
"including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"]",
"源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"],",
"\"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj",
"datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth from django.forms import",
"rt_info.get(\"storages\") for storage_type in storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in",
"from datahub.common.const import DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils",
"MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input = args[\"input\"] obj.output = args[\"output\"] obj.updated_at",
"or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C)",
"@apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\"",
"{patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status 状态 @apiParam {int} parallelism 处理并发数",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import time",
"settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" return Response( { \"source\": settings.migration_source_supported, \"dest\": settings.migration_dest_supported,",
"args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id): \"\"\" @apiGroup migration @api",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import",
"= self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status =",
"args[\"status\"] != \"\": obj.status = args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"]",
"@apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\":",
"exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } ) # 目的存储配置检查 if args[\"dest\"] not",
"else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\",",
"all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"@apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under",
"/databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"OK { \"result\": true, \"data\": True, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args",
"\"\": obj.status = args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"] obj.save() return",
"migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\"",
"{\"source\": [], \"dest\": []} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or",
"Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\",",
"{ \"result\": true, \"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\",",
"obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\",",
"\"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args =",
"\"source\", \"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"],",
"input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request):",
"in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request,",
"\"status\", ) ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\",",
"@api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response:",
"try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"]",
"dest 目标存储 @apiParam {string} start 起始时间 @apiParam {string} end 结束时间 @apiParam {int} parallelism",
"true, \"data\": True, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj",
"task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\",",
"task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\" return Response(tasks) def retrieve(self,",
"OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"\"storage\": args[\"source\"], } ) # 目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound(",
"-------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a",
"coding: utf-8 -*- \"\"\" Tencent is pleased to support the open source community",
"= migration.get_task(id) if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"],",
"\"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer)",
"@apiParam {string} dest 目标存储 @apiParam {string} start 起始时间 @apiParam {string} end 结束时间 @apiParam",
"= migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup migration",
": [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" return Response( {",
"storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result)",
"@apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\" : [\"tspider\"],",
"Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\",",
"当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {{}}, \"message\":",
"in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def",
"启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": True, \"message\":",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"common.views import APIViewSet from datahub.common.const import DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError,",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import time from common.decorators",
"result_table_id @apiParam {string} source 源存储 @apiParam {string} dest 目标存储 @apiParam {string} start 起始时间",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id)",
"list(self, request): \"\"\" @apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json}",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status in [\"finish\"]:",
"migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam {string}",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"!= \"\": obj.status = args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"] obj.save()",
"\"ok\", \"code\": \"1500200\", } \"\"\" return Response( { \"source\": settings.migration_source_supported, \"dest\": settings.migration_dest_supported, }",
"\"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", ) for task_obj in tasks: if task_obj[\"task_type\"]",
"list_route from common.log import logger from common.transaction import auto_meta_sync from common.views import APIViewSet",
"DEALINGS IN THE SOFTWARE. \"\"\" import time from common.decorators import detail_route, list_route from",
"Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License.",
"\"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id =",
"Response(tasks) def retrieve(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"{int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29",
"{patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with",
"@apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"@apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}],",
"args: # query by raw_data_id raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts =",
"OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id,",
"import ( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth from django.forms import model_to_dict",
"task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def",
"# 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def create(self, request): \"\"\" @apiGroup migration @api",
") ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id): \"\"\" @apiGroup migration @api {post}",
"\"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self,",
"above copyright notice and this permission notice shall be included in all copies",
"get_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string}",
"models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status = args[\"status\"] if args[\"parallelism\"] >",
") return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup migration @api {post}",
"raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input = args[\"input\"] obj.output = args[\"output\"]",
"OK { \"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\"",
"WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"in args: rts = [args[\"result_table_id\"]] else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\",",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True)",
"{json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\":",
"check_task_auth from django.forms import model_to_dict from rest_framework.response import Response from datahub.databus import exceptions,",
"@apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"permission notice shall be included in all copies or substantial portions of the",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"@api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\" return Response(tasks)",
"from common.log import logger from common.transaction import auto_meta_sync from common.views import APIViewSet from",
"[], \"dest\": []} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"\"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"@detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id): \"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态",
"the following conditions: The above copyright notice and this permission notice shall be",
"\"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\")",
"OK { \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" task_id",
"= models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\",",
"\"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result",
"datahub.databus import exceptions, migration, models, rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST",
"\"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id): \"\"\" @apiGroup migration",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"\"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id): \"\"\" @apiGroup",
"retrieve(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample",
"if \"raw_data_id\" in args: # query by raw_data_id raw_data_id = args[\"raw_data_id\"] objects =",
"furnished to do so, subject to the following conditions: The above copyright notice",
"create(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string}",
"OK { \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" tasks",
"task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\",",
"rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError() #",
"return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription",
"import time from common.decorators import detail_route, list_route from common.log import logger from common.transaction",
"return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id): \"\"\" @apiGroup migration @api {get}",
"raw_data_id raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj in",
"{string} status 状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json}",
"permit persons to whom the Software is furnished to do so, subject to",
"/databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"\"overwrite\", \"start\", \"end\", \"status\", ) for task_obj in tasks: if task_obj[\"task_type\"] != \"overall\":",
"any person obtaining a copy of this software and associated documentation files (the",
"import auto_meta_sync from common.views import APIViewSet from datahub.common.const import DEFAULT from datahub.databus.exceptions import",
"@apiParam {string} end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample",
"\"id\" def create(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务",
"\"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id)",
"= models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status = args[\"status\"] if args[\"parallelism\"]",
"copies of the Software, and to permit persons to whom the Software is",
"in args: # query by raw_data_id raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts",
"args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request, id): \"\"\" @apiGroup migration",
"{string} status 状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"(C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台",
"\"data\": True, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj =",
"return Response(objs) def partial_update(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务",
"= serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def create(self, request): \"\"\" @apiGroup",
"[]} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not rt_info.get(\"storages\"): return",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {{}},",
"obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output))",
"查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"= migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id): \"\"\"",
"= models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\",",
"{json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\" : [\"tspider\"], \"dest\":",
"中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def create(self,",
"included in all copies or substantial portions of the Software. THE SOFTWARE IS",
"@api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"= self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return",
"[args[\"result_table_id\"]] else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\",",
"if args[\"status\"] != \"\": obj.status = args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism =",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and",
"HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\",",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"@apiDescription 更新任务状态 @apiParam {int} task_id 任务id @apiParam {string} status 状态 @apiParam {int} input",
"partial_update(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam",
"in tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\" return",
"the Software, and to permit persons to whom the Software is furnished to",
") # 目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"],",
"= migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request):",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup",
"making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company.",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"\"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\":",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import time from",
"following conditions: The above copyright notice and this permission notice shall be included",
"serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class =",
"from common.views import APIViewSet from datahub.common.const import DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError,",
"\"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with",
"logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\")",
"true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer)",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" task_id = 0 try: task_id = int(id)",
"\"created_by\", \"updated_at\", \"status\", ) ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\",",
"copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",",
"true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer)",
"= [args[\"result_table_id\"]] else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\",",
"\"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) return",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"model_to_dict from rest_framework.response import Response from datahub.databus import exceptions, migration, models, rt, serializers,",
"\"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", ) for task_obj in tasks:",
"OK { \"result\": true, \"data\": {}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args",
"rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\") for",
"= self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status",
"if task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\",",
"\"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" return",
"HTTP/1.1 200 OK { \"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", }",
"try: task_id = int(id) except Exception: pass if task_id == 0: return Response(",
"The above copyright notice and this permission notice shall be included in all",
"rest_framework.response import Response from datahub.databus import exceptions, migration, models, rt, serializers, settings class",
"{post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id 任务id @apiParam {string} status 状态",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"])",
"self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request,",
"result_table_id result_table_id @apiParam {string} source 源存储 @apiParam {string} dest 目标存储 @apiParam {string} start",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"]",
"Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {}, \"message\": \"ok\", \"code\": \"1500200\",",
"200 OK { \"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", }",
"url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表",
"Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\":",
"\"Software\"), to deal in the Software without restriction, including without limitation the rights",
"@apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response:",
"deal in the Software without restriction, including without limitation the rights to use,",
"{string} result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]:",
"granted, free of charge, to any person obtaining a copy of this software",
"limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"# 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not rt_info.get(\"storages\"): return Response(result)",
"for obj in objects] elif \"result_table_id\" in args: rts = [args[\"result_table_id\"]] else: return",
"args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/",
"rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: #",
"id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response:",
"= args[\"status\"] obj.input = args[\"input\"] obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())",
"\"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer)",
"return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return",
"{json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {}, \"message\": \"ok\", \"code\":",
"/databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"= args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status,",
"class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer #",
"of this software and associated documentation files (the \"Software\"), to deal in the",
"DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth from",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"request, id): \"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string}",
"if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"],",
"/databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id 任务id @apiParam {string} status 状态 @apiParam",
"true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try:",
"return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\",",
"sell copies of the Software, and to permit persons to whom the Software",
"\"\"\" import time from common.decorators import detail_route, list_route from common.log import logger from",
"\"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def create(self, request):",
"elif \"result_table_id\" in args: rts = [args[\"result_table_id\"]] else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts,",
"status 状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input,",
"\"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", ) for task_obj",
"\"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values(",
"OK { \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args",
"overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}],",
"@apiParam {int} parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam {string}",
"request): \"\"\" @apiGroup migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id",
"def list(self, request): \"\"\" @apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample",
"do so, subject to the following conditions: The above copyright notice and this",
"【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright",
"\"end\", \"status\", ) for task_obj in tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] =",
"obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup migration @api",
"return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\",",
"migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"from rest_framework.response import Response from datahub.databus import exceptions, migration, models, rt, serializers, settings",
"if args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], }",
"int(id) except Exception: pass if task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\")",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return",
"def get_support_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample",
"url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表",
"not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } ) #",
"查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}], \"message\":",
"@apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {}, \"message\": \"ok\",",
"( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth from django.forms import model_to_dict from",
"is furnished to do so, subject to the following conditions: The above copyright",
"HTTP/1.1 200 OK { \"result\": true, \"data\": {}, \"message\": \"ok\", \"code\": \"1500200\", }",
"\"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk",
"MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id): \"\"\" @apiGroup",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\":",
"@list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist:",
"objects] elif \"result_table_id\" in args: rts = [args[\"result_table_id\"]] else: return Response([]) result =",
"\"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" task_id = 0 try: task_id",
"= models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj in objects] elif \"result_table_id\" in args:",
"\"\"\" @apiGroup migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id",
"so, subject to the following conditions: The above copyright notice and this permission",
"@apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"@apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info",
"obj.status = args[\"status\"] obj.input = args[\"input\"] obj.output = args[\"output\"] obj.updated_at = time.strftime(\"%Y-%m-%d %H:%M:%S\",",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"])",
"models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\",",
"datahub.common.const import DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import",
"migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request, id): \"\"\" @apiGroup",
"args[\"source\"], } ) # 目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={",
"stop_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample",
"\"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self,",
"@detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务",
"@list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription",
"\"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\": []} # 查询已配置存储集群列表 rt_info",
"查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound(",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, ) from datahub.databus.task.task_utils import check_task_auth from django.forms",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\": []} # 查询已配置存储集群列表 rt_info =",
"/databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam {string} source 源存储 @apiParam",
"of the Software, and to permit persons to whom the Software is furnished",
"@apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"HTTP/1.1 200 OK { \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", }",
"and/or sell copies of the Software, and to permit persons to whom the",
"\"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result = migration.get_task_status(task_obj,",
"@apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json}",
"from datahub.databus.task.task_utils import check_task_auth from django.forms import model_to_dict from rest_framework.response import Response from",
"migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id): \"\"\" @apiGroup",
"{ \"result\": true, \"data\": True, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args =",
"def stop_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务",
"def get_status(self, request, id): \"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态",
"true, \"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\"",
"result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"of charge, to any person obtaining a copy of this software and associated",
"(the \"Software\"), to deal in the Software without restriction, including without limitation the",
"HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\",",
"{ \"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args =",
"obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status = args[\"status\"] if",
"@apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":{}, \"sink\":{}}, \"message\":",
"\"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def start_task(self, request,",
"更新任务状态 @apiParam {int} task_id 任务id @apiParam {string} status 状态 @apiParam {int} input [选填]source任务处理数量,默认0",
"任务id @apiParam {string} status 状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0",
"copyright notice and this permission notice shall be included in all copies or",
"查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":[], \"sink\":[]},",
"task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", )",
"get_support_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json}",
"= \"\" return Response(tasks) def retrieve(self, request, id): \"\"\" @apiGroup migration @api {patch}",
"} \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if",
"@apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"to permit persons to whom the Software is furnished to do so, subject",
"APIViewSet from datahub.common.const import DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, ) from",
"停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": True, \"message\":",
"查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\":",
"storages = rt_info.get(\"storages\") for storage_type in storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif",
"Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务",
"task_obj = migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self,",
"conditions: The above copyright notice and this permission notice shall be included in",
"源存储 @apiParam {string} dest 目标存储 @apiParam {string} start 起始时间 @apiParam {string} end 结束时间",
"\"raw_data_id\" in args: # query by raw_data_id raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id)",
"@list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription",
"= \"\" task_obj[\"dest_config\"] = \"\" return Response(tasks) def retrieve(self, request, id): \"\"\" @apiGroup",
"or not rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\") for storage_type in storages.keys(): if",
"objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj in objects] elif \"result_table_id\" in",
"serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def create(self, request): \"\"\" @apiGroup migration",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\"",
"import model_to_dict from rest_framework.response import Response from datahub.databus import exceptions, migration, models, rt,",
"200 OK { \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\"",
"args[\"source\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } )",
"对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\" def create(self, request): \"\"\" @apiGroup migration @api {post}",
"obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"], url_path=\"get_support_clusters\") def get_support_clusters(self, request): \"\"\" @apiGroup migration",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id)",
"{{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj =",
"\"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", ) for task_obj in tasks: if task_obj[\"task_type\"] !=",
"\"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" task_id = 0",
"\"result_table_id\" in args: rts = [args[\"result_table_id\"]] else: return Response([]) result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values(",
"%H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\")",
"be included in all copies or substantial portions of the Software. THE SOFTWARE",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def stop_task(self, request, id): \"\"\" @apiGroup migration",
"蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining",
"REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field =",
"@apiParam {int} task_id 任务id @apiParam {string} status 状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam",
"\"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj",
"whom the Software is furnished to do so, subject to the following conditions:",
"not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if",
"task_id = int(id) except Exception: pass if task_id == 0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id,",
"[{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" task_id = 0 try: task_id =",
"@api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam {string} result_table_id",
"url_path=\"stop\") def stop_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription",
"创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam {string} source 源存储 @apiParam {string} dest 目标存储",
"utf-8 -*- \"\"\" Tencent is pleased to support the open source community by",
"by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent",
"= self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not rt_info: raise",
"true, \"data\": {}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj",
"exceptions, migration, models, rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet",
"type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {\"source\":[],",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"",
"/databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"= rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if args[\"source\"] not in",
"@apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam",
"{string} result_table_id result_table_id @apiParam {string} source 源存储 @apiParam {string} dest 目标存储 @apiParam {string}",
"\"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT):",
"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"} \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return",
"task_id = 0 try: task_id = int(id) except Exception: pass if task_id ==",
"migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status 状态 @apiParam {int}",
"obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务",
"\"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\":",
"obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input",
"{post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam {string} result_table_id result_table_id @apiParam {string} source 源存储",
"= migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request, id): \"\"\"",
"from django.forms import model_to_dict from rest_framework.response import Response from datahub.databus import exceptions, migration,",
"{get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1",
"common.decorators import detail_route, list_route from common.log import logger from common.transaction import auto_meta_sync from",
"Response from datahub.databus import exceptions, migration, models, rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\"",
"request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json}",
"end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response:",
"OK { \"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args",
"= time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save()",
"0 try: task_id = int(id) except Exception: pass if task_id == 0: return",
"{get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink",
"= self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self,",
"portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self,",
"community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a",
"@apiGroup migration @api {patch} /databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200",
"All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for",
"\"status\", ) for task_obj in tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\"",
"{string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"{{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in",
"\"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup migration",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"\"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label = migration.create_task(rt_info, args) objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values()",
"if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\") def",
"true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id",
"request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response:",
"distribute, sublicense, and/or sell copies of the Software, and to permit persons to",
"of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"\"code\": \"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\",",
"software and associated documentation files (the \"Software\"), to deal in the Software without",
"the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL",
"{ \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" task_id =",
"[{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateCreateSerializer) rt_id = args[\"result_table_id\"]",
"get_status(self, request, id): \"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam",
"\"\"\" @apiGroup migration @api {get} /databus/migrations/get_support_clusters/ 获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"200 OK { \"result\": true, \"data\": {}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\"",
"task_obj = migration.get_task(id) if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"]))",
"\"code\": \"1500200\", } \"\"\" return Response( { \"source\": settings.migration_source_supported, \"dest\": settings.migration_dest_supported, } )",
"task_id 任务id @apiParam {string} status 状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int} output",
"-*- coding: utf-8 -*- \"\"\" Tencent is pleased to support the open source",
"/databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效",
"shall be included in all copies or substantial portions of the Software. THE",
"} \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\",",
"\"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) @detail_route(methods=[\"get\"], url_path=\"start\") def",
"} \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status in [\"finish\"]: raise",
"migration.stop_task(task_obj, args[\"type\"]) return Response(True) @detail_route(methods=[\"get\"], url_path=\"status\") def get_status(self, request, id): \"\"\" @apiGroup migration",
"not rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\") for storage_type in storages.keys(): if storage_type",
"= rt_info.get(\"storages\") for storage_type in storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type",
"in objects] elif \"result_table_id\" in args: rts = [args[\"result_table_id\"]] else: return Response([]) result",
"is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.",
"操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\" serializer_class = serializers.MigrateCreateSerializer # 对于URL中实例ID变量名进行重命名,默认为 pk lookup_field = \"id\"",
"auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status = args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism",
"{ \"result\": true, \"data\": {\"source\":[], \"sink\":[]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args",
"raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj in objects]",
"request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id",
"url_path=\"status\") def get_status(self, request, id): \"\"\" @apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"{string} source 源存储 @apiParam {string} dest 目标存储 @apiParam {string} start 起始时间 @apiParam {string}",
"\"result\": true, \"data\": {\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", }",
"\"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request):",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"task_obj in tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\"",
"under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted,",
"start 起始时间 @apiParam {string} end 结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite",
"objs = models.DatabusMigrateTask.objects.filter(task_label=task_label).values() return Response(objs) def partial_update(self, request, id): \"\"\" @apiGroup migration @api",
"@apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}], \"message\": \"ok\",",
"@apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": True, \"message\": \"ok\",",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"\"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) migration.stop_task(task_obj,",
"models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\",",
"USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import time from common.decorators import",
"result = models.DatabusMigrateTask.objects.filter(result_table_id__in=rts, task_type=\"overall\").values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\",",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT",
"obj.status = args[\"status\"] if args[\"parallelism\"] > 0: obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id)))",
"migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id 任务id @apiParam {string}",
"} \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer) if \"raw_data_id\" in args: # query by raw_data_id",
"更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string} status 状态 @apiParam {int} parallelism 处理并发数 @apiSuccessExample {json}",
"/databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"the Software is furnished to do so, subject to the following conditions: The",
"[选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {{}}, \"message\":",
"migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK",
"Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\") def get_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表",
"BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING",
"\"1500200\", } \"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\",",
"args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id) with auto_meta_sync(using=DEFAULT): if args[\"status\"] != \"\": obj.status",
"\"\"\" tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\",",
"for task_obj in tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] =",
"Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\",",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
") from datahub.databus.task.task_utils import check_task_auth from django.forms import model_to_dict from rest_framework.response import Response",
"{ \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args =",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
") ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\",",
"parallelism 处理并发数 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\": {},",
"args = self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT):",
"= rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\")",
"subject to the following conditions: The above copyright notice and this permission notice",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查 if",
"time from common.decorators import detail_route, list_route from common.log import logger from common.transaction import",
"except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input = args[\"input\"] obj.output",
"message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"], } ) task_label = migration.create_task(rt_info, args) objs =",
"models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\", \"end\",",
"结束时间 @apiParam {int} parallelism 【选填】处理并发数,默认3 @apiParam {boolean} overwrite 是否覆盖已有数据 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"if not rt_info or not rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\") for storage_type",
"models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status = args[\"status\"] obj.input = args[\"input\"] obj.output =",
") for task_obj in tasks: if task_obj[\"task_type\"] != \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"]",
"is hereby granted, free of charge, to any person obtaining a copy of",
"\"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", ) for task_obj in",
"and associated documentation files (the \"Software\"), to deal in the Software without restriction,",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"= args[\"result_table_id\"] check_task_auth(rt_id) rt_info = rt.get_databus_rt_info(rt_id) if not rt_info: raise exceptions.NotFoundRtError() # 源存储配置检查",
"message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } ) # 目的存储配置检查 if args[\"dest\"] not in",
"OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import time from common.decorators import detail_route,",
"{}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer) obj = models.DatabusMigrateTask.objects.get(id=id)",
"migration.get_task(id) if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status}) return Response(migration.start_task(task_obj, args[\"type\"])) @detail_route(methods=[\"get\"], url_path=\"stop\")",
"\"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\" return Response(tasks) def retrieve(self, request, id):",
"\"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) else: obj =",
"{\"source\":{}, \"sink\":{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj =",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"def get_clusters(self, request): \"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam",
"by raw_data_id raw_data_id = args[\"raw_data_id\"] objects = models.DatabusClean.objects.filter(raw_data_id=raw_data_id) rts = [obj.processing_id for obj",
"time.localtime()) logger.info(\"update task:{} status:{} input:{} output:{}\".format(obj.id, obj.status, obj.input, obj.output)) obj.save() return Response(\"ok\") @list_route(methods=[\"get\"],",
"in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } ) # 目的存储配置检查",
"0: return Response( models.DatabusMigrateTask.objects.filter(result_table_id=id, task_type=\"overall\") .order_by(\"task_label\") .values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\",",
"\"\"\" @apiGroup migration @api {get} /databus/migrations/get_tasks/ 获取dataid下迁移任务列表 @apiDescription 获取dataid下迁移任务列表 @apiParam {string} raw_data_id 数据id",
"rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"source\"], } ) # 目的存储配置检查 if",
"def update_task_status(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam",
"目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\": args[\"dest\"],",
".values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", )",
"request): \"\"\" @apiGroup migration @api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response:",
"= models.DatabusMigrateTask.objects.get(id=task_id) return Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\",",
"\"status\", ) return Response(result) @list_route(methods=[\"post\"], url_path=\"update_task_status\") def update_task_status(self, request): \"\"\" @apiGroup migration @api",
"状态 @apiParam {int} input [选填]source任务处理数量,默认0 @apiParam {int} output [选填]sink任务处理数量,默认0 @apiSuccessExample {json} Success-Response: HTTP/1.1",
"{\"source\" : [\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" return Response(",
"hereby granted, free of charge, to any person obtaining a copy of this",
"obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup migration @api",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"])",
"from common.transaction import auto_meta_sync from common.views import APIViewSet from datahub.common.const import DEFAULT from",
"= self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) result = migration.get_task_status(task_obj, args[\"type\"]) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_clusters\")",
"\"\"\" @apiGroup migration @api {get} /databus/migrations/get_clusters/ 获取result_table_id支持迁移集群列表 @apiDescription 获取result_table_id支持迁移集群列表 @apiParam {string} result_table_id result_table_id",
"HTTP/1.1 200 OK { \"result\": true, \"data\": True, \"message\": \"ok\", \"code\": \"1500200\", }",
"= [obj.processing_id for obj in objects] elif \"result_table_id\" in args: rts = [args[\"result_table_id\"]]",
"\"result\": true, \"data\": {}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrateUpdateSerializer)",
"id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/stop/ 停止任务 @apiDescription 停止任务 @apiSuccessExample {json} Success-Response:",
"\"result\": true, \"data\": {{}}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.MigrationGetTasksVerifySerializer)",
"[\"tspider\"], \"dest\": [\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" return Response( { \"source\":",
"\"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) )",
"start_task(self, request, id): \"\"\" @apiGroup migration @api {post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample",
"result = {\"source\": [], \"dest\": []} # 查询已配置存储集群列表 rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not",
"\"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\", \"status\", ) for",
"@apiGroup migration @api {get} /databus/migrations/:task_id/status/ 查询任务pulsar运行状态 @apiDescription 查询任务pulsar运行状态 @apiParam {string} type 查询的任务类型,选值:all—所有类型任务,默认;source;sink @apiSuccessExample",
"request): \"\"\" @apiGroup migration @api {post} /databus/migrations/update_task_status/ 更新任务状态 @apiDescription 更新任务状态 @apiParam {int} task_id",
"SOFTWARE. \"\"\" import time from common.decorators import detail_route, list_route from common.log import logger",
"a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT",
"THE SOFTWARE. \"\"\" import time from common.decorators import detail_route, list_route from common.log import",
"restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,",
"rt_info or not rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\") for storage_type in storages.keys():",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR",
"settings.migration_dest_supported: result[\"dest\"].append(storage_type) return Response(result) @list_route(methods=[\"get\"], url_path=\"get_tasks\") def get_tasks(self, request): \"\"\" @apiGroup migration @api",
"{string} dest 目标存储 @apiParam {string} start 起始时间 @apiParam {string} end 结束时间 @apiParam {int}",
"to the following conditions: The above copyright notice and this permission notice shall",
"@api {patch} /databus/migrations/ 查询未完成任务 @apiDescription 查询未完成任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"in storages.keys(): if storage_type in settings.migration_source_supported: result[\"source\"].append(storage_type) elif storage_type in settings.migration_dest_supported: result[\"dest\"].append(storage_type) return",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"Software, and to permit persons to whom the Software is furnished to do",
"{ \"result\": true, \"data\": [{}], \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" tasks =",
"[\"hdfs\"]}, \"message\": \"ok\", \"code\": \"1500200\", } \"\"\" return Response( { \"source\": settings.migration_source_supported, \"dest\":",
"\"\" return Response(tasks) def retrieve(self, request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/",
"> 0: obj.parallelism = args[\"parallelism\"] obj.save() return Response(model_to_dict(models.DatabusMigrateTask.objects.get(id=id))) def list(self, request): \"\"\" @apiGroup",
"rt_info = rt.get_rt_fields_storages(args[\"result_table_id\"]) if not rt_info or not rt_info.get(\"storages\"): return Response(result) storages =",
"import logger from common.transaction import auto_meta_sync from common.views import APIViewSet from datahub.common.const import",
"request, id): \"\"\" @apiGroup migration @api {patch} /databus/migrations/:task_id/ 更新迁移任务 @apiDescription 更新迁移任务 @apiParam {string}",
"import APIViewSet from datahub.common.const import DEFAULT from datahub.databus.exceptions import ( MigrationCannotOperatError, MigrationNotFoundError, )",
"\"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) ) else: obj = models.DatabusMigrateTask.objects.get(id=task_id)",
"\"result_table_id\", \"source\", \"dest\", \"start\", \"end\", \"created_at\", \"created_by\", \"updated_at\", \"status\", ) return Response(result) @list_route(methods=[\"post\"],",
"rt_info.get(\"storages\"): return Response(result) storages = rt_info.get(\"storages\") for storage_type in storages.keys(): if storage_type in",
"/databus/migrations/:task_id/ 查询任务 @apiDescription 查询任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true,",
"\"1500200\", } \"\"\" args = self.params_valid(serializer=serializers.TasksRtIdSerializer) result = {\"source\": [], \"dest\": []} #",
"获取当前支持的迁移列表 @apiDescription 更新任务状态 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\": true, \"data\":",
"BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: --------------------------------------------------------------------",
"tasks = models.DatabusMigrateTask.objects.exclude(status__in=[\"finish\"]).values( \"id\", \"task_label\", \"task_type\", \"result_table_id\", \"parallelism\", \"dest\", \"dest_config\", \"overwrite\", \"start\", \"end\",",
"!= \"overall\": task_obj[\"source_config\"] = \"\" task_obj[\"dest_config\"] = \"\" return Response(tasks) def retrieve(self, request,",
"args = self.params_valid(serializer=serializers.MigrateTaskTypeSerializer) task_obj = migration.get_task(id) if task_obj.status in [\"finish\"]: raise MigrationCannotOperatError(message_kv={\"type\": task_obj.status})",
"Response( models.DatabusMigrateTask.objects.filter(task_label=obj.task_label).values( \"id\", \"task_type\", \"result_table_id\", \"source\", \"dest\", \"input\", \"output\", \"start\", \"end\", \"created_at\", \"created_by\",",
"{post} /databus/migrations/:task_id/start/ 启动任务 @apiDescription 启动任务 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"result\":",
"models, rt, serializers, settings class MigrationViewset(APIViewSet): \"\"\" 对于资源 REST 操作逻辑统一放置在 APIViewSet 中提供接口 \"\"\"",
"数据id @apiParam {string} result_table_id result_table_id, 当存在raw_data_id时无效 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {",
"= \"id\" def create(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription",
"# 目的存储配置检查 if args[\"dest\"] not in rt_info[\"storages.list\"]: raise exceptions.TaskStorageNotFound( message_kv={ \"result_table_id\": args[\"result_table_id\"], \"storage\":",
"def create(self, request): \"\"\" @apiGroup migration @api {post} /databus/migrations/ 创建迁移任务 @apiDescription 创建迁移任务 @apiParam",
"return Response(result) storages = rt_info.get(\"storages\") for storage_type in storages.keys(): if storage_type in settings.migration_source_supported:",
"self.params_valid(serializer=serializers.MigrateUpdateStateSerializer) try: obj = models.DatabusMigrateTask.objects.get(id=args[\"task_id\"]) except models.DatabusMigrateTask.DoesNotExist: raise MigrationNotFoundError() with auto_meta_sync(using=DEFAULT): obj.status =",
"common.transaction import auto_meta_sync from common.views import APIViewSet from datahub.common.const import DEFAULT from datahub.databus.exceptions"
] |
[
"a random contact from the list'): contact = random.choice(old_contact_list) with pytest.allure.step('When I delete",
"a new contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct list",
"address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a random contact from",
"contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list if check_ui: assert sorted(new_contact_list,",
"random import pytest def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a non-empty contact list'):",
"pytest.allure.step('When I delete a new contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the",
"pytest.allure.step('Given a non-empty contact list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address,",
"new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list if check_ui: assert sorted(new_contact_list, key=Contact.id_or_max)",
"contact list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\"))",
"check_ui): with pytest.allure.step('Given a non-empty contact list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\",",
"delete a new contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct",
"with pytest.allure.step('When I delete a new contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then",
"equal to the old list without the deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact)",
"list is equal to the old list without the deleted contact'): new_contact_list =",
"app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct list is equal to the old list",
"lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a random",
"0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given",
"contact = random.choice(old_contact_list) with pytest.allure.step('When I delete a new contact from the list'):",
"non-empty contact list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\",",
"coding: utf-8 -*- from models.contact import Contact import random import pytest def test_delete_contact(app,",
"import pytest def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a non-empty contact list'): if",
"1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a random contact from the",
"list without the deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list",
"the new contct list is equal to the old list without the deleted",
"new contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct list is",
"pytest.allure.step('Then the new contct list is equal to the old list without the",
"list'): contact = random.choice(old_contact_list) with pytest.allure.step('When I delete a new contact from the",
"random contact from the list'): contact = random.choice(old_contact_list) with pytest.allure.step('When I delete a",
"old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a random contact from the list'): contact =",
"-*- from models.contact import Contact import random import pytest def test_delete_contact(app, orm, check_ui):",
"from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct list is equal to",
"is equal to the old list without the deleted contact'): new_contact_list = orm.get_contact_list()",
"to the old list without the deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert",
"random.choice(old_contact_list) with pytest.allure.step('When I delete a new contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with",
"Contact import random import pytest def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a non-empty",
"deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list if check_ui: assert",
"orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list if check_ui: assert sorted(new_contact_list, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(),",
"test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a non-empty contact list'): if app.contact.count() == 0:",
"I delete a new contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new",
"def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a non-empty contact list'): if app.contact.count() ==",
"models.contact import Contact import random import pytest def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given",
"mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a random contact from the list'): contact",
"import random import pytest def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a non-empty contact",
"old list without the deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list ==",
"pytest def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a non-empty contact list'): if app.contact.count()",
"= orm.get_contact_list() with pytest.allure.step('Given a random contact from the list'): contact = random.choice(old_contact_list)",
"address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a random contact",
"list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct list is equal to the old",
"home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a random contact from the list'):",
"# -*- coding: utf-8 -*- from models.contact import Contact import random import pytest",
"contact from the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct list is equal",
"= random.choice(old_contact_list) with pytest.allure.step('When I delete a new contact from the list'): app.contact.delete_some_contact_by_id(contact.id)",
"with pytest.allure.step('Then the new contct list is equal to the old list without",
"app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list()",
"without the deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list if",
"with pytest.allure.step('Given a random contact from the list'): contact = random.choice(old_contact_list) with pytest.allure.step('When",
"from the list'): contact = random.choice(old_contact_list) with pytest.allure.step('When I delete a new contact",
"contct list is equal to the old list without the deleted contact'): new_contact_list",
"a non-empty contact list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\",",
"the list'): app.contact.delete_some_contact_by_id(contact.id) with pytest.allure.step('Then the new contct list is equal to the",
"the old list without the deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list",
"new contct list is equal to the old list without the deleted contact'):",
"if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list =",
"list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list",
"import Contact import random import pytest def test_delete_contact(app, orm, check_ui): with pytest.allure.step('Given a",
"the list'): contact = random.choice(old_contact_list) with pytest.allure.step('When I delete a new contact from",
"= orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list if check_ui: assert sorted(new_contact_list, key=Contact.id_or_max) ==",
"-*- coding: utf-8 -*- from models.contact import Contact import random import pytest def",
"app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with pytest.allure.step('Given a",
"pytest.allure.step('Given a random contact from the list'): contact = random.choice(old_contact_list) with pytest.allure.step('When I",
"old_contact_list.remove(contact) assert old_contact_list == new_contact_list if check_ui: assert sorted(new_contact_list, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)",
"orm.get_contact_list() with pytest.allure.step('Given a random contact from the list'): contact = random.choice(old_contact_list) with",
"with pytest.allure.step('Given a non-empty contact list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some",
"<filename>tests/test_delete_contact.py # -*- coding: utf-8 -*- from models.contact import Contact import random import",
"the deleted contact'): new_contact_list = orm.get_contact_list() old_contact_list.remove(contact) assert old_contact_list == new_contact_list if check_ui:",
"contact from the list'): contact = random.choice(old_contact_list) with pytest.allure.step('When I delete a new",
"from models.contact import Contact import random import pytest def test_delete_contact(app, orm, check_ui): with",
"orm, check_ui): with pytest.allure.step('Given a non-empty contact list'): if app.contact.count() == 0: app.contact.create(Contact(firstname=\"Test\",",
"== 0: app.contact.create(Contact(firstname=\"Test\", lastname=\"Test\", address=\"some address, 1\", home_number=\"+375293003030\", mobile_number=\"+375294004040\")) old_contact_list = orm.get_contact_list() with",
"utf-8 -*- from models.contact import Contact import random import pytest def test_delete_contact(app, orm,"
] |
[
"as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example, meaning, syntaxis,category,day)",
"askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2",
"in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in words: syn=input(\"sysntaxis",
"from tkinter import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file",
"syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word,",
"print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although its example is too large\") print(\"Added words:\"+str(len(words))+\".",
"= open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else",
"filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon)",
"connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although its example is too large\") print(\"Added",
"import sqlite3 from tkinter.filedialog import askopenfilename from tkinter import Tk Tk().withdraw() filename =",
"words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]),",
"in file: line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line)",
"(?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although its example is too",
"sqlite3 from tkinter.filedialog import askopenfilename from tkinter import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\")",
"\\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example, meaning, syntaxis,category,day) VALUES",
"time import sqlite3 from tkinter.filedialog import askopenfilename from tkinter import Tk Tk().withdraw() filename",
"for line in file: line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]])",
"line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\'",
"cursor.execute('INSERT INTO WORDS (word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word",
"str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit()",
"str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New",
"else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\")",
"day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3:",
"= askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if",
"discardedwords.append(line) for word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]),",
"else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\")",
"for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in",
"meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although its",
"word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT",
"import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r')",
"if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in",
"syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although its example",
"file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2",
"len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file:",
"cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if",
"INTO WORDS (word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0]))",
"Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[]",
"import askopenfilename from tkinter import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename)",
"open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday)",
"dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\") for i",
"WORDS (word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0])) if",
"import time import sqlite3 from tkinter.filedialog import askopenfilename from tkinter import Tk Tk().withdraw()",
"now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for",
"\"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\") for",
"<filename>BrushUp/import.py<gh_stars>0 import time import sqlite3 from tkinter.filedialog import askopenfilename from tkinter import Tk",
"len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\") for i in range(len(line)):",
"line in file: line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else:",
"len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\")",
"= sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon)",
"askopenfilename from tkinter import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor()",
"i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in words:",
"connection = sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else",
"Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time())",
"words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd)",
"\"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if",
"\"+str(word[0])) if len(word[1])>100: print(\"although its example is too large\") print(\"Added words:\"+str(len(words))+\". Discarded lines:\"+str(len(discardedwords)))",
"tkinter import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection = sqlite3.connect(filename) cursor=connection.cursor() file =",
"example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although",
"sqlite3.connect(filename) cursor=connection.cursor() file = open(\"DOCS/words.txt\",'r') words,discardedwords=[],[] now=time.localtime(time.time()) mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday)",
"for word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day)",
"\\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example, meaning,",
"t) connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although its example is too large\")",
"for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example,",
"if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as",
"from tkinter.filedialog import askopenfilename from tkinter import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection",
"str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t)",
"file: line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for",
"t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS (word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)',",
"in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO",
"mm=str(now.tm_mon) if len(str(now.tm_mon))==2 else \"0\"+str(now.tm_mon) dd=str(now.tm_mday) if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line",
"words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]), str(word[2]), str(syn),1,day) cursor.execute('INSERT INTO WORDS",
"VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100: print(\"although its example is",
"tkinter.filedialog import askopenfilename from tkinter import Tk Tk().withdraw() filename = askopenfilename(initialdir=\"./BBDD\") connection =",
"if len(str(now.tm_mday))==2 else \"0\"+str(now.tm_mday) day=\"{!s}/{!s}/{!s}\".format(str(now.tm_year),mm,dd) for line in file: line=line.split(\"*\") for i in",
"else: discardedwords.append(line) for word in words: syn=input(\"sysntaxis for \\'\"+str(word[0])+\"\\' as \\'\"+str(word[2])+\"\\':\") t=(str(word[0]), str(word[1]),",
"range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word in words: syn=input(\"sysntaxis for",
"line=line.split(\"*\") for i in range(len(line)): line[i]=line[i].strip().replace(\"\\t\",\"\").replace(\"\\n\",\"\") if len(line)==3: words.append([line[0],line[1],line[2]]) else: discardedwords.append(line) for word",
"(word, example, meaning, syntaxis,category,day) VALUES (?,?,?,?,?,?)', t) connection.commit() print(\"New word \"+str(word[0])) if len(word[1])>100:",
"word \"+str(word[0])) if len(word[1])>100: print(\"although its example is too large\") print(\"Added words:\"+str(len(words))+\". Discarded"
] |
[
"_praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine( lat1=coordenadas['lat'], lon1=coordenadas['lng'], lat2=_coordenadas['lat'], lon2=_coordenadas['lng'], ) return",
"self._pracas[marcadores.name] = { 'id': idx, 'lat': lat, 'lng': lng, } return self._pracas def",
"for idx, marcadores in enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] = {",
"'lng': lng, } return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for praca,",
"self.get_pracas() for praca, coordenadas in pracas.items(): self._distancias[praca] = {} for _praca, _coordenadas in",
"for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine( lat1=coordenadas['lat'], lon1=coordenadas['lng'], lat2=_coordenadas['lat'], lon2=_coordenadas['lng'], )",
"return self._document def get_pracas(self): self._pracas = dict() for locais in self._get_document().features(): for idx,",
"kml from .utils import haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename = filename",
"= { 'id': idx, 'lat': lat, 'lng': lng, } return self._pracas def get_matriz_adjacencias(self):",
"import kml from .utils import haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename =",
"lng, } return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for praca, coordenadas",
"self._filename = filename def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc)",
"__init__(self, filename='pracas'): self._filename = filename def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document =",
"self._distancias[praca] = {} for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine( lat1=coordenadas['lat'], lon1=coordenadas['lng'],",
"= marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx, 'lat': lat, 'lng': lng, } return",
"in enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx, 'lat':",
"for praca, coordenadas in pracas.items(): self._distancias[praca] = {} for _praca, _coordenadas in pracas.items():",
"fastkml import kml from .utils import haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename",
"for locais in self._get_document().features(): for idx, marcadores in enumerate(locais.features()): lng, lat, *args =",
"'id': idx, 'lat': lat, 'lng': lng, } return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas",
"def __init__(self, filename='pracas'): self._filename = filename def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document",
"return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for praca, coordenadas in pracas.items():",
"class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename = filename def _get_document(self): doc = open(\"pracas.kml\",",
"'lat': lat, 'lng': lng, } return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas()",
"lat, 'lng': lng, } return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for",
"filename='pracas'): self._filename = filename def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML()",
"def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return self._document def",
"enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx, 'lat': lat,",
"= kml.KML() self._document.from_string(doc) return self._document def get_pracas(self): self._pracas = dict() for locais in",
"import haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename = filename def _get_document(self): doc",
"GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename = filename def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8')",
"doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return self._document def get_pracas(self): self._pracas",
"in self._get_document().features(): for idx, marcadores in enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name]",
"self._get_document().features(): for idx, marcadores in enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] =",
"idx, 'lat': lat, 'lng': lng, } return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas =",
"praca, coordenadas in pracas.items(): self._distancias[praca] = {} for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca]",
"pracas = self.get_pracas() for praca, coordenadas in pracas.items(): self._distancias[praca] = {} for _praca,",
"= open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return self._document def get_pracas(self): self._pracas =",
"get_pracas(self): self._pracas = dict() for locais in self._get_document().features(): for idx, marcadores in enumerate(locais.features()):",
"lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx, 'lat': lat, 'lng':",
"self._document.from_string(doc) return self._document def get_pracas(self): self._pracas = dict() for locais in self._get_document().features(): for",
"self._document = kml.KML() self._document.from_string(doc) return self._document def get_pracas(self): self._pracas = dict() for locais",
"def get_pracas(self): self._pracas = dict() for locais in self._get_document().features(): for idx, marcadores in",
"dict() for locais in self._get_document().features(): for idx, marcadores in enumerate(locais.features()): lng, lat, *args",
"from fastkml import kml from .utils import haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'):",
"= self.get_pracas() for praca, coordenadas in pracas.items(): self._distancias[praca] = {} for _praca, _coordenadas",
"coordenadas in pracas.items(): self._distancias[praca] = {} for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] =",
".utils import haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename = filename def _get_document(self):",
"self._distancias=dict() pracas = self.get_pracas() for praca, coordenadas in pracas.items(): self._distancias[praca] = {} for",
"{ 'id': idx, 'lat': lat, 'lng': lng, } return self._pracas def get_matriz_adjacencias(self): self._distancias=dict()",
"self._pracas = dict() for locais in self._get_document().features(): for idx, marcadores in enumerate(locais.features()): lng,",
"= filename def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return",
"from .utils import haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename = filename def",
"kml.KML() self._document.from_string(doc) return self._document def get_pracas(self): self._pracas = dict() for locais in self._get_document().features():",
"self._document def get_pracas(self): self._pracas = dict() for locais in self._get_document().features(): for idx, marcadores",
"\"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return self._document def get_pracas(self): self._pracas = dict() for",
"= dict() for locais in self._get_document().features(): for idx, marcadores in enumerate(locais.features()): lng, lat,",
"_coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine( lat1=coordenadas['lat'], lon1=coordenadas['lng'], lat2=_coordenadas['lat'], lon2=_coordenadas['lng'], ) return self._distancias",
"filename def _get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return self._document",
"marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx, 'lat': lat, 'lng': lng, } return self._pracas",
"_get_document(self): doc = open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return self._document def get_pracas(self):",
"idx, marcadores in enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id':",
"get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for praca, coordenadas in pracas.items(): self._distancias[praca] = {}",
"haversine class GraphFromKmlDoc: def __init__(self, filename='pracas'): self._filename = filename def _get_document(self): doc =",
"lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx, 'lat': lat, 'lng': lng,",
"def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for praca, coordenadas in pracas.items(): self._distancias[praca] =",
"} return self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for praca, coordenadas in",
"locais in self._get_document().features(): for idx, marcadores in enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates",
"marcadores in enumerate(locais.features()): lng, lat, *args = marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx,",
"self._pracas def get_matriz_adjacencias(self): self._distancias=dict() pracas = self.get_pracas() for praca, coordenadas in pracas.items(): self._distancias[praca]",
"in pracas.items(): self._distancias[praca] = {} for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine(",
"= {} for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine( lat1=coordenadas['lat'], lon1=coordenadas['lng'], lat2=_coordenadas['lat'],",
"open(\"pracas.kml\", \"r\").read().encode('utf-8') self._document = kml.KML() self._document.from_string(doc) return self._document def get_pracas(self): self._pracas = dict()",
"{} for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine( lat1=coordenadas['lat'], lon1=coordenadas['lng'], lat2=_coordenadas['lat'], lon2=_coordenadas['lng'],",
"*args = marcadores.geometry._coordinates self._pracas[marcadores.name] = { 'id': idx, 'lat': lat, 'lng': lng, }",
"pracas.items(): self._distancias[praca] = {} for _praca, _coordenadas in pracas.items(): self._distancias[praca][_praca] = haversine( lat1=coordenadas['lat'],"
] |
[
"manual_crop=\"\") tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self):",
"python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model): title",
"= ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True)",
"created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save()",
"django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models",
"import unicode_literals from django.db import models from django.utils import timezone from django.utils.encoding import",
"__future__ import absolute_import from __future__ import unicode_literals from django.db import models from django.utils",
"import absolute_import from __future__ import unicode_literals from django.db import models from django.utils import",
"django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers",
"from __future__ import absolute_import from __future__ import unicode_literals from django.db import models from",
"timezone from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import TaggableManager",
"= models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title",
"from __future__ import unicode_literals from django.db import models from django.utils import timezone from",
"@python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags = TaggableManager()",
"= models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def",
"__future__ import unicode_literals from django.db import models from django.utils import timezone from django.utils.encoding",
"import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model):",
"ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255) image =",
"models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date =",
"published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return",
"utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals from django.db import",
"from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from",
"from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255) image = ImageField(blank=True,",
"taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\")",
"from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from",
"absolute_import from __future__ import unicode_literals from django.db import models from django.utils import timezone",
"pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255)",
"import TaggableManager @python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags",
"-*- from __future__ import absolute_import from __future__ import unicode_literals from django.db import models",
"= models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date",
"django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class",
"= TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date =",
"ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def",
"models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField",
"image = ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,",
"import timezone from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import",
"class Word(models.Model): title = models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date",
"Word(models.Model): title = models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date =",
"coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals from django.db",
"title = models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now)",
"tags = TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date",
"import ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255) image",
"TaggableManager @python_2_unicode_compatible class Word(models.Model): title = models.CharField(max_length=255) image = ImageField(blank=True, manual_crop=\"\") tags =",
"models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self):",
"TaggableManager() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now()",
"from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible",
"from pyuploadcare.dj.models import ImageField from taggit_autosuggest.managers import TaggableManager @python_2_unicode_compatible class Word(models.Model): title =",
"# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals",
"-*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals from",
"import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from pyuploadcare.dj.models import",
"unicode_literals from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible"
] |
[
"worst, sort): if unit == 'seconds': prefix = 'm' scale = 1e3 elif",
"== 'operations': prefix = 'K' scale = 0.001 else: raise RuntimeError(\"Unexpected measurement unit",
"def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort): if unit == 'seconds': prefix =",
"'seconds': prefix = 'm' scale = 1e3 elif unit == 'operations': prefix =",
"'operations': prefix = 'K' scale = 0.001 else: raise RuntimeError(\"Unexpected measurement unit %r\"",
"benchmarks, best, worst, sort): if unit == 'seconds': prefix = 'm' scale =",
"coding: utf-8 -*- def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort): if unit ==",
"-*- coding: utf-8 -*- def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort): if unit",
"scale = 1e3 elif unit == 'operations': prefix = 'K' scale = 0.001",
"best, worst, sort): if unit == 'seconds': prefix = 'm' scale = 1e3",
"1e3 elif unit == 'operations': prefix = 'K' scale = 0.001 else: raise",
"== 'seconds': prefix = 'm' scale = 1e3 elif unit == 'operations': prefix",
"python # -*- coding: utf-8 -*- def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort):",
"unit == 'seconds': prefix = 'm' scale = 1e3 elif unit == 'operations':",
"#!/usr/bin/env python # -*- coding: utf-8 -*- def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst,",
"'m' scale = 1e3 elif unit == 'operations': prefix = 'K' scale =",
"if unit == 'seconds': prefix = 'm' scale = 1e3 elif unit ==",
"'K' scale = 0.001 else: raise RuntimeError(\"Unexpected measurement unit %r\" % unit) return",
"sort): if unit == 'seconds': prefix = 'm' scale = 1e3 elif unit",
"prefix = 'K' scale = 0.001 else: raise RuntimeError(\"Unexpected measurement unit %r\" %",
"# -*- coding: utf-8 -*- def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort): if",
"= 0.001 else: raise RuntimeError(\"Unexpected measurement unit %r\" % unit) return prefix, scale",
"= 'm' scale = 1e3 elif unit == 'operations': prefix = 'K' scale",
"unit == 'operations': prefix = 'K' scale = 0.001 else: raise RuntimeError(\"Unexpected measurement",
"-*- def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort): if unit == 'seconds': prefix",
"= 'K' scale = 0.001 else: raise RuntimeError(\"Unexpected measurement unit %r\" % unit)",
"pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort): if unit == 'seconds': prefix = 'm'",
"= 1e3 elif unit == 'operations': prefix = 'K' scale = 0.001 else:",
"prefix = 'm' scale = 1e3 elif unit == 'operations': prefix = 'K'",
"utf-8 -*- def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort): if unit == 'seconds':",
"scale = 0.001 else: raise RuntimeError(\"Unexpected measurement unit %r\" % unit) return prefix,",
"elif unit == 'operations': prefix = 'K' scale = 0.001 else: raise RuntimeError(\"Unexpected",
"unit, benchmarks, best, worst, sort): if unit == 'seconds': prefix = 'm' scale"
] |
[
"# shape = [*, grid ** 2 + 1, width] x = x",
"model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'],",
"from collections import OrderedDict import torch import numpy as np from torch import",
"self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding =",
"NLD -> LND x = self.transformer(x) x = x.permute(1, 0, 2) # LND",
"// patch_size) ** 2 + 1, width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width,",
"torch.Tensor): return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int,",
"int, layers: int, heads: int, attn_mask: torch.Tensor = None): super().__init__() self.width = width",
"LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if",
"* torch.randn(width, output_dim)) def forward(self, x: torch.Tensor): x = self.conv1(x) # shape =",
"= self.encode_text(input_ids) # normalize features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features =",
"embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__()",
"def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class",
"x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return x def forward(self, input_ids,",
"= self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize features image_features = image_features / image_features.norm(dim=-1,",
"Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):",
"= x.permute(1, 0, 2) # LND -> NLD x = self.ln_post(x[:, 0, :])",
"], dim=1) # shape = [*, grid ** 2 + 1, width] x",
"= image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True) # cosine",
"self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding,",
"self.attn_mask is not None else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def",
"= x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1, 0, 2) #",
"((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5 fc_std = (2",
"text_features = self.encode_text(input_ids) # normalize features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features",
"= nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width,",
"keepdim=True) # cosine similarity as logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale *",
"* np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std =",
"------- text_latents : torch.Tensor Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx,",
"output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width,",
"@ self.text_projection return x def forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features =",
"self.eos_id = eos_id self.context_length = context_length vision_heads = vision_width // 64 self.visual =",
"pixel_values: torch.Tensor Processed images from RuCLIPProcessor class Returns ------- image_latents : torch.Tensor Image",
"\"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor Tokenized",
"def forward(self, x: torch.Tensor): x = self.conv1(x) # shape = [*, width, grid,",
"Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts Parameters ---------- input_ids:",
"not None else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x:",
"torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\" def forward(self,",
"torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp =",
"= context_length vision_heads = vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width,",
"'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'],",
"= nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([])",
"self.transformer = Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width,",
"= nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01)",
"nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self):",
"not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf'))",
"x = self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids",
"shape = [*, grid ** 2, width] x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0],",
"nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\" def forward(self, x: torch.Tensor):",
"* torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask:",
"** -0.5 fc_std = (2 * self.transformer.width) ** -0.5 for block in self.transformer.resblocks:",
"attn_mask) for _ in range(layers)]) def forward(self, x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module):",
"+ 1, width] x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x =",
"1, width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post = LayerNorm(width)",
"Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def",
"x = x @ self.proj return x class CLIP(nn.Module): def __init__( self, embed_dim,",
"width, grid ** 2] x = x.permute(0, 2, 1) # shape = [*,",
"x = self.ln_post(x[:, 0, :]) if self.proj is not None: x = x",
"context_length vision_heads = vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers,",
"# LND -> NLD x = self.ln_post(x[:, 0, :]) if self.proj is not",
"nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std",
"self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None return self.attn(x, x, x,",
"-0.5 fc_std = (2 * self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight,",
"self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 /",
"vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id = eos_id self.context_length",
"NLD x = self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]),",
"None else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor):",
"stride=patch_size, bias=False) scale = width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding",
"vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id =",
"super().__init__() self.eos_id = eos_id self.context_length = context_length vision_heads = vision_width // 64 self.visual",
"= [batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return",
"folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'],",
"LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters()",
"return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor Processed images",
"torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1) # shape",
"-0.5) attn_std = self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width) ** -0.5",
"])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x: torch.Tensor): self.attn_mask =",
"= nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self):",
"torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width: int,",
"[*, grid ** 2, width] x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1],",
"std=0.01) proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std",
"from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model = cls(",
"2 + 1, width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post",
"self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not",
"attn_std = self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width) ** -0.5 for",
"nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers)",
"self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values):",
"RuCLIPProcessor class Returns ------- text_latents : torch.Tensor Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype)",
"self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)",
"= x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] x",
"self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text = logits_per_image.t() return logits_per_image,",
"x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return",
"to handle fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32))",
"grid ** 2, width] x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype,",
"width] x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1, 0,",
"LayerNorm to handle fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type = x.dtype ret =",
"def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property def dtype(self):",
"self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width)",
"= x.permute(0, 2, 1) # shape = [*, grid ** 2, width] x",
"attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x = x",
"self.ln_pre(x) x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x)",
"return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head:",
"encode_text(self, input_ids): \"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor class",
"_ in range(layers)]) def forward(self, x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self,",
"forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize features image_features",
"x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def",
"layers, heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self,",
"self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _",
"heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x:",
"torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self,",
"ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): super().__init__() self.attn",
"heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 =",
"('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask =",
"grid ** 2 + 1, width] x = x + self.positional_embedding.to(x.dtype) x =",
"VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width, layers=transformer_layers,",
"vision_heads = vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads,",
"nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self,",
"= x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor):",
"def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): super().__init__()",
"x class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor",
"self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection =",
"None): super().__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask)",
"return logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\" config =",
"int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution",
"= logit_scale * image_features @ text_features.t() logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text @classmethod",
"= LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device)",
"torch.Tensor = None): super().__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width,",
"None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x =",
"from RuCLIPProcessor class Returns ------- image_latents : torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype))",
"torch.randn((input_resolution // patch_size) ** 2 + 1, width)) self.ln_pre = LayerNorm(width) self.transformer =",
"attn_mask: torch.Tensor = None): super().__init__() self.width = width self.layers = layers self.resblocks =",
"logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json')))",
"class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor =",
"** -0.5) def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property",
"else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x",
"+ self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) # NLD -> LND x =",
"from torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\" def",
"= torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property def dtype(self): return self.visual.conv1.weight.dtype def",
"super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size,",
"collections import OrderedDict import torch import numpy as np from torch import nn",
"LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale *",
"x + self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def __init__(self, width: int, layers: int,",
"= x @ self.proj return x class CLIP(nn.Module): def __init__( self, embed_dim, image_resolution,",
"input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale =",
"x @ self.proj return x class CLIP(nn.Module): def __init__( self, embed_dim, image_resolution, vision_layers,",
"4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x: torch.Tensor):",
"out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width ** -0.5 self.class_embedding = nn.Parameter(scale *",
"1) # shape = [*, grid ** 2, width] x = torch.cat([ self.class_embedding.to(x.dtype)",
"__init__( self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3,",
"range(layers)]) def forward(self, x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution: int,",
"self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor Processed images from",
"Processed images from RuCLIPProcessor class Returns ------- image_latents : torch.Tensor Image embeddings \"\"\"",
"int, width: int, layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution",
"self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()),",
"text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity as logits logit_scale = self.logit_scale.exp() logits_per_image",
"nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width",
"texts Parameters ---------- input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor class Returns ------- text_latents",
"def forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize features",
"model from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'],",
"# cosine similarity as logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features",
"+ self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads:",
"= [*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape =",
"= x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x) x =",
"orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x:",
"self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj =",
"output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size",
"x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class",
"self.ln_post(x[:, 0, :]) if self.proj is not None: x = x @ self.proj",
"os import json from collections import OrderedDict import torch import numpy as np",
"in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is",
"transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id = eos_id self.context_length = context_length vision_heads",
"------- image_latents : torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode",
"64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer =",
"self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor Tokenized texts from",
"[batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return x",
"= output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width **",
"x = self.ln_pre(x) x = x.permute(1, 0, 2) # NLD -> LND x",
"2) # NLD -> LND x = self.transformer(x) x = x.permute(1, 0, 2)",
"QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask",
"0, 2) # LND -> NLD x = self.ln_final(x).type(self.dtype) # x.shape = [batch_size,",
"torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts Parameters ----------",
"* self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight,",
"** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution //",
"QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module):",
"mask.triu_(1) return mask @property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images",
"from RuCLIPProcessor class Returns ------- text_latents : torch.Tensor Text embeddings \"\"\" x =",
"text_features.norm(dim=-1, keepdim=True) # cosine similarity as logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale",
"width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj",
"# x.shape = [batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @",
"@property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images Parameters ---------- pixel_values:",
"x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1, 0, 2)",
"def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim:",
"class Returns ------- image_latents : torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self,",
"= self.ln_pre(x) x = x.permute(1, 0, 2) # NLD -> LND x =",
"build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property def dtype(self): return",
"self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x = x +",
"+ self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def __init__(self,",
"-0.5) def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property def",
"std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width **",
"x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def",
"* torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1,",
"utf-8 -*- import os import json from collections import OrderedDict import torch import",
"= nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) self.ln_pre =",
"class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type",
"torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))",
"output_dim)) def forward(self, x: torch.Tensor): x = self.conv1(x) # shape = [*, width,",
"x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]",
"self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype,",
"x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_final(x).type(self.dtype) #",
"/ text_features.norm(dim=-1, keepdim=True) # cosine similarity as logits logit_scale = self.logit_scale.exp() logits_per_image =",
"0, 2) # NLD -> LND x = self.transformer(x) x = x.permute(1, 0,",
"forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module):",
"return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x = x",
"return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor Tokenized texts",
"* image_features @ text_features.t() logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text @classmethod def from_pretrained(cls,",
"2, width] x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x",
"torch.Tensor Tokenized texts from RuCLIPProcessor class Returns ------- text_latents : torch.Tensor Text embeddings",
"heads, attn_mask) for _ in range(layers)]) def forward(self, x: torch.Tensor): return self.resblocks(x) class",
"0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5)",
"Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width)",
"Parameters ---------- input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor class Returns ------- text_latents :",
"x def forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize",
"features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True)",
"images from RuCLIPProcessor class Returns ------- image_latents : torch.Tensor Image embeddings \"\"\" return",
"= LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale",
"__init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): super().__init__() self.width",
"int, attn_mask: torch.Tensor = None): super().__init__() self.width = width self.layers = layers self.resblocks",
"embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint =",
"self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) **",
"+ self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1, 0, 2) # NLD ->",
"self.proj is not None: x = x @ self.proj return x class CLIP(nn.Module):",
"self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width ** -0.5 self.class_embedding",
"proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std =",
"def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5) * ((2",
"self.proj return x class CLIP(nn.Module): def __init__( self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size,",
"= self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x = x + self.positional_embedding.type(self.dtype) x =",
"= LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()), ('c_proj',",
"mask.fill_(float('-inf')) mask.triu_(1) return mask @property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode",
"scale = width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale",
"-> NLD x = self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx, transformer.width] x =",
"image_features @ text_features.t() logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder):",
"nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)),",
"std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self): mask",
"None: x = x @ self.proj return x class CLIP(nn.Module): def __init__( self,",
"context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id = eos_id self.context_length =",
"d_model: int, n_head: int, attn_mask: torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head)",
"super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model,",
"= width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in",
"self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters() def",
"vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint = torch.load(os.path.join(folder, 'pytorch_model.bin'), map_location='cpu')",
"n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return x def",
"encode_image(self, pixel_values): \"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor Processed images from RuCLIPProcessor class",
"= self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width) ** -0.5 for block",
"forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self,",
"-*- coding: utf-8 -*- import os import json from collections import OrderedDict import",
"input_ids): \"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor class Returns",
"self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1) # shape =",
"dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor Processed",
"return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width: int, layers:",
"** 2 + 1, width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers, heads)",
"nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight,",
"forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x))",
"np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width",
"d_model] x = x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) # NLD",
"if self.proj is not None: x = x @ self.proj return x class",
"logit_scale * image_features @ text_features.t() logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text @classmethod def",
"kernel_size=patch_size, stride=patch_size, bias=False) scale = width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width))",
"initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5) * ((2 *",
"= nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x: torch.Tensor): x = self.conv1(x) #",
"vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, )",
"transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return x def forward(self,",
"Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x = x",
"self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def __init__(self, width:",
"return x def forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids) #",
"pixel_values): image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize features image_features = image_features",
"self.text_projection return x def forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids)",
"np from torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\"",
"for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if",
"torch import numpy as np from torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's",
"x = x + self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def __init__(self, width: int,",
"LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x: torch.Tensor): x =",
"texts from RuCLIPProcessor class Returns ------- text_latents : torch.Tensor Text embeddings \"\"\" x",
"import json from collections import OrderedDict import torch import numpy as np from",
"CLIP(nn.Module): def __init__( self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads,",
") self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding",
"d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model)) ])) self.ln_2 =",
"mask @property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images Parameters ----------",
"-> NLD x = self.ln_post(x[:, 0, :]) if self.proj is not None: x",
"= vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim,",
"self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int,",
"# LND -> NLD x = self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx, transformer.width]",
"nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)",
"2) # LND -> NLD x = self.ln_post(x[:, 0, :]) if self.proj is",
"logits_per_image.t() return logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\" config",
"def forward(self, x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size:",
"nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return",
"LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type =",
"---------- input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor class Returns ------- text_latents : torch.Tensor",
"import OrderedDict import torch import numpy as np from torch import nn class",
"def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def",
"std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def",
"n_head: int, attn_mask: torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 =",
"torch.Tensor): x = self.conv1(x) # shape = [*, width, grid, grid] x =",
"fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type)",
"// 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer",
"= Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size,",
"grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid",
"\"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x = x + self.positional_embedding.type(self.dtype)",
"heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length,",
"ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x",
"input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads,",
"is not None else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self,",
"int, attn_mask: torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model)",
"patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(),",
"** -0.5) attn_std = self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width) **",
"x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) # NLD -> LND x",
"handle fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return",
"as logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text",
"self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_post(x[:,",
"\"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor Processed images from RuCLIPProcessor class Returns -------",
"x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1, 0, 2) # NLD",
"self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1, 0, 2) # NLD -> LND",
"# normalize features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features /",
"* x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor =",
"similarity as logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t()",
"x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1) # shape = [*, grid ** 2",
"self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize features image_features = image_features / image_features.norm(dim=-1, keepdim=True)",
"0, :]) if self.proj is not None: x = x @ self.proj return",
"VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int,",
"\"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor class Returns -------",
"= LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x: torch.Tensor): x",
"int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size,",
"class Returns ------- text_latents : torch.Tensor Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) #",
": torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts Parameters",
"('c_proj', nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def",
"attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))",
"LND -> NLD x = self.ln_post(x[:, 0, :]) if self.proj is not None:",
"= None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([",
"= layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) def forward(self,",
"x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None",
"= nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width ** -0.5 self.class_embedding =",
"config = json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'],",
"x.permute(0, 2, 1) # shape = [*, grid ** 2, width] x =",
"fc_std = (2 * self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std)",
"self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model",
"int, heads: int, attn_mask: torch.Tensor = None): super().__init__() self.width = width self.layers =",
"self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5) *",
"n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu',",
"def __init__( self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers,",
"image_latents : torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts",
"@classmethod def from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model",
"coding: utf-8 -*- import os import json from collections import OrderedDict import torch",
"int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3,",
"torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return x def forward(self, input_ids, pixel_values): image_features =",
"attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else",
"0, 2) # LND -> NLD x = self.ln_post(x[:, 0, :]) if self.proj",
"= nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) def forward(self, x: torch.Tensor): return",
"self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x: torch.Tensor):",
"grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid **",
"= x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class Transformer(nn.Module):",
"= nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model *",
"input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor class Returns ------- text_latents : torch.Tensor Text",
"= logits_per_image.t() return logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\"",
"attn_mask def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not",
"heads: int, attn_mask: torch.Tensor = None): super().__init__() self.width = width self.layers = layers",
"layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) def forward(self, x:",
"as np from torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle",
"x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] x =",
"in range(layers)]) def forward(self, x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution:",
"= super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x *",
"self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)",
": torch.Tensor Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x",
"vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection",
"= x + self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def __init__(self, width: int, layers:",
"eos_id self.context_length = context_length vision_heads = vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution,",
"-0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5 fc_std",
"-> LND x = self.transformer(x) x = x.permute(1, 0, 2) # LND ->",
"image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id",
"dim=1) # shape = [*, grid ** 2 + 1, width] x =",
"self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]]",
"x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width:",
"+ 1, width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post =",
"grid ** 2] x = x.permute(0, 2, 1) # shape = [*, grid",
"int, n_head: int, attn_mask: torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1",
"[*, width, grid ** 2] x = x.permute(0, 2, 1) # shape =",
"x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_post(x[:, 0,",
"normalize features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1,",
"** 2, width] x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),",
"text_features = text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity as logits logit_scale =",
"@ self.proj return x class CLIP(nn.Module): def __init__( self, embed_dim, image_resolution, vision_layers, vision_width,",
"+ torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1) # shape = [*,",
"self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer(",
"-0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)",
"x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x) x = x.permute(1,",
"** 2] x = x.permute(0, 2, 1) # shape = [*, grid **",
"(self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width **",
"json from collections import OrderedDict import torch import numpy as np from torch",
"transformer_layers, eos_id=3, ): super().__init__() self.eos_id = eos_id self.context_length = context_length vision_heads = vision_width",
"n_ctx, d_model] x = x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) #",
"# shape = [*, grid ** 2, width] x = torch.cat([ self.class_embedding.to(x.dtype) +",
"nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width ** -0.5 self.class_embedding = nn.Parameter(scale",
"patch_size) ** 2 + 1, width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers,",
"text_features.t() logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load model",
"NLD x = self.ln_post(x[:, 0, :]) if self.proj is not None: x =",
"output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width ** -0.5",
"None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1)",
"Parameters ---------- pixel_values: torch.Tensor Processed images from RuCLIPProcessor class Returns ------- image_latents :",
"self.attn_mask = attn_mask def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask",
"* self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5 fc_std = (2 *",
"self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x: torch.Tensor): x = self.conv1(x)",
"= nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2",
"torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1) # shape = [*, grid",
"self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ):",
"device=x.device), x ], dim=1) # shape = [*, grid ** 2 + 1,",
"= eos_id self.context_length = context_length vision_heads = vision_width // 64 self.visual = VisionTransformer(",
"torch's LayerNorm to handle fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type = x.dtype ret",
"x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1)",
"shape = [*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape",
"torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None return",
"= json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'],",
"== self.eos_id)[1]] @ self.text_projection return x def forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values)",
"torch.Tensor Processed images from RuCLIPProcessor class Returns ------- image_latents : torch.Tensor Image embeddings",
"x ], dim=1) # shape = [*, grid ** 2 + 1, width]",
"-0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size)",
"if self.attn_mask is not None else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]",
"image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize features image_features = image_features /",
"torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self,",
"layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size",
"image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity",
"nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model))",
"logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\" config = json.load(open(os.path.join(folder,",
"x = x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) # NLD ->",
"bias=False) scale = width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding =",
"RuCLIPProcessor class Returns ------- image_latents : torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def",
"self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x)",
"torch.Tensor): x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x",
"json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'],",
"x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x) x",
"= self.ln_post(x[:, 0, :]) if self.proj is not None: x = x @",
"context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint = torch.load(os.path.join(folder, 'pytorch_model.bin'), map_location='cpu') model.load_state_dict(checkpoint) return",
"= vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width)",
"import os import json from collections import OrderedDict import torch import numpy as",
"x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x))",
"= self.conv1(x) # shape = [*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1],",
"transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id = eos_id self.context_length = context_length vision_heads =",
"need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x =",
"self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x = x + self.positional_embedding.type(self.dtype) x = x.permute(1,",
"x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x",
"self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width",
"nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))",
"self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) self.ln_pre",
"embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x = x +",
"x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]",
"width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution",
"embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02)",
"(2 * self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std)",
"): super().__init__() self.eos_id = eos_id self.context_length = context_length vision_heads = vision_width // 64",
"self.mlp(self.ln_2(x)) return x class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int,",
"x.shape[1], -1) # shape = [*, width, grid ** 2] x = x.permute(0,",
"nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model)) ])) self.ln_2",
"import torch import numpy as np from torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass",
"** 2 + 1, width] x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x)",
"eos_id=3, ): super().__init__() self.eos_id = eos_id self.context_length = context_length vision_heads = vision_width //",
"self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model *",
"* 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x:",
"nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None:",
"= cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], )",
"# shape = [*, width, grid ** 2] x = x.permute(0, 2, 1)",
"-*- import os import json from collections import OrderedDict import torch import numpy",
"ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x)",
"pixel_values): \"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor Processed images from RuCLIPProcessor class Returns",
"nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) self.ln_pre = LayerNorm(width)",
"* torch.randn((input_resolution // patch_size) ** 2 + 1, width)) self.ln_pre = LayerNorm(width) self.transformer",
"folder): \"\"\"Load model from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'],",
"self.context_length = context_length vision_heads = vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size,",
"logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text",
"self.conv1(x) # shape = [*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1)",
"= Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim))",
"device=x.device) if self.attn_mask is not None else None return self.attn(x, x, x, need_weights=False,",
"x class CLIP(nn.Module): def __init__( self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size,",
"self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale =",
"nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) def forward(self, x: torch.Tensor): return self.resblocks(x)",
"= self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None return self.attn(x, x,",
"width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width,",
"super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702",
"self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width) ** -0.5 for block in",
"= text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity as logits logit_scale = self.logit_scale.exp()",
"return x class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int, attn_mask:",
"block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection",
"heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size =",
"= None): super().__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads,",
"is not None: x = x @ self.proj return x class CLIP(nn.Module): def",
"self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) def forward(self, x: torch.Tensor):",
"shape = [*, grid ** 2 + 1, width] x = x +",
"class CLIP(nn.Module): def __init__( self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width,",
"# NLD -> LND x = self.transformer(x) x = x.permute(1, 0, 2) #",
"input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features = self.encode_text(input_ids) # normalize features image_features =",
"** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight,",
":]) if self.proj is not None: x = x @ self.proj return x",
"x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x = x + self.positional_embedding.type(self.dtype) x",
"dtype=x.dtype, device=x.device), x ], dim=1) # shape = [*, grid ** 2 +",
"layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding =",
"= self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids ==",
"return x class CLIP(nn.Module): def __init__( self, embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length,",
"logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load model from",
"= input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale",
"x: torch.Tensor): x = self.conv1(x) # shape = [*, width, grid, grid] x",
"attn_mask: torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp",
"width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), )",
"x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):",
"LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model",
"# [batch_size, n_ctx, d_model] x = x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0,",
"= [*, grid ** 2, width] x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1,",
"2 + 1, width] x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x",
"= width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale *",
"image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity as logits",
"x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return",
"* ((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5 fc_std =",
"x.permute(1, 0, 2) # LND -> NLD x = self.ln_post(x[:, 0, :]) if",
"class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads:",
"---------- pixel_values: torch.Tensor Processed images from RuCLIPProcessor class Returns ------- image_latents : torch.Tensor",
"vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint = torch.load(os.path.join(folder, 'pytorch_model.bin'), map_location='cpu') model.load_state_dict(checkpoint) return model",
"layers: int, heads: int, attn_mask: torch.Tensor = None): super().__init__() self.width = width self.layers",
"LND -> NLD x = self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx, transformer.width] x",
"= [*, grid ** 2 + 1, width] x = x + self.positional_embedding.to(x.dtype)",
"def encode_image(self, pixel_values): \"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor Processed images from RuCLIPProcessor",
"logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text =",
"torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor",
"= [*, width, grid ** 2] x = x.permute(0, 2, 1) # shape",
"std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection,",
"embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids): \"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor",
"__init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model,",
"image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint = torch.load(os.path.join(folder,",
"mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask @property def dtype(self): return self.visual.conv1.weight.dtype",
"cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint",
"[*, grid ** 2 + 1, width] x = x + self.positional_embedding.to(x.dtype) x",
"= self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD x =",
"= x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) # NLD -> LND",
"-1) # shape = [*, width, grid ** 2] x = x.permute(0, 2,",
"nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x: torch.Tensor): x = self.conv1(x) # shape",
"import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\" def forward(self, x:",
"def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): super().__init__() self.attn =",
"[*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*,",
"Returns ------- text_latents : torch.Tensor Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size,",
"torch.Tensor Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model] x =",
"vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint = torch.load(os.path.join(folder, 'pytorch_model.bin'), map_location='cpu') model.load_state_dict(checkpoint)",
"transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1",
"self.eos_id)[1]] @ self.text_projection return x def forward(self, input_ids, pixel_values): image_features = self.encode_image(pixel_values) text_features",
"class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x) class",
"x: torch.Tensor): return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model:",
"return mask @property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images Parameters",
"/ image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity as",
"images Parameters ---------- pixel_values: torch.Tensor Processed images from RuCLIPProcessor class Returns ------- image_latents",
"vision_layers=config['vision_layers'], vision_width=config['vision_width'], vision_patch_size=config['vision_patch_size'], context_length=config['context_length'], vocab_size=config['vocab_size'], transformer_width=config['transformer_width'], transformer_heads=config['transformer_heads'], transformer_layers=config['transformer_layers'], ) checkpoint = torch.load(os.path.join(folder, 'pytorch_model.bin'),",
"vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id = eos_id self.context_length = context_length",
"image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True) #",
"* 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model)",
"d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x: torch.Tensor): self.attn_mask",
"return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 *",
"vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, eos_id=3, ): super().__init__() self.eos_id = eos_id",
"= (2 * self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight,",
"def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, pixel_values): \"\"\"Encode images Parameters ---------- pixel_values: torch.Tensor",
"\"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\" def forward(self, x: torch.Tensor): orig_type = x.dtype",
"2, 1) # shape = [*, grid ** 2, width] x = torch.cat([",
"x = self.conv1(x) # shape = [*, width, grid, grid] x = x.reshape(x.shape[0],",
"/ 0.07)) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width **",
"int, heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1",
"Tokenized texts from RuCLIPProcessor class Returns ------- text_latents : torch.Tensor Text embeddings \"\"\"",
"for _ in range(layers)]) def forward(self, x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def",
"width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])",
"cosine similarity as logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features @",
"from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'], vision_layers=config['vision_layers'], vision_width=config['vision_width'],",
"__init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):",
"x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return x def forward(self, input_ids, pixel_values): image_features",
"if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self): mask =",
"numpy as np from torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm to",
"super().__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for",
"self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self): mask = torch.empty(self.context_length,",
"x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int,",
"\"\"\"Load model from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model = cls( embed_dim=config['embed_dim'], image_resolution=config['image_resolution'],",
"def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None",
"import numpy as np from torch import nn class LayerNorm(nn.LayerNorm): \"\"\"Subclass torch's LayerNorm",
"= self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text = logits_per_image.t() return",
"LND x = self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD",
"width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask(), ) self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding",
"nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 +",
"= x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection return x def forward(self, input_ids, pixel_values):",
"x.permute(1, 0, 2) # LND -> NLD x = self.ln_final(x).type(self.dtype) # x.shape =",
"self.encode_text(input_ids) # normalize features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features",
"1, width] x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1,",
"int, layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim =",
"self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_final(x).type(self.dtype)",
"x = self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD x",
"x.shape = [batch_size, n_ctx, transformer.width] x = x[torch.arange(x.shape[0]), torch.where(input_ids == self.eos_id)[1]] @ self.text_projection",
"def from_pretrained(cls, folder): \"\"\"Load model from folder\"\"\" config = json.load(open(os.path.join(folder, 'config.json'))) model =",
"nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) *",
"[batch_size, n_ctx, d_model] x = x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2)",
"std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) **",
"<filename>ruclip/model.py # -*- coding: utf-8 -*- import os import json from collections import",
"OrderedDict import torch import numpy as np from torch import nn class LayerNorm(nn.LayerNorm):",
"patch_size: int, width: int, layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution =",
"= attn_mask def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is",
"forward(self, x: torch.Tensor): return self.resblocks(x) class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int,",
"width: int, layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim",
"text_latents : torch.Tensor Text embeddings \"\"\" x = self.token_embedding(input_ids).type(self.dtype) # [batch_size, n_ctx, d_model]",
"# shape = [*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) #",
"nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)",
"not None: x = x @ self.proj return x class CLIP(nn.Module): def __init__(",
"1, x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1) # shape = [*, grid **",
"# -*- coding: utf-8 -*- import os import json from collections import OrderedDict",
"is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length)",
"= VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim, ) self.transformer = Transformer( width=transformer_width,",
"2) # LND -> NLD x = self.ln_final(x).type(self.dtype) # x.shape = [batch_size, n_ctx,",
"forward(self, x: torch.Tensor): x = self.conv1(x) # shape = [*, width, grid, grid]",
"= nn.Sequential(OrderedDict([ ('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4,",
"self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) def",
") self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final",
"logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text = logits_per_image.t()",
"width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): super().__init__() self.width =",
"class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): super().__init__()",
"layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim",
"keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity as logits logit_scale",
"= x.permute(1, 0, 2) # LND -> NLD x = self.ln_final(x).type(self.dtype) # x.shape",
"@ text_features.t() logits_per_text = logits_per_image.t() return logits_per_image, logits_per_text @classmethod def from_pretrained(cls, folder): \"\"\"Load",
"width] x = torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x ],",
"None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ('c_fc',",
"torch.randn(width, output_dim)) def forward(self, x: torch.Tensor): x = self.conv1(x) # shape = [*,",
"std=self.transformer.width ** -0.5) def build_attention_mask(self): mask = torch.empty(self.context_length, self.context_length) mask.fill_(float('-inf')) mask.triu_(1) return mask",
"4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask",
"Returns ------- image_latents : torch.Tensor Image embeddings \"\"\" return self.visual(pixel_values.type(self.dtype)) def encode_text(self, input_ids):",
"self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None return self.attn(x,",
"def encode_text(self, input_ids): \"\"\"Encode texts Parameters ---------- input_ids: torch.Tensor Tokenized texts from RuCLIPProcessor",
"= (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width",
"def forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x = x +",
"input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): super().__init__()",
"shape = [*, width, grid ** 2] x = x.permute(0, 2, 1) #",
"self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final =",
"transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale",
"2] x = x.permute(0, 2, 1) # shape = [*, grid ** 2,",
"= LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))",
"** -0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5",
"('c_fc', nn.Linear(d_model, d_model * 4)), ('gelu', QuickGELU()), ('c_proj', nn.Linear(d_model * 4, d_model)) ]))",
"= torch.cat([ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x ], dim=1) #"
] |
[
"D contains information about the various tasks supported by T5. \"\"\" def __init__(self,",
"to summarize English text. Trained on the CNN/Daily Mail summarization dataset. For more",
"For more information, please see the T5 paper, \"Exploring the Limits of Transfer",
"on the CNN/Daily Mail summarization dataset. For more information, please see the T5",
"a Unified Text-to-Text Transformer\". Appendix D contains information about the various tasks supported",
"the CNN/Daily Mail summarization dataset. For more information, please see the T5 paper,",
"Transfer Learning with a Unified Text-to-Text Transformer\". Appendix D contains information about the",
"English text. Trained on the CNN/Daily Mail summarization dataset. For more information, please",
"the T5 paper, \"Exploring the Limits of Transfer Learning with a Unified Text-to-Text",
"model trained to summarize English text. Trained on the CNN/Daily Mail summarization dataset.",
"about the various tasks supported by T5. \"\"\" def __init__(self, **kwargs): super().__init__('summarization', **kwargs)",
"trained to summarize English text. Trained on the CNN/Daily Mail summarization dataset. For",
"paper, \"Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer\". Appendix",
"Text-to-Text Transformer\". Appendix D contains information about the various tasks supported by T5.",
"Mail summarization dataset. For more information, please see the T5 paper, \"Exploring the",
"Trained on the CNN/Daily Mail summarization dataset. For more information, please see the",
"contains information about the various tasks supported by T5. \"\"\" def __init__(self, **kwargs):",
"A T5 model trained to summarize English text. Trained on the CNN/Daily Mail",
"<filename>textattack/models/summarization/t5_summarization.py from textattack.models.helpers import T5ForTextToText class T5Summarization(T5ForTextToText): \"\"\" A T5 model trained to",
"class T5Summarization(T5ForTextToText): \"\"\" A T5 model trained to summarize English text. Trained on",
"T5ForTextToText class T5Summarization(T5ForTextToText): \"\"\" A T5 model trained to summarize English text. Trained",
"information, please see the T5 paper, \"Exploring the Limits of Transfer Learning with",
"import T5ForTextToText class T5Summarization(T5ForTextToText): \"\"\" A T5 model trained to summarize English text.",
"T5Summarization(T5ForTextToText): \"\"\" A T5 model trained to summarize English text. Trained on the",
"with a Unified Text-to-Text Transformer\". Appendix D contains information about the various tasks",
"please see the T5 paper, \"Exploring the Limits of Transfer Learning with a",
"Limits of Transfer Learning with a Unified Text-to-Text Transformer\". Appendix D contains information",
"dataset. For more information, please see the T5 paper, \"Exploring the Limits of",
"of Transfer Learning with a Unified Text-to-Text Transformer\". Appendix D contains information about",
"\"Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer\". Appendix D",
"the Limits of Transfer Learning with a Unified Text-to-Text Transformer\". Appendix D contains",
"text. Trained on the CNN/Daily Mail summarization dataset. For more information, please see",
"CNN/Daily Mail summarization dataset. For more information, please see the T5 paper, \"Exploring",
"more information, please see the T5 paper, \"Exploring the Limits of Transfer Learning",
"Transformer\". Appendix D contains information about the various tasks supported by T5. \"\"\"",
"Appendix D contains information about the various tasks supported by T5. \"\"\" def",
"summarization dataset. For more information, please see the T5 paper, \"Exploring the Limits",
"Unified Text-to-Text Transformer\". Appendix D contains information about the various tasks supported by",
"T5 model trained to summarize English text. Trained on the CNN/Daily Mail summarization",
"\"\"\" A T5 model trained to summarize English text. Trained on the CNN/Daily",
"see the T5 paper, \"Exploring the Limits of Transfer Learning with a Unified",
"information about the various tasks supported by T5. \"\"\" def __init__(self, **kwargs): super().__init__('summarization',",
"summarize English text. Trained on the CNN/Daily Mail summarization dataset. For more information,",
"from textattack.models.helpers import T5ForTextToText class T5Summarization(T5ForTextToText): \"\"\" A T5 model trained to summarize",
"T5 paper, \"Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer\".",
"Learning with a Unified Text-to-Text Transformer\". Appendix D contains information about the various",
"textattack.models.helpers import T5ForTextToText class T5Summarization(T5ForTextToText): \"\"\" A T5 model trained to summarize English"
] |
[
"intro else: super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None): name = name or",
"attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx):",
"def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and callable(on_finished): on_finished(ctx)",
"decorator(f): cmd = prettyGroup(cls=Shell if not cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return",
"return cmd return decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation with an",
"also: - Allows defining commands with multiple aliases - Allows for addtional command",
"args if tmpCommand is None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias = False",
"len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and callable(on_finished): on_finished(ctx) def on_shell_start(): if",
"cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return",
"has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin",
"Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def",
"hidden=True) def __repeat_command__(): \"\"\"Repeats the last valid command with all previous parameters\"\"\" if",
"within the current session by launching the python app again os.system('python \"%s\"' %",
"cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else:",
"super(MultiCommandShell, self).add_command(cmd) return cmd return decorator class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART,",
"if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A shortcut decorator",
"base shell commands - Implements all pretty formatting features If not attached to",
"as globs from . import _colors as colors from .chars import IGNORE_LINE from",
"attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if",
"from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with an (optionally)",
"a new shell instance? - :param:`prompt`: Prompt Text - :param:`intro`: Shell Intro Text",
"command options (hidden, exit, etc.) - Implements pre-defined base shell commands - Implements",
"prettyGroup(cls=MultiCommandShell if not cls else cls, isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd) return",
"from .utils import HasKey from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group`",
"invoke(self, ctx: click.Context): if self.isShell: ret = super(Shell, self).invoke(ctx) if not ctx.protected_args and",
"globals as globs from . import _colors as colors from .chars import IGNORE_LINE",
"to a shell, functions as a :class:`PrettyGroup` with the non-shell-related features listed above",
"*args, **kwargs): \"\"\"Behaves the same as `click.Group.command()` except if passed a list of",
"this class to be used as a subclass without a new shell instance",
"to be used as a subclass without a new shell instance attached self.isShell",
"def command(self, *args, **kwargs): \"\"\"Behaves the same as `click.Group.command()` except if passed a",
"a shell, functions as a :class:`PrettyGroup` with the non-shell-related features listed above Constructor",
"**kwargs): \"\"\"A shortcut decorator for declaring and attaching a group to the group.",
"= prettyGroup(cls=MultiCommandShell if not cls else cls, isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd)",
"functions as a :class:`PrettyGroup` with the non-shell-related features listed above Constructor Kwargs: -",
"False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd =",
"try: if isinstance(args[0], list): _args = [args[0][0]] + list(args[1:]) for alias in args[0][1:]:",
"without a new shell instance attached self.isShell = isShell if isShell: attrs['invoke_without_command'] =",
"{h}\".format(c = _args[0], h = cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden =",
"cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\"",
"setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A shortcut decorator for declaring and",
"aliases.append(alias) else: _args = args if tmpCommand is None: cmd: PrettyCommand = prettyCommand(*_args,",
"PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell,",
"hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None] = None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True,",
"raise TypeError(\"Command has no name.\") _check_multicommand(self, name, cmd, register=True) if type(name) is str:",
"all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin",
"- :param:`before_start`: os.system() command to execute prior to starting the shell - :param:`readline`:",
"click.core import MultiCommand, _check_multicommand from colorama import Style from . import globals as",
"= prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd)",
"return cmd return decorator def command(self, *args, **kwargs): \"\"\"Behaves the same as `click.Group.command()`",
"aliases for the first. Also allows for use of custom kwargs defined in",
"# Spawns a new shell within the current session by launching the python",
"click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the CLI history for this terminal for",
"CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ ==",
"= cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else:",
"exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the",
"= False self.add_command(cmd) return cmd return decorator def command(self, *args, **kwargs): \"\"\"Behaves the",
"import sys import os from copy import deepcopy from io import StringIO import",
"MultiCommand, _check_multicommand from colorama import Style from . import globals as globs from",
"cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return decorator class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell):",
"from copy import deepcopy from io import StringIO import click from click.core import",
"and callable(before_start): before_start() if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell",
"prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None] = None, before_start=None, readline=None,",
"result else 'failed', Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls():",
"ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with an (optionally) attatched shell. Otherwise",
"- :param:`fuzzy_completion`: If True, use fuzzy completion for prompt_toolkit suggestions - :param:`mouse_support`: If",
"instantiates a new Shell instance and attaches it to the existing Command \"\"\"",
"ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the CLI history for this terminal",
"if prompt: self.shell.prompt = prompt self.shell.intro = intro else: super(Shell, self).__init__(**attrs) def add_command(self,",
"super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args = args if tmpCommand is None: cmd: PrettyCommand",
"a new shell instance attached self.isShell = isShell if isShell: attrs['invoke_without_command'] = True",
"else: cmd = deepcopy(tmpCommand) cmd.alias = False cmd.aliases = aliases cmd.name = _args[0]",
"be aliases for the first. Also allows for use of custom kwargs defined",
"decorator that instantiates a new Shell instance and attaches it to the existing",
"def __restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns a new shell within the current",
"= deepcopy(tmpCommand) cmd.alias = False cmd.aliases = aliases cmd.name = _args[0] cmd.help =",
"None] = None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows this",
"it to the existing Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd",
"mouse_support=False, lexer=True, **attrs): # Allows this class to be used as a subclass",
"if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and callable(on_finished): on_finished(ctx) def on_shell_start():",
"__strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs,",
"group. This takes the same arguments as :func:`group` but immediately registers the created",
"@shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__():",
"declaring and attaching a group to the group. This takes the same arguments",
"this terminal for the current user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE,",
"\"\"\"A :class:`Click Group` implementation with an (optionally) attatched shell. Otherwise functions as a",
"self.add_command(cmd) return cmd return decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation with",
"aliases cmd.name = _args[0] cmd.help = origHelpTxt cmd.short_help = '' cmd.hidden = cmd.true_hidden",
"os.system() command to execute prior to starting the shell - :param:`readline`: If True,",
"pass if on_finished and callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start and callable(before_start): before_start()",
"before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt = prompt self.shell.intro",
"self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context): if self.isShell:",
"self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx = ctx",
"def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a new Shell instance",
"def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns a",
"Otherwise functions as a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach a new shell",
"prompt_toolkit suggestions - :param:`mouse_support`: If True, enables mouse support for prompt_toolkit - :param:`lexer`:",
"= \"(Alias for '{c}') {h}\".format(c = _args[0], h = cmd.help) cmd.short_help = \"Alias",
"new shell instance attached self.isShell = isShell if isShell: attrs['invoke_without_command'] = True super(Shell,",
"else: for _name_ in name: self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd, name) def",
"return self.shell.cmdloop() return ret else: return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A",
"ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a new Shell",
"self.commands[name] = cmd else: for _name_ in name: self.commands[_name_] = cmd if self.isShell:",
"= cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden = True",
"for prompt_toolkit suggestions - :param:`mouse_support`: If True, enables mouse support for prompt_toolkit -",
"is None: raise TypeError(\"Command has no name.\") _check_multicommand(self, name, cmd, register=True) if type(name)",
"isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None] = None, before_start=None,",
"else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return decorator class MultiCommandShell(Shell): \"\"\" A",
"formatting features If not attached to a shell, functions as a :class:`PrettyGroup` with",
"readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows this class to be used",
"or cmd.name if name is None: raise TypeError(\"Command has no name.\") _check_multicommand(self, name,",
"__repeat_command__(): \"\"\"Repeats the last valid command with all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__",
"as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the CLI history for this",
"return cmd except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases =",
"_args[0], h = origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs,",
"cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self,",
"fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt = prompt self.shell.intro = intro else:",
"self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias",
":param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=None, **attrs): self.isShell",
"all after the first will be aliases for the first. Also allows for",
"= [] try: if isinstance(args[0], list): _args = [args[0][0]] + list(args[1:]) for alias",
"before_start() if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell =",
"BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_,",
"name) def invoke(self, ctx: click.Context): if self.isShell: ret = super(Shell, self).invoke(ctx) if not",
"_check_multicommand(self, name, cmd, register=True) if type(name) is str: self.commands[name] = cmd else: for",
"the last valid command with all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True",
"if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs):",
"cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd: PrettyCommand =",
"h = cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden =",
"custom kwargs defined in multicommand.py. \"\"\" def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from",
"globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r')",
"created command with this instance by calling into :meth:`add_command`. \"\"\" from .pretty import",
"HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A shortcut decorator for",
"**kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def new_shell(self, cls=None, **kwargs):",
"def __exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the last",
"- :param:`isShell`: Attach a new shell instance? - :param:`prompt`: Prompt Text - :param:`intro`:",
"self).add_command(cmd) return cmd return decorator class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True)",
"StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with",
"shell instance? - :param:`prompt`: Prompt Text - :param:`intro`: Shell Intro Text - :param:`hist_file`:",
"pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__():",
"if name is None: raise TypeError(\"Command has no name.\") _check_multicommand(self, name, cmd, register=True)",
"None: cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias = True",
"click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell) as ctx:",
"__clear_history__(): \"\"\"Clears the CLI history for this terminal for the current user\"\"\" result",
"else: super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None): name = name or cmd.name",
"- :param:`on_finished`: Callback function when shell closes - :param:`add_command_callback`: Callback for extending command",
"import prettyCommand tmpCommand = None origHelpTxt = None aliases = [] try: if",
"from .pretty import prettyCommand tmpCommand = None origHelpTxt = None aliases = []",
"typing import Callable import sys import os from copy import deepcopy from io",
"if self.isShell: ret = super(Shell, self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name",
"return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a",
"None aliases = [] try: if isinstance(args[0], list): _args = [args[0][0]] + list(args[1:])",
"ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt",
"**kwargs)(f) self.add_command(cmd) return cmd return decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation",
"exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the",
"'History cleared' if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully'",
"import click from click.core import MultiCommand, _check_multicommand from colorama import Style from .",
"._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with an (optionally) attatched",
"globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin =",
"a new shell within the current session by launching the python app again",
"kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to execute prior to starting the",
"from typing import Callable import sys import os from copy import deepcopy from",
":meth:`add_command`. \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias",
"alias in args[0][1:]: if tmpCommand is None: cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f)",
"cmd except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases",
"= aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return decorator class BaseShellCommands: @staticmethod",
"pyreadline instead of any prompt_toolkit features - :param:`complete_while_typing`: If True, prompt_toolkit suggestions will",
"the current session by launching the python app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\',",
"\"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd)",
"__init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None] = None,",
"cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a new Shell instance and attaches",
"existing Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if",
"import prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not cls else cls, isShell=True,",
"cmd return decorator def command(self, *args, **kwargs): \"\"\"Behaves the same as `click.Group.command()` except",
"cmd.true_hidden = cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd",
"True globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else:",
"globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if",
"if not cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return decorator class",
"except if passed a list of names, all after the first will be",
"launching the python app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits the",
"above Constructor Kwargs: - :param:`isShell`: Attach a new shell instance? - :param:`prompt`: Prompt",
"complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows this class to be used as",
"cmd return decorator def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a",
"*args, **kwargs): \"\"\"A shortcut decorator for declaring and attaching a group to the",
"except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs,",
"as :func:`group` but immediately registers the created command with this instance by calling",
"import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup):",
"if self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context): if self.isShell: ret = super(Shell,",
"group(self, *args, **kwargs): \"\"\"A shortcut decorator for declaring and attaching a group to",
"list(args[1:]) for alias in args[0][1:]: if tmpCommand is None: cmd: PrettyCommand = prettyCommand(alias,",
"subclass without a new shell instance attached self.isShell = isShell if isShell: attrs['invoke_without_command']",
"== globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start,",
"cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click",
"import globals as globs from . import _colors as colors from .chars import",
"immediately registers the created command with this instance by calling into :meth:`add_command`. \"\"\"",
"= cmd.help cmd.alias = True cmd.aliases = [] cmd.help = \"(Alias for '{c}')",
"- :param:`readline`: If True, use pyreadline instead of any prompt_toolkit features - :param:`complete_while_typing`:",
"name: self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context): if",
"super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else: cmd = deepcopy(tmpCommand) cmd.alias = True cmd.aliases",
"the same arguments as :func:`group` but immediately registers the created command with this",
"not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass",
"prompt_toolkit - :param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=False,",
"object, str], None] = None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): #",
"tmpCommand is None: cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias",
"def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True,",
"Callback for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to execute",
"If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=None, **attrs): self.isShell =",
"shortcut decorator for declaring and attaching a group to the group. This takes",
"= True cmd.aliases = [] cmd.name = alias cmd.help = \"(Alias for '{c}')",
"shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell) as",
"\"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits the current shell once it's child has",
"(optionally) attatched shell. Otherwise functions as a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach",
"session by launching the python app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) #",
"tmpCommand is None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases =",
"self.isShell: if not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs)",
"super(Shell, self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx =",
"aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return decorator class BaseShellCommands: @staticmethod def",
"isShell if self.isShell: if not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser",
"features - :param:`complete_while_typing`: If True, prompt_toolkit suggestions will be live (on a separate",
"not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx = ctx return self.shell.cmdloop() return ret else:",
"deepcopy from io import StringIO import click from click.core import MultiCommand, _check_multicommand from",
"prettyCommand tmpCommand = None origHelpTxt = None aliases = [] try: if isinstance(args[0],",
"for prompt_toolkit - :param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def __init__(self,",
"= True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if",
"Spawns a new shell within the current session by launching the python app",
"globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell):",
"= origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell,",
"for the first. Also allows for use of custom kwargs defined in multicommand.py.",
"of any prompt_toolkit features - :param:`complete_while_typing`: If True, prompt_toolkit suggestions will be live",
"with an (optionally) attached shell, that also: - Allows defining commands with multiple",
"True cmd.aliases = [] cmd.name = alias cmd.help = \"(Alias for '{c}') {h}\".format(c",
"cmd = prettyGroup(cls=Shell if not cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd",
"def __init__(self, isShell=None, **attrs): self.isShell = isShell attrs['isShell'] = isShell if self.isShell: if",
"arguments as :func:`group` but immediately registers the created command with this instance by",
"if tmpCommand is None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases",
"for addtional command options (hidden, exit, etc.) - Implements pre-defined base shell commands",
"cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias =",
"def invoke(self, ctx: click.Context): if self.isShell: ret = super(Shell, self).invoke(ctx) if not ctx.protected_args",
". import globals as globs from . import _colors as colors from .chars",
"prompt_toolkit lexer \"\"\" def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object,",
"'successfully' if result else 'failed', Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True)",
"True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else: cmd = deepcopy(tmpCommand) cmd.alias",
"= _args[0], h = cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden",
"for the current user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared'",
"= prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd)",
"child has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__ =",
"+ list(args[1:]) for alias in args[0][1:]: if tmpCommand is None: cmd: PrettyCommand =",
"PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias = True cmd.aliases =",
".multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey from ._cmd_factories import ClickCmdShell class",
"return cmd else: cmd = deepcopy(tmpCommand) cmd.alias = False cmd.aliases = aliases cmd.name",
"cmd.alias = False cmd.aliases = aliases cmd.name = _args[0] cmd.help = origHelpTxt cmd.short_help",
"with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the CLI history",
"parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin =",
"True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod",
"prompt self.shell.intro = intro else: super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None): name",
"by calling into :meth:`add_command`. \"\"\" from .pretty import prettyGroup def decorator(f): cmd =",
"the existing Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell",
"'{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args = args",
"\"\"\" def __init__(self, isShell=None, **attrs): self.isShell = isShell attrs['isShell'] = isShell if self.isShell:",
"'{c}') {h}\".format(c = _args[0], h = cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden",
"for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args =",
"Prompt Text - :param:`intro`: Shell Intro Text - :param:`hist_file`: Full Path & Filename",
"if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except:",
".pretty import PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey",
"See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to execute prior to starting the shell",
"Callable import sys import os from copy import deepcopy from io import StringIO",
"\"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell if not cls",
"Allows for addtional command options (hidden, exit, etc.) - Implements pre-defined base shell",
"Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not",
"addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True)",
"cmd.aliases = aliases cmd.name = _args[0] cmd.help = origHelpTxt cmd.short_help = '' cmd.hidden",
"BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None)",
"isShell if isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ =",
"return decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation with an (optionally) attached",
"and attaching a group to the group. This takes the same arguments as",
"- Implements pre-defined base shell commands - Implements all pretty formatting features If",
"with this instance by calling into :meth:`add_command`. \"\"\" from .pretty import prettyGroup def",
"def _exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\"",
"closes - :param:`add_command_callback`: Callback for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system()",
"@shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the last valid command with all previous parameters\"\"\"",
"print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if",
"click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result",
"from colorama import Style from . import globals as globs from . import",
"has no name.\") _check_multicommand(self, name, cmd, register=True) if type(name) is str: self.commands[name] =",
"prettyGroup(cls=Shell if not cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return decorator",
"if passed a list of names, all after the first will be aliases",
"once it's child has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True if shell.shell.readline:",
"= None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows this class",
"last valid command with all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if",
":param:`readline`: If True, use pyreadline instead of any prompt_toolkit features - :param:`complete_while_typing`: If",
"exit, etc.) - Implements pre-defined base shell commands - Implements all pretty formatting",
"HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if",
"= None origHelpTxt = None aliases = [] try: if isinstance(args[0], list): _args",
"shell instance attached self.isShell = isShell if isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs)",
"- Allows defining commands with multiple aliases - Allows for addtional command options",
"thread) - :param:`fuzzy_completion`: If True, use fuzzy completion for prompt_toolkit suggestions - :param:`mouse_support`:",
"cmd.alias = True cmd.aliases = [] cmd.help = \"(Alias for '{c}') {h}\".format(c =",
"kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A shortcut decorator for declaring",
"addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns a new",
"**kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd",
"import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with an (optionally) attatched shell.",
"of names, all after the first will be aliases for the first. Also",
"self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand = None origHelpTxt = None aliases =",
"= StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__():",
"import StringIO import click from click.core import MultiCommand, _check_multicommand from colorama import Style",
"str: self.commands[name] = cmd else: for _name_ in name: self.commands[_name_] = cmd if",
"from click.core import MultiCommand, _check_multicommand from colorama import Style from . import globals",
"If True, enables mouse support for prompt_toolkit - :param:`lexer`: If True, enables the",
"str], None] = None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows",
"= cmd if self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context): if self.isShell: ret",
"terminal for the current user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History",
"click from click.core import MultiCommand, _check_multicommand from colorama import Style from . import",
"History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed', Style.RESET_ALL ))",
"prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not cls else cls, isShell=True, **kwargs)(f)",
"command with this instance by calling into :meth:`add_command`. \"\"\" from .pretty import prettyGroup",
"add_command(self, cmd: click.Command, name=None): name = name or cmd.name if name is None:",
"commands with multiple aliases - Allows for addtional command options (hidden, exit, etc.)",
"Implements all pretty formatting features If not attached to a shell, functions as",
"the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT,",
"for _name_ in name: self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd, name) def invoke(self,",
"Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the last valid command with all",
"= [] cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h = cmd.help)",
"If True, use pyreadline instead of any prompt_toolkit features - :param:`complete_while_typing`: If True,",
"\"\"\"Repeats the last valid command with all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ =",
"Group` implementation with an (optionally) attached shell, that also: - Allows defining commands",
"the same as `click.Group.command()` except if passed a list of names, all after",
"use pyreadline instead of any prompt_toolkit features - :param:`complete_while_typing`: If True, prompt_toolkit suggestions",
"if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__)",
"instance by calling into :meth:`add_command`. \"\"\" from .pretty import prettyGroup def decorator(f): cmd",
"deepcopy(tmpCommand) cmd.alias = False cmd.aliases = aliases cmd.name = _args[0] cmd.help = origHelpTxt",
"@shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the CLI history for this terminal for the",
"and callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start and callable(before_start): before_start() if not self.name",
".pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell if not cls else cls,",
"def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand = None",
"to the existing Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd =",
"cmd.name = _args[0] cmd.help = origHelpTxt cmd.short_help = '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs,",
"self).add_command(cmd) aliases.append(alias) else: _args = args if tmpCommand is None: cmd: PrettyCommand =",
"before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows this class to be",
"if isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name",
"lexer \"\"\" def __init__(self, isShell=None, **attrs): self.isShell = isShell attrs['isShell'] = isShell if",
"Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True)",
"click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the CLI history for",
"attrs['isShell'] = isShell if self.isShell: if not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback']",
"kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_,",
"True, prompt_toolkit suggestions will be live (on a separate thread) - :param:`fuzzy_completion`: If",
"If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None,",
"listed above Constructor Kwargs: - :param:`isShell`: Attach a new shell instance? - :param:`prompt`:",
"allows for use of custom kwargs defined in multicommand.py. \"\"\" def decorator(f): old_kwargs",
"cmd = deepcopy(tmpCommand) cmd.alias = True cmd.aliases = [] cmd.name = alias cmd.help",
"if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def",
"Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with an (optionally) attatched shell. Otherwise functions as",
"\"\"\"Behaves the same as `click.Group.command()` except if passed a list of names, all",
"add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt = prompt",
"the current user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if",
"cleared' if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if",
"closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin",
"alias cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h = origHelpTxt) cmd.short_help",
"shell, functions as a :class:`PrettyGroup` with the non-shell-related features listed above Constructor Kwargs:",
"History File - :param:`on_finished`: Callback function when shell closes - :param:`add_command_callback`: Callback for",
"an (optionally) attatched shell. Otherwise functions as a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`:",
"__get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the CLI",
"click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def",
"the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True)",
"class to be used as a subclass without a new shell instance attached",
"cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else: cmd",
"ctx: click.Context): if self.isShell: ret = super(Shell, self).invoke(ctx) if not ctx.protected_args and not",
":class:`Click Group` implementation with an (optionally) attatched shell. Otherwise functions as a :class:`PrettyGroup`",
"= shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else 'Clear History',",
"\"\"\"A shortcut decorator for declaring and attaching a group to the group. This",
"= prompt self.shell.intro = intro else: super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None):",
":param:`complete_while_typing`: If True, prompt_toolkit suggestions will be live (on a separate thread) -",
"decorator def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a new Shell",
"ret = super(Shell, self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name = None",
"self.isShell = isShell if isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__:",
"Path & Filename to History File - :param:`on_finished`: Callback function when shell closes",
"registers the created command with this instance by calling into :meth:`add_command`. \"\"\" from",
"use fuzzy completion for prompt_toolkit suggestions - :param:`mouse_support`: If True, enables mouse support",
"\"\"\"A shortcut decorator that instantiates a new Shell instance and attaches it to",
"= None aliases = [] try: if isinstance(args[0], list): _args = [args[0][0]] +",
"= aliases cmd.name = _args[0] cmd.help = origHelpTxt cmd.short_help = '' cmd.hidden =",
"on_finished and callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start and callable(before_start): before_start() if not",
"ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx = ctx return self.shell.cmdloop() return",
"= [args[0][0]] + list(args[1:]) for alias in args[0][1:]: if tmpCommand is None: cmd:",
"starting the shell - :param:`readline`: If True, use pyreadline instead of any prompt_toolkit",
"origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd)",
"self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name)",
"_name_ in name: self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx:",
"def cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits the",
"MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def",
"addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True)",
"TypeError(\"Command has no name.\") _check_multicommand(self, name, cmd, register=True) if type(name) is str: self.commands[name]",
"_exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\" pass",
"def __repeat_command__(): \"\"\"Repeats the last valid command with all previous parameters\"\"\" if globs.__LAST_COMMAND__:",
"shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell:",
"first will be aliases for the first. Also allows for use of custom",
"= _args[0] cmd.help = origHelpTxt cmd.short_help = '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd)",
"current session by launching the python app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/'))",
"lexer=True, **attrs): # Allows this class to be used as a subclass without",
"not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell:",
"it's child has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__",
"True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None,",
"a list of names, all after the first will be aliases for the",
":class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach a new shell instance? - :param:`prompt`: Prompt",
"cmd else: cmd = deepcopy(tmpCommand) cmd.alias = True cmd.aliases = [] cmd.name =",
"any prompt_toolkit features - :param:`complete_while_typing`: If True, prompt_toolkit suggestions will be live (on",
"self.isShell = isShell attrs['isShell'] = isShell if self.isShell: if not HasKey('add_command_callback', attrs) or",
"shell once it's child has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True if",
"If True, prompt_toolkit suggestions will be live (on a separate thread) - :param:`fuzzy_completion`:",
"decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation with an (optionally) attached shell,",
"__init__(self, isShell=None, **attrs): self.isShell = isShell attrs['isShell'] = isShell if self.isShell: if not",
"\"(Alias for '{c}') {h}\".format(c = _args[0], h = cmd.help) cmd.short_help = \"Alias for",
"for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args,",
"takes the same arguments as :func:`group` but immediately registers the created command with",
"Kwargs: - :param:`isShell`: Attach a new shell instance? - :param:`prompt`: Prompt Text -",
"(optionally) attached shell, that also: - Allows defining commands with multiple aliases -",
"prettyGroup def decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd",
"is str: self.commands[name] = cmd else: for _name_ in name: self.commands[_name_] = cmd",
"@staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT,",
"list of names, all after the first will be aliases for the first.",
"a subclass without a new shell instance attached self.isShell = isShell if isShell:",
"= deepcopy(tmpCommand) cmd.alias = True cmd.aliases = [] cmd.name = alias cmd.help =",
"class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\"",
"Implements pre-defined base shell commands - Implements all pretty formatting features If not",
"prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias = True cmd.aliases = [] cmd.help",
"else cls, isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def",
"names, all after the first will be aliases for the first. Also allows",
"cmd return decorator class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__():",
"as `click.Group.command()` except if passed a list of names, all after the first",
"and self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_",
".pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not cls else cls,",
"= prettyGroup(cls=Shell if not cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return",
"[] try: if isinstance(args[0], list): _args = [args[0][0]] + list(args[1:]) for alias in",
"to the group. This takes the same arguments as :func:`group` but immediately registers",
"import IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from",
"prompt_toolkit features - :param:`complete_while_typing`: If True, prompt_toolkit suggestions will be live (on a",
"'' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd: PrettyCommand",
"BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def",
"_colors as colors from .chars import IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand from",
"will be live (on a separate thread) - :param:`fuzzy_completion`: If True, use fuzzy",
"= aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd = deepcopy(tmpCommand) cmd.alias",
"with an (optionally) attatched shell. Otherwise functions as a :class:`PrettyGroup` Constructor Kwargs: -",
"True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__):",
"name.\") _check_multicommand(self, name, cmd, register=True) if type(name) is str: self.commands[name] = cmd else:",
"@staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_,",
"self).add_command(cmd) tmpCommand = cmd else: cmd = deepcopy(tmpCommand) cmd.alias = True cmd.aliases =",
"origHelpTxt = None aliases = [] try: if isinstance(args[0], list): _args = [args[0][0]]",
"= cmd else: cmd = deepcopy(tmpCommand) cmd.alias = True cmd.aliases = [] cmd.name",
"the existing Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell",
"not cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return decorator class MultiCommandShell(Shell):",
"Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\"",
"mouse support for prompt_toolkit - :param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\"",
"This takes the same arguments as :func:`group` but immediately registers the created command",
"**kwargs): \"\"\"A shortcut decorator that instantiates a new Shell instance and attaches it",
".chars import IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser",
"Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell if not",
"hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits",
"if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed', Style.RESET_ALL )) @staticmethod def",
"_args = [args[0][0]] + list(args[1:]) for alias in args[0][1:]: if tmpCommand is None:",
"user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else",
"import HasKey from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with",
"def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not cls else cls, isShell=True, **kwargs)(f) cmd.alias",
"prompt: self.shell.prompt = prompt self.shell.intro = intro else: super(Shell, self).__init__(**attrs) def add_command(self, cmd:",
"cmd if self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context): if self.isShell: ret =",
"attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell:",
"MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a new",
"MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation with an (optionally) attached shell, that also:",
"@shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns a new shell within",
"name or cmd.name if name is None: raise TypeError(\"Command has no name.\") _check_multicommand(self,",
"cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args = args if",
"cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias)",
"prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell if not cls else cls, isShell=True, **kwargs)(f)",
"- :param:`mouse_support`: If True, enables mouse support for prompt_toolkit - :param:`lexer`: If True,",
"colors from .chars import IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand from .multicommand import",
"Shell instance and attaches it to the existing Command \"\"\" from .pretty import",
"hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns a new shell within the",
"decorator for declaring and attaching a group to the group. This takes the",
"else: return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates",
"separate thread) - :param:`fuzzy_completion`: If True, use fuzzy completion for prompt_toolkit suggestions -",
"copy import deepcopy from io import StringIO import click from click.core import MultiCommand,",
"instance and attaches it to the existing Command \"\"\" from .pretty import prettyGroup",
"cmd = prettyGroup(cls=MultiCommandShell if not cls else cls, isShell=True, **kwargs)(f) cmd.alias = False",
":class:`Click Group` implementation with an (optionally) attached shell, that also: - Allows defining",
"type(name) is str: self.commands[name] = cmd else: for _name_ in name: self.commands[_name_] =",
"= origHelpTxt cmd.short_help = '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return",
"the prompt_toolkit lexer \"\"\" def __init__(self, isShell=None, **attrs): self.isShell = isShell attrs['isShell'] =",
"return decorator def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a new",
"an (optionally) attached shell, that also: - Allows defining commands with multiple aliases",
"If True, use fuzzy completion for prompt_toolkit suggestions - :param:`mouse_support`: If True, enables",
"but immediately registers the created command with this instance by calling into :meth:`add_command`.",
"= ctx return self.shell.cmdloop() return ret else: return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None,",
"the CLI history for this terminal for the current user\"\"\" result = shell.shell.clear_history()",
"= prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias = True cmd.aliases = []",
"None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows this class to",
"and not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx = ctx return self.shell.cmdloop() return ret",
"prompt_toolkit suggestions will be live (on a separate thread) - :param:`fuzzy_completion`: If True,",
"prompt_toolkit - :param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=None,",
"self.shell.intro = intro else: super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None): name =",
"- :param:`prompt`: Prompt Text - :param:`intro`: Shell Intro Text - :param:`hist_file`: Full Path",
"name is None: raise TypeError(\"Command has no name.\") _check_multicommand(self, name, cmd, register=True) if",
"attatched shell. Otherwise functions as a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach a",
"_args[0] cmd.help = origHelpTxt cmd.short_help = '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell,",
"before_start and callable(before_start): before_start() if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the",
"Attach a new shell instance? - :param:`prompt`: Prompt Text - :param:`intro`: Shell Intro",
"pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the last valid command with all previous",
"def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def",
"PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey from ._cmd_factories import",
"globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start and",
"CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in",
"cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd)",
"= True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args = args if tmpCommand",
"command to execute prior to starting the shell - :param:`readline`: If True, use",
"if self.isShell: if not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell,",
":param:`hist_file`: Full Path & Filename to History File - :param:`on_finished`: Callback function when",
"origHelpTxt cmd.short_help = '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd",
"- :param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=None, **attrs):",
"implementation with an (optionally) attatched shell. Otherwise functions as a :class:`PrettyGroup` Constructor Kwargs:",
":param:`fuzzy_completion`: If True, use fuzzy completion for prompt_toolkit suggestions - :param:`mouse_support`: If True,",
":param:`intro`: Shell Intro Text - :param:`hist_file`: Full Path & Filename to History File",
"return cmd return decorator class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def",
"\"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the last valid command",
"if before_start and callable(before_start): before_start() if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create",
"_kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A shortcut decorator for declaring and attaching",
"old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand = None origHelpTxt =",
"import deepcopy from io import StringIO import click from click.core import MultiCommand, _check_multicommand",
"self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context): if self.isShell: ret = super(Shell, self).invoke(ctx) if",
"click.Context): if self.isShell: ret = super(Shell, self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand:",
"- Implements all pretty formatting features If not attached to a shell, functions",
":func:`group` but immediately registers the created command with this instance by calling into",
"intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None] = None, before_start=None, readline=None, complete_while_typing=True,",
"attached shell, that also: - Allows defining commands with multiple aliases - Allows",
"colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed', Style.RESET_ALL )) @staticmethod",
"None: raise TypeError(\"Command has no name.\") _check_multicommand(self, name, cmd, register=True) if type(name) is",
"self.add_command(cmd) return cmd return decorator def command(self, *args, **kwargs): \"\"\"Behaves the same as",
"by launching the python app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits",
"\"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias =",
"etc.) - Implements pre-defined base shell commands - Implements all pretty formatting features",
"for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to execute prior",
"the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer",
"return decorator def command(self, *args, **kwargs): \"\"\"Behaves the same as `click.Group.command()` except if",
"None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias = True cmd.aliases = [] cmd.help =",
"if type(name) is str: self.commands[name] = cmd else: for _name_ in name: self.commands[_name_]",
"for '{c}') {h}\".format(c = _args[0], h = origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0])",
"None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs,",
"in multicommand.py. \"\"\" def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand",
"= self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and",
"from . import globals as globs from . import _colors as colors from",
":param:`add_command_callback`: Callback for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to",
"function when shell closes - :param:`add_command_callback`: Callback for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()`",
"_check_multicommand from colorama import Style from . import globals as globs from .",
"if not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx = ctx return",
"isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def command(self, *args,",
"current user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result",
"for declaring and attaching a group to the group. This takes the same",
"'/')) # Exits the current shell once it's child has closed globs.__IS_REPEAT__ =",
"use of custom kwargs defined in multicommand.py. \"\"\" def decorator(f): old_kwargs = kwargs.copy()",
"cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f)",
"self).add_command(cmd) return cmd else: cmd = deepcopy(tmpCommand) cmd.alias = False cmd.aliases = aliases",
"shell - :param:`readline`: If True, use pyreadline instead of any prompt_toolkit features -",
"super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias = False",
"command with all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if shell.shell.readline: globs.__PREV_STDIN__",
"import MultiCommand, _check_multicommand from colorama import Style from . import globals as globs",
"h = origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd)",
"CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A shortcut",
"cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h = origHelpTxt) cmd.short_help =",
"'{c}') {h}\".format(c = _args[0], h = origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden",
"\"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\" pass",
"& Filename to History File - :param:`on_finished`: Callback function when shell closes -",
"Shell Intro Text - :param:`hist_file`: Full Path & Filename to History File -",
"result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else 'Clear",
"= _args[0], h = origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden = True",
"the non-shell-related features listed above Constructor Kwargs: - :param:`isShell`: Attach a new shell",
"def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY,",
"\"\"\" def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None]",
"CustomCommandPropsParser from .utils import HasKey from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click",
"**kwargs)(f) origHelpTxt = cmd.help cmd.alias = True cmd.aliases = [] cmd.help = \"(Alias",
"Callback function when shell closes - :param:`add_command_callback`: Callback for extending command kwargs. See",
"non-shell-related features listed above Constructor Kwargs: - :param:`isShell`: Attach a new shell instance?",
"\"\"\" def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand =",
"register=True) if type(name) is str: self.commands[name] = cmd else: for _name_ in name:",
"self.shell.cmdloop() return ret else: return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut",
"that instantiates a new Shell instance and attaches it to the existing Command",
"on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt =",
"ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx = ctx return self.shell.cmdloop() return ret else: return",
"the current shell once it's child has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ =",
"from io import StringIO import click from click.core import MultiCommand, _check_multicommand from colorama",
"self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback,",
"self).add_command(cmd) return cmd except: cmd: PrettyCommand = prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases",
"if not cls else cls, isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd",
"if not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if",
"import os from copy import deepcopy from io import StringIO import click from",
"in name: self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context):",
"as colors from .chars import IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand from .multicommand",
".pretty import prettyGroup def decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd)",
"except: pass if on_finished and callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start and callable(before_start):",
"with the non-shell-related features listed above Constructor Kwargs: - :param:`isShell`: Attach a new",
"functions as a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach a new shell instance?",
"return cmd return decorator def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates",
".pretty import prettyCommand tmpCommand = None origHelpTxt = None aliases = [] try:",
"aliases = [] try: if isinstance(args[0], list): _args = [args[0][0]] + list(args[1:]) for",
"if tmpCommand is None: cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help",
"= \"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell,",
"\"(Alias for '{c}') {h}\".format(c = _args[0], h = origHelpTxt) cmd.short_help = \"Alias for",
"shell commands - Implements all pretty formatting features If not attached to a",
"a group to the group. This takes the same arguments as :func:`group` but",
"isinstance(args[0], list): _args = [args[0][0]] + list(args[1:]) for alias in args[0][1:]: if tmpCommand",
"as a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach a new shell instance? -",
"@shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__():",
"cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else: cmd =",
"tmpCommand = None origHelpTxt = None aliases = [] try: if isinstance(args[0], list):",
"instead of any prompt_toolkit features - :param:`complete_while_typing`: If True, prompt_toolkit suggestions will be",
"current shell once it's child has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__ = True",
") if prompt: self.shell.prompt = prompt self.shell.intro = intro else: super(Shell, self).__init__(**attrs) def",
"multiple aliases - Allows for addtional command options (hidden, exit, etc.) - Implements",
"not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and",
"shell closes - :param:`add_command_callback`: Callback for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`:",
"= CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__",
"existing Command \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell if",
"deepcopy(tmpCommand) cmd.alias = True cmd.aliases = [] cmd.name = alias cmd.help = \"(Alias",
"args[0][1:]: if tmpCommand is None: cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt =",
"True cmd.aliases = [] cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h",
"_args = args if tmpCommand is None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias",
"% sys.argv[0].replace('\\\\', '/')) # Exits the current shell once it's child has closed",
"else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed', Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell):",
"def group(self, *args, **kwargs): \"\"\"A shortcut decorator for declaring and attaching a group",
"kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand = None origHelpTxt = None aliases",
"lexer \"\"\" def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str],",
"'{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand =",
"Text - :param:`intro`: Shell Intro Text - :param:`hist_file`: Full Path & Filename to",
"else 'failed', Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears",
"True, use fuzzy completion for prompt_toolkit suggestions - :param:`mouse_support`: If True, enables mouse",
"hidden=True, exit=True) def _exit_(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits",
"from . import _colors as colors from .chars import IGNORE_LINE from .pretty import",
"valid command with all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if shell.shell.readline:",
"isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def",
"the shell - :param:`readline`: If True, use pyreadline instead of any prompt_toolkit features",
"attached to a shell, functions as a :class:`PrettyGroup` with the non-shell-related features listed",
"defined in multicommand.py. \"\"\" def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import",
"None origHelpTxt = None aliases = [] try: if isinstance(args[0], list): _args =",
"list): _args = [args[0][0]] + list(args[1:]) for alias in args[0][1:]: if tmpCommand is",
"if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS:",
"isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click Group`",
"\"Alias for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args",
"to starting the shell - :param:`readline`: If True, use pyreadline instead of any",
"be used as a subclass without a new shell instance attached self.isShell =",
"cmd = prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def",
"True, enables mouse support for prompt_toolkit - :param:`lexer`: If True, enables the prompt_toolkit",
"Intro Text - :param:`hist_file`: Full Path & Filename to History File - :param:`on_finished`:",
"= kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand = None origHelpTxt = None",
"os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits the current shell once it's child",
"= \"Alias for '{}'\".format(_args[0]) cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else:",
"multicommand.py. \"\"\" def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand",
"# Exits the current shell once it's child has closed globs.__IS_REPEAT__ = True",
"tmpCommand = cmd else: cmd = deepcopy(tmpCommand) cmd.alias = True cmd.aliases = []",
"- :param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=False, prompt=None,",
"if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS:",
"used as a subclass without a new shell instance attached self.isShell = isShell",
"fuzzy completion for prompt_toolkit suggestions - :param:`mouse_support`: If True, enables mouse support for",
"= ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt:",
"self.add_command(cmd) return cmd return decorator def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that",
"a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach a new shell instance? - :param:`prompt`:",
"globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing,",
"= super(Shell, self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx",
":param:`on_finished`: Callback function when shell closes - :param:`add_command_callback`: Callback for extending command kwargs.",
"Exits the current shell once it's child has closed globs.__IS_REPEAT__ = True globs.__IS_EXITING__",
"import Style from . import globals as globs from . import _colors as",
"a new Shell instance and attaches it to the existing Command \"\"\" from",
"self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else: cmd = deepcopy(tmpCommand) cmd.alias =",
"PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey from ._cmd_factories",
"prior to starting the shell - :param:`readline`: If True, use pyreadline instead of",
"= cmd else: for _name_ in name: self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd,",
"- Allows for addtional command options (hidden, exit, etc.) - Implements pre-defined base",
"new Shell instance and attaches it to the existing Command \"\"\" from .pretty",
"same arguments as :func:`group` but immediately registers the created command with this instance",
"if on_finished and callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start and callable(before_start): before_start() if",
"import Callable import sys import os from copy import deepcopy from io import",
"super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None): name = name or cmd.name if",
"for use of custom kwargs defined in multicommand.py. \"\"\" def decorator(f): old_kwargs =",
"in args[0][1:]: if tmpCommand is None: cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt",
"_kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for",
"= cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd: PrettyCommand = prettyCommand(*args,",
"File - :param:`on_finished`: Callback function when shell closes - :param:`add_command_callback`: Callback for extending",
"@shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats",
"self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args = args if tmpCommand is None:",
"(hidden, exit, etc.) - Implements pre-defined base shell commands - Implements all pretty",
"[args[0][0]] + list(args[1:]) for alias in args[0][1:]: if tmpCommand is None: cmd: PrettyCommand",
"the first will be aliases for the first. Also allows for use of",
"for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd):",
"kwargs defined in multicommand.py. \"\"\" def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty",
"cmd, register=True) if type(name) is str: self.commands[name] = cmd else: for _name_ in",
"into :meth:`add_command`. \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(*args, **kwargs)(f)",
"command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to execute prior to starting",
"- :param:`intro`: Shell Intro Text - :param:`hist_file`: Full Path & Filename to History",
"= True cmd.aliases = [] cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0],",
"for '{c}') {h}\".format(c = _args[0], h = cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0])",
":func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to execute prior to starting the shell -",
"= False self.add_command(cmd) return cmd return decorator def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut",
"{h}\".format(c = _args[0], h = origHelpTxt) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.hidden =",
"the python app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits the current",
"cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd)",
"__exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the last valid",
"decorator class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the",
"None self.shell.ctx = ctx return self.shell.cmdloop() return ret else: return MultiCommand.invoke(self, ctx) def",
"self.shell.prompt = prompt self.shell.intro = intro else: super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command,",
"shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE",
"= sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP,",
"hidden=True) def __get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears",
"else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell)",
"cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs,",
"pre-defined base shell commands - Implements all pretty formatting features If not attached",
"try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start",
"from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias = False",
"app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits the current shell once",
"previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin",
". import _colors as colors from .chars import IGNORE_LINE from .pretty import PrettyGroup,",
"ctx.info_name = None self.shell.ctx = ctx return self.shell.cmdloop() return ret else: return MultiCommand.invoke(self,",
"cmd else: cmd = deepcopy(tmpCommand) cmd.alias = False cmd.aliases = aliases cmd.name =",
"class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with an (optionally) attatched shell. Otherwise functions",
"instance? - :param:`prompt`: Prompt Text - :param:`intro`: Shell Intro Text - :param:`hist_file`: Full",
"MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns a new shell",
"on_finished(ctx) def on_shell_start(): if before_start and callable(before_start): before_start() if not self.name == globs.__MASTER_SHELL__:",
"# Create the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion,",
"self.shell.ctx = ctx return self.shell.cmdloop() return ret else: return MultiCommand.invoke(self, ctx) def new_shell(self,",
"commands - Implements all pretty formatting features If not attached to a shell,",
"None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd,",
"callable(before_start): before_start() if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell",
"again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits the current shell once it's",
"cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h = cmd.help) cmd.short_help =",
"def __clear_history__(): \"\"\"Clears the CLI history for this terminal for the current user\"\"\"",
"If not attached to a shell, functions as a :class:`PrettyGroup` with the non-shell-related",
"the first. Also allows for use of custom kwargs defined in multicommand.py. \"\"\"",
"to History File - :param:`on_finished`: Callback function when shell closes - :param:`add_command_callback`: Callback",
"globs from . import _colors as colors from .chars import IGNORE_LINE from .pretty",
"cmd.name if name is None: raise TypeError(\"Command has no name.\") _check_multicommand(self, name, cmd,",
"\"\"\" A :class:`Click Group` implementation with an (optionally) attached shell, that also: -",
"colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE,",
"PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell,",
"_kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs):",
"= False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd",
"first. Also allows for use of custom kwargs defined in multicommand.py. \"\"\" def",
"sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True)",
"Constructor Kwargs: - :param:`isShell`: Attach a new shell instance? - :param:`prompt`: Prompt Text",
"MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def",
"Callable[[ClickCmdShell, object, str], None] = None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True, **attrs):",
"from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey from ._cmd_factories import ClickCmdShell",
"name=None): name = name or cmd.name if name is None: raise TypeError(\"Command has",
"self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if",
"in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_",
"= \"(Alias for '{c}') {h}\".format(c = _args[0], h = origHelpTxt) cmd.short_help = \"Alias",
"prompt_toolkit lexer \"\"\" def __init__(self, isShell=None, **attrs): self.isShell = isShell attrs['isShell'] = isShell",
"return ret else: return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator",
"not cls else cls, isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return",
"= False cmd.aliases = aliases cmd.name = _args[0] cmd.help = origHelpTxt cmd.short_help =",
"not attached to a shell, functions as a :class:`PrettyGroup` with the non-shell-related features",
"cmd.alias = False self.add_command(cmd) return cmd return decorator def command(self, *args, **kwargs): \"\"\"Behaves",
"io import StringIO import click from click.core import MultiCommand, _check_multicommand from colorama import",
"cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd)",
"'failed', Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the",
"def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_])",
"def decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return",
"else: _args = args if tmpCommand is None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f)",
"shell, that also: - Allows defining commands with multiple aliases - Allows for",
"from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell if not cls else",
"group to the group. This takes the same arguments as :func:`group` but immediately",
"is None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases",
"= False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return decorator",
"def add_command(self, cmd: click.Command, name=None): name = name or cmd.name if name is",
"is None: cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias =",
"on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and callable(on_finished): on_finished(ctx) def",
"as a :class:`PrettyGroup` with the non-shell-related features listed above Constructor Kwargs: - :param:`isShell`:",
":param:`isShell`: Attach a new shell instance? - :param:`prompt`: Prompt Text - :param:`intro`: Shell",
"in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A",
"cmd: click.Command, name=None): name = name or cmd.name if name is None: raise",
"command(self, *args, **kwargs): \"\"\"Behaves the same as `click.Group.command()` except if passed a list",
"cmd else: for _name_ in name: self.commands[_name_] = cmd if self.isShell: self.shell.add_command(cmd, name)",
"attaching a group to the group. This takes the same arguments as :func:`group`",
"sys import os from copy import deepcopy from io import StringIO import click",
"= isShell if isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__",
"globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for",
"= prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def new_shell(self,",
"suggestions will be live (on a separate thread) - :param:`fuzzy_completion`: If True, use",
"the prompt_toolkit lexer \"\"\" def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell,",
"callable(on_finished): on_finished(ctx) def on_shell_start(): if before_start and callable(before_start): before_start() if not self.name ==",
"from .pretty import PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import",
"with multiple aliases - Allows for addtional command options (hidden, exit, etc.) -",
"super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd = deepcopy(tmpCommand) cmd.alias = False cmd.aliases =",
":class:`PrettyGroup` with the non-shell-related features listed above Constructor Kwargs: - :param:`isShell`: Attach a",
"of custom kwargs defined in multicommand.py. \"\"\" def decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs)",
"cmd.help = origHelpTxt cmd.short_help = '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd)",
"BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\" #",
"Create the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support,",
"if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self)",
"_args[0], h = cmd.help) cmd.short_help = \"Alias for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden",
"if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result",
"readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt = prompt self.shell.intro =",
"False self.add_command(cmd) return cmd return decorator def command(self, *args, **kwargs): \"\"\"Behaves the same",
"prettyCommand(*args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return",
"Group` implementation with an (optionally) attatched shell. Otherwise functions as a :class:`PrettyGroup` Constructor",
"isShell=None, **attrs): self.isShell = isShell attrs['isShell'] = isShell if self.isShell: if not HasKey('add_command_callback',",
"that also: - Allows defining commands with multiple aliases - Allows for addtional",
"a :class:`PrettyGroup` with the non-shell-related features listed above Constructor Kwargs: - :param:`isShell`: Attach",
"**kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def command(self, *args, **kwargs):",
"execute prior to starting the shell - :param:`readline`: If True, use pyreadline instead",
"options (hidden, exit, etc.) - Implements pre-defined base shell commands - Implements all",
"**attrs): self.isShell = isShell attrs['isShell'] = isShell if self.isShell: if not HasKey('add_command_callback', attrs)",
"new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that instantiates a new Shell instance and",
"the created command with this instance by calling into :meth:`add_command`. \"\"\" from .pretty",
"False self.add_command(cmd) return cmd return decorator def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator",
"cmd return decorator class MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation with an (optionally)",
"IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils",
"decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator",
"def __get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx)) @shell.command(globs.BASIC_COMMAND_ALIAS_CLEARHISTORY, hidden=True) def __clear_history__(): \"\"\"Clears the",
"`click.Group.command()` except if passed a list of names, all after the first will",
"super(Shell, self).__init__(**attrs) if not globs.__MASTER_SHELL__: globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try:",
":param:`before_start`: os.system() command to execute prior to starting the shell - :param:`readline`: If",
"aliases - Allows for addtional command options (hidden, exit, etc.) - Implements pre-defined",
"\"\"\"Restarts the application\"\"\" # Spawns a new shell within the current session by",
"HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self)",
"= True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else: cmd = deepcopy(tmpCommand)",
"history for this terminal for the current user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{}",
"shortcut decorator that instantiates a new Shell instance and attaches it to the",
"self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd = deepcopy(tmpCommand) cmd.alias = False",
"cmd.alias = True cmd.aliases = [] cmd.name = alias cmd.help = \"(Alias for",
"== self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_,",
"Text - :param:`hist_file`: Full Path & Filename to History File - :param:`on_finished`: Callback",
"else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed',",
"python app again os.system('python \"%s\"' % sys.argv[0].replace('\\\\', '/')) # Exits the current shell",
"def decorator(f): cmd = prettyGroup(cls=Shell if not cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd)",
"os from copy import deepcopy from io import StringIO import click from click.core",
"kwargs.pop(_kwarg_, None) @staticmethod def __assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs):",
"prettyCommand(*_args, **kwargs)(f) cmd.alias = False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return",
"new shell within the current session by launching the python app again os.system('python",
"implementation with an (optionally) attached shell, that also: - Allows defining commands with",
"Allows defining commands with multiple aliases - Allows for addtional command options (hidden,",
"\"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_EXIT, exit=True) def __exit__(): \"\"\"Exits the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT,",
".utils import HasKey from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation",
"Filename to History File - :param:`on_finished`: Callback function when shell closes - :param:`add_command_callback`:",
"and attaches it to the existing Command \"\"\" from .pretty import prettyGroup def",
"result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else",
"cmd.short_help = '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except:",
"as a subclass without a new shell instance attached self.isShell = isShell if",
"support for prompt_toolkit - :param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def",
"Full Path & Filename to History File - :param:`on_finished`: Callback function when shell",
"the application\"\"\" # Spawns a new shell within the current session by launching",
"False cmd.aliases = aliases cmd.name = _args[0] cmd.help = origHelpTxt cmd.short_help = ''",
"all pretty formatting features If not attached to a shell, functions as a",
"after the first will be aliases for the first. Also allows for use",
"Style from . import globals as globs from . import _colors as colors",
"= intro else: super(Shell, self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None): name = name",
"for alias in args[0][1:]: if tmpCommand is None: cmd: PrettyCommand = prettyCommand(alias, None,",
"cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd = deepcopy(tmpCommand)",
"cls else cls, isShell=True, **kwargs)(f) self.add_command(cmd) return cmd return decorator class MultiCommandShell(Shell): \"\"\"",
"decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not cls else cls, isShell=True, **kwargs)(f) cmd.alias =",
"else: cmd = deepcopy(tmpCommand) cmd.alias = True cmd.aliases = [] cmd.name = alias",
"cmd = deepcopy(tmpCommand) cmd.alias = False cmd.aliases = aliases cmd.name = _args[0] cmd.help",
"application\"\"\" # Spawns a new shell within the current session by launching the",
"A :class:`Click Group` implementation with an (optionally) attached shell, that also: - Allows",
"Allows this class to be used as a subclass without a new shell",
"\"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not cls",
"completion for prompt_toolkit suggestions - :param:`mouse_support`: If True, enables mouse support for prompt_toolkit",
"live (on a separate thread) - :param:`fuzzy_completion`: If True, use fuzzy completion for",
"attaches it to the existing Command \"\"\" from .pretty import prettyGroup def decorator(f):",
"features listed above Constructor Kwargs: - :param:`isShell`: Attach a new shell instance? -",
"suggestions - :param:`mouse_support`: If True, enables mouse support for prompt_toolkit - :param:`lexer`: If",
"[] cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h = cmd.help) cmd.short_help",
"True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args = args if tmpCommand is",
"StringIO import click from click.core import MultiCommand, _check_multicommand from colorama import Style from",
"@shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\" click.clear() @shell.command(globs.SHELL_COMMAND_ALIAS_QUIT, hidden=True, exit=True) def _exit_():",
"shell. Otherwise functions as a :class:`PrettyGroup` Constructor Kwargs: - :param:`isShell`: Attach a new",
"False cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return decorator class",
"@staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def __get_help__(): with click.Context(shell) as ctx: click.echo(shell.get_help(ctx))",
"ret else: return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs): \"\"\"A shortcut decorator that",
"complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt = prompt self.shell.intro = intro",
"cmd.aliases = [] cmd.name = alias cmd.help = \"(Alias for '{c}') {h}\".format(c =",
"**kwargs): \"\"\"Behaves the same as `click.Group.command()` except if passed a list of names,",
"cmd: PrettyCommand = prettyCommand(alias, None, **kwargs)(f) origHelpTxt = cmd.help cmd.alias = True cmd.aliases",
"passed a list of names, all after the first will be aliases for",
"defining commands with multiple aliases - Allows for addtional command options (hidden, exit,",
"True, use pyreadline instead of any prompt_toolkit features - :param:`complete_while_typing`: If True, prompt_toolkit",
"if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell = ClickCmdShell(hist_file=hist_file,",
"prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def new_shell(self, cls=None,",
"self).__init__(**attrs) def add_command(self, cmd: click.Command, name=None): name = name or cmd.name if name",
"no name.\") _check_multicommand(self, name, cmd, register=True) if type(name) is str: self.commands[name] = cmd",
"be live (on a separate thread) - :param:`fuzzy_completion`: If True, use fuzzy completion",
"fuzzy_completion=True, mouse_support=False, lexer=True, **attrs): # Allows this class to be used as a",
"globs.__MASTER_SHELL__ = self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished",
"self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in",
"colorama import Style from . import globals as globs from . import _colors",
"self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self)",
"= isShell attrs['isShell'] = isShell if self.isShell: if not HasKey('add_command_callback', attrs) or not",
"addtional command options (hidden, exit, etc.) - Implements pre-defined base shell commands -",
"this instance by calling into :meth:`add_command`. \"\"\" from .pretty import prettyGroup def decorator(f):",
"aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd = deepcopy(tmpCommand) cmd.alias =",
"import PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey from",
"attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if",
"CLI history for this terminal for the current user\"\"\" result = shell.shell.clear_history() print()",
"extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command to execute prior to",
"- :param:`hist_file`: Full Path & Filename to History File - :param:`on_finished`: Callback function",
"when shell closes - :param:`add_command_callback`: Callback for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` -",
":param:`prompt`: Prompt Text - :param:`intro`: Shell Intro Text - :param:`hist_file`: Full Path &",
"for '{}'\".format(_args[0]) cmd.true_hidden = cmd.hidden cmd.hidden = True self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand",
"calling into :meth:`add_command`. \"\"\" from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(*args,",
"cmd.aliases = [] cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h =",
"name = name or cmd.name if name is None: raise TypeError(\"Command has no",
"__restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns a new shell within the current session",
"instance attached self.isShell = isShell if isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if",
"the Shell\"\"\" pass @shell.command(globs.SHELL_COMMAND_ALIAS_REPEAT, hidden=True) def __repeat_command__(): \"\"\"Repeats the last valid command with",
"@staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): kwargs.pop(_kwarg_, None) @staticmethod",
"= args if tmpCommand is None: cmd: PrettyCommand = prettyCommand(*_args, **kwargs)(f) cmd.alias =",
"result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed', Style.RESET_ALL )) @staticmethod def addAll(shell:",
"cmd) super(MultiCommandShell, self).add_command(cmd) aliases.append(alias) else: _args = args if tmpCommand is None: cmd:",
"HasKey from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A :class:`Click Group` implementation with an",
"to execute prior to starting the shell - :param:`readline`: If True, use pyreadline",
"class MultiCommandShell(Shell): \"\"\" A :class:`Click Group` implementation with an (optionally) attached shell, that",
"same as `click.Group.command()` except if passed a list of names, all after the",
"cmd.help cmd.alias = True cmd.aliases = [] cmd.help = \"(Alias for '{c}') {h}\".format(c",
"\"\"\"Clears the CLI history for this terminal for the current user\"\"\" result =",
"sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE) @staticmethod def addBasics(shell: MultiCommandShell): @shell.command(globs.BASIC_COMMAND_ALIAS_HELP, hidden=True) def",
"# Allows this class to be used as a subclass without a new",
"CUSTOM_COMMAND_PROPS, CustomCommandPropsParser from .utils import HasKey from ._cmd_factories import ClickCmdShell class Shell(PrettyGroup): \"\"\"A",
"decorator(f): old_kwargs = kwargs.copy() self.__strip_invalidKeys(kwargs) from .pretty import prettyCommand tmpCommand = None origHelpTxt",
"from .pretty import prettyGroup def decorator(f): cmd = prettyGroup(cls=MultiCommandShell if not cls else",
"add_command_callback: Callable[[ClickCmdShell, object, str], None] = None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False, lexer=True,",
"import prettyGroup def decorator(f): cmd = prettyGroup(cls=Shell if not cls else cls, isShell=True,",
"kwargs[_kwarg_]) def group(self, *args, **kwargs): \"\"\"A shortcut decorator for declaring and attaching a",
"on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None] = None, before_start=None, readline=None, complete_while_typing=True, fuzzy_completion=True, mouse_support=False,",
"= '' cmd.hidden = cmd.true_hidden self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd except: cmd:",
"or not attrs['add_command_callback']: attrs['add_command_callback'] = CustomCommandPropsParser super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__",
"self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return decorator class BaseShellCommands: @staticmethod def addMasters(shell:",
"super(MultiCommandShell, self).__init__(**attrs) if self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ == self.name:",
"cmd) super(MultiCommandShell, self).add_command(cmd) tmpCommand = cmd else: cmd = deepcopy(tmpCommand) cmd.alias = True",
"enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback:",
"def on_shell_start(): if before_start and callable(before_start): before_start() if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name)",
"colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed', Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR,",
"lexer=lexer ) if prompt: self.shell.prompt = prompt self.shell.intro = intro else: super(Shell, self).__init__(**attrs)",
"will be aliases for the first. Also allows for use of custom kwargs",
":param:`lexer`: If True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=False, prompt=None, intro=None,",
"- :param:`add_command_callback`: Callback for extending command kwargs. See :func:`multicommand.CustomCommandPropsParser()` - :param:`before_start`: os.system() command",
"= isShell if self.isShell: if not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']: attrs['add_command_callback'] =",
"__assign_invalidKeys(kwargs, cmd): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs): setattr(cmd, _kwarg_, kwargs[_kwarg_]) def",
"= None self.shell.ctx = ctx return self.shell.cmdloop() return ret else: return MultiCommand.invoke(self, ctx)",
"hidden=True) def __clear_history__(): \"\"\"Clears the CLI history for this terminal for the current",
"attached self.isShell = isShell if isShell: attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) if not",
"origHelpTxt = cmd.help cmd.alias = True cmd.aliases = [] cmd.help = \"(Alias for",
"= [] cmd.name = alias cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0],",
"on_shell_start(): if before_start and callable(before_start): before_start() if not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) #",
":param:`mouse_support`: If True, enables mouse support for prompt_toolkit - :param:`lexer`: If True, enables",
"'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else colors.SHELL_HISTORY_CLEARED_FALSE, 'successfully' if result else 'failed', Style.RESET_ALL",
"True, enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=None, **attrs): self.isShell = isShell",
"globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline,",
"Also allows for use of custom kwargs defined in multicommand.py. \"\"\" def decorator(f):",
"if isinstance(args[0], list): _args = [args[0][0]] + list(args[1:]) for alias in args[0][1:]: if",
"@staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts the application\"\"\" # Spawns",
"def __init__(self, isShell=False, prompt=None, intro=None, hist_file=None, on_finished=None, add_command_callback: Callable[[ClickCmdShell, object, str], None] =",
"if result else 'failed', Style.RESET_ALL )) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def",
"**attrs): # Allows this class to be used as a subclass without a",
"the group. This takes the same arguments as :func:`group` but immediately registers the",
"shell within the current session by launching the python app again os.system('python \"%s\"'",
"self.name def on_shell_closed(ctx): if len(globs.__SHELL_PATH__): try: globs.__SHELL_PATH__.remove(self.name) except: pass if on_finished and callable(on_finished):",
"cls, isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator def command(self,",
"from .chars import IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand from .multicommand import CUSTOM_COMMAND_PROPS,",
"decorator def command(self, *args, **kwargs): \"\"\"Behaves the same as `click.Group.command()` except if passed",
"pretty formatting features If not attached to a shell, functions as a :class:`PrettyGroup`",
"self.isShell: BaseShellCommands.addBasics(self) if globs.__IsShell__ and self.isShell: if globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod",
"sys.argv[0].replace('\\\\', '/')) # Exits the current shell once it's child has closed globs.__IS_REPEAT__",
"not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name = None self.shell.ctx = ctx return self.shell.cmdloop()",
"= True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__) else: shell.shell._pipe_input.send_text('exit\\r') click.echo(IGNORE_LINE)",
"with all previous parameters\"\"\" if globs.__LAST_COMMAND__: globs.__IS_REPEAT__ = True if shell.shell.readline: globs.__PREV_STDIN__ =",
"[] cmd.name = alias cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h",
"globs.__MASTER_SHELL__ == self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if",
"ctx return self.shell.cmdloop() return ret else: return MultiCommand.invoke(self, ctx) def new_shell(self, cls=None, **kwargs):",
"(on a separate thread) - :param:`fuzzy_completion`: If True, use fuzzy completion for prompt_toolkit",
"new shell instance? - :param:`prompt`: Prompt Text - :param:`intro`: Shell Intro Text -",
"cmd.alias = False self.add_command(cmd) return cmd return decorator def new_shell(self, cls=None, **kwargs): \"\"\"A",
"shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed, add_command_callback=add_command_callback, before_start=on_shell_start, readline=readline, complete_while_typing=complete_while_typing, fuzzy_completion=fuzzy_completion, mouse_support=mouse_support, lexer=lexer )",
"= alias cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h = origHelpTxt)",
"a separate thread) - :param:`fuzzy_completion`: If True, use fuzzy completion for prompt_toolkit suggestions",
"features If not attached to a shell, functions as a :class:`PrettyGroup` with the",
"click.Command, name=None): name = name or cmd.name if name is None: raise TypeError(\"Command",
"= True globs.__IS_EXITING__ = True if shell.shell.readline: globs.__PREV_STDIN__ = sys.stdin sys.stdin = StringIO(globs.__LAST_COMMAND__)",
"self.isShell: ret = super(Shell, self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand: ctx.info_name =",
"cmd) super(MultiCommandShell, self).add_command(cmd) return cmd else: cmd = deepcopy(tmpCommand) cmd.alias = False cmd.aliases",
"{}{}{}'.format( colors.SHELL_HISTORY_CLEARED_STYLE, 'History cleared' if result else 'Clear History', colors.SHELL_HISTORY_CLEARED_TRUE if result else",
"cmd.aliases = aliases self.__assign_invalidKeys(old_kwargs, cmd) super(MultiCommandShell, self).add_command(cmd) return cmd return decorator class BaseShellCommands:",
"import _colors as colors from .chars import IGNORE_LINE from .pretty import PrettyGroup, PrettyCommand",
"not self.name == globs.__MASTER_SHELL__: globs.__SHELL_PATH__.append(self.name) # Create the shell self.shell = ClickCmdShell(hist_file=hist_file, on_finished=on_shell_closed,",
"isShell attrs['isShell'] = isShell if self.isShell: if not HasKey('add_command_callback', attrs) or not attrs['add_command_callback']:",
"self.name: BaseShellCommands.addMasters(self) BaseShellCommands.addAll(self) @staticmethod def __strip_invalidKeys(kwargs): for _kwarg_ in CUSTOM_COMMAND_PROPS: if HasKey(_kwarg_, kwargs):",
"return decorator class BaseShellCommands: @staticmethod def addMasters(shell: MultiCommandShell): @shell.command(globs.MASTERSHELL_COMMAND_ALIAS_RESTART, hidden=True) def __restart_shell__(): \"\"\"Restarts",
"import prettyGroup def decorator(f): cmd = prettyGroup(*args, **kwargs)(f) cmd.alias = False self.add_command(cmd) return",
"- :param:`complete_while_typing`: If True, prompt_toolkit suggestions will be live (on a separate thread)",
"mouse_support=mouse_support, lexer=lexer ) if prompt: self.shell.prompt = prompt self.shell.intro = intro else: super(Shell,",
"name, cmd, register=True) if type(name) is str: self.commands[name] = cmd else: for _name_",
"cmd.name = alias cmd.help = \"(Alias for '{c}') {h}\".format(c = _args[0], h =",
"cls else cls, isShell=True, **kwargs)(f) cmd.alias = False self.add_command(cmd) return cmd return decorator",
"for this terminal for the current user\"\"\" result = shell.shell.clear_history() print() click.echo('\\t{}{} {}{}{}'.format(",
")) @staticmethod def addAll(shell: MultiCommandShell): @shell.command(globs.SHELL_COMMAND_ALIAS_CLEAR, hidden=True) def cls(): \"\"\"Clears the Terminal\"\"\" click.clear()",
"= name or cmd.name if name is None: raise TypeError(\"Command has no name.\")",
"enables mouse support for prompt_toolkit - :param:`lexer`: If True, enables the prompt_toolkit lexer",
"self.isShell: self.shell.add_command(cmd, name) def invoke(self, ctx: click.Context): if self.isShell: ret = super(Shell, self).invoke(ctx)",
"enables the prompt_toolkit lexer \"\"\" def __init__(self, isShell=None, **attrs): self.isShell = isShell attrs['isShell']"
] |
[
"except ValueError as v: self.assertTrue( str(v) is not None ) # Assert value",
"region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert",
"# Assert that this line is reached without error def test_get_log_events(self): self.testCls.client =",
"def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this line is",
"{\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that this line",
"from unittest.mock import MagicMock from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class",
"unittest.mock import MagicMock from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase):",
"= MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\")",
"200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that this line is",
"= \"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client =",
"error\") except ValueError as v: self.assertTrue( str(v) is not None ) # Assert",
"os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client",
"MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this line is reached without error def",
"self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that this line is reached without error def",
"from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls =",
"def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [],",
"be an error\") except ValueError as v: self.assertTrue( str(v) is not None )",
"\"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that this line is reached",
"ValueError as v: self.assertTrue( str(v) is not None ) # Assert value error",
"aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this",
"this line is reached without error def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value =",
"v: self.assertTrue( str(v) is not None ) # Assert value error did happen",
"{\"HTTPStatusCode\": 500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an error\")",
"import unittest from unittest.mock import MagicMock from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import",
"UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls",
"line is reached without error def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = {",
"unittest from unittest.mock import MagicMock from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction",
"class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\"",
"TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" )",
"this line is reached without error def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value =",
"import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\"",
"reached without error def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\":",
"self.assertTrue(True) # Assert that this line is reached without error def test_get_log_events(self): self.testCls.client",
"Test Cloud Watch Log \"\"\" import os import unittest from unittest.mock import MagicMock",
"is reached without error def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\":",
"that this line is reached without error def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value",
"[], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that this line is reached without",
"is reached without error def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\":",
"<gh_stars>1-10 \"\"\" Test Cloud Watch Log \"\"\" import os import unittest from unittest.mock",
"self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) #",
"} self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that this line is reached without error",
"} try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an error\") except ValueError as v:",
"self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There",
"{ \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that",
"datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction(",
"Watch Log \"\"\" import os import unittest from unittest.mock import MagicMock from datacoco_cloud",
"log_stream=\"\") self.fail(\"There should be an error\") except ValueError as v: self.assertTrue( str(v) is",
"\"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert that this",
"# Assert that this line is reached without error def test_get_log_events_http_error(self): self.testCls.client =",
"from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY]",
"self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\")",
"Assert that this line is reached without error def test_get_log_events(self): self.testCls.client = MagicMock()",
"Assert that this line is reached without error def test_get_log_events_http_error(self): self.testCls.client = MagicMock()",
"self.fail(\"There should be an error\") except ValueError as v: self.assertTrue( str(v) is not",
"that this line is reached without error def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value",
"Log \"\"\" import os import unittest from unittest.mock import MagicMock from datacoco_cloud import",
"as v: self.assertTrue( str(v) is not None ) # Assert value error did",
"MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True)",
"self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this line is reached without error def test_get_log_events(self):",
"an error\") except ValueError as v: self.assertTrue( str(v) is not None ) #",
"\"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an error\") except ValueError",
"should be an error\") except ValueError as v: self.assertTrue( str(v) is not None",
"test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], }",
"datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] =",
"= CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True)",
"def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [],",
"self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], } try:",
"[], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an error\") except ValueError as",
"CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) #",
"self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an error\") except ValueError as v: self.assertTrue( str(v)",
"= { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.assertTrue(True) # Assert",
"error def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\":",
"without error def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500},",
"self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], } self.testCls.get_log_events(log_group=\"\",",
"test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this line is reached",
"import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction( region=\"\",",
"without error def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200},",
"500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an error\") except",
"setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self):",
"= { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should",
"self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this line is reached without",
"\"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client = MagicMock()",
"Cloud Watch Log \"\"\" import os import unittest from unittest.mock import MagicMock from",
"reached without error def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\":",
"MagicMock from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self):",
"aws_secret_key=\"\", aws_access_key=\"\" ) def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that",
"= MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this line is reached without error",
"= MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\",",
"error def test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\":",
"try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an error\") except ValueError as v: self.assertTrue(",
"\"\"\" Test Cloud Watch Log \"\"\" import os import unittest from unittest.mock import",
"\"\"\" import os import unittest from unittest.mock import MagicMock from datacoco_cloud import UNIT_TEST_KEY",
"import os import unittest from unittest.mock import MagicMock from datacoco_cloud import UNIT_TEST_KEY from",
") def test_parse_and_print_events(self): self.testCls.client = MagicMock() self.testCls.parse_and_print_events(events=\"\") self.assertTrue(True) # Assert that this line",
"\"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be an",
"def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\", aws_access_key=\"\" ) def",
"MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\")",
"log_stream=\"\") self.assertTrue(True) # Assert that this line is reached without error def test_get_log_events_http_error(self):",
"line is reached without error def test_get_log_events_http_error(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = {",
"self.assertTrue(True) # Assert that this line is reached without error def test_get_log_events_http_error(self): self.testCls.client",
"os import unittest from unittest.mock import MagicMock from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction",
"{ \"ResponseMetadata\": {\"HTTPStatusCode\": 500}, \"events\": [], } try: self.testCls.get_log_events(log_group=\"\", log_stream=\"\") self.fail(\"There should be",
"test_get_log_events(self): self.testCls.client = MagicMock() self.testCls.client.get_log_events.return_value = { \"ResponseMetadata\": {\"HTTPStatusCode\": 200}, \"events\": [], }",
"import MagicMock from datacoco_cloud import UNIT_TEST_KEY from datacoco_cloud.cwl_interaction import CWLInteraction class TestCWLInteraction(unittest.TestCase): def",
"CWLInteraction class TestCWLInteraction(unittest.TestCase): def setUp(self): os.environ[UNIT_TEST_KEY] = \"True\" self.testCls = CWLInteraction( region=\"\", aws_secret_key=\"\","
] |
[
"sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event, values = self.windowMain.read() if",
"= _to_ msg['Subject'] = _matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text =",
"values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_, _to_, _matter_, _message_): try: Select = _using_server_",
"sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))],",
"msg['From'] = _from_ msg['To'] = _to_ msg['Subject'] = _matter_ #message = input(str('Mensagem: '))",
"server.quit() print('Sucesso ao enviar o email') except: print('Ops, ocorreu um erro :(') debg",
"MIMEMultipart from email.mime.text import MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4') layout = [",
"= input(str('Assunto: ')) msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = _to_ msg['Subject']",
"msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit()",
"size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto",
"size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_',",
"enviar o email') except: print('Ops, ocorreu um erro :(') debg = Interface() debg.Home()",
"size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ]",
"smtplib import PySimpleGUI as sg from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText",
"self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event, values =",
"if event == sg.WINDOW_CLOSED: break if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'],",
"#message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando a mensagem...') #SET",
"_message_): try: Select = _using_server_ s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls()",
"server...') #email_from = input(str('De: ')) print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to =",
"'plain')) text = msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso",
"print('Configurando o server...') #email_from = input(str('De: ')) print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip())",
"mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao enviar o email') except: print('Ops,",
"import MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ', size=(8,1)),",
"[sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))],",
"sg.WINDOW_CLOSED: break if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self,",
"1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ',",
"msg['Subject'] = _matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando",
"Select = _using_server_ s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls() print('Configurando o",
"email.mime.text import MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ',",
"size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def",
"self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_, _to_, _matter_, _message_): try:",
"'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...') #email_from = input(str('De: '))",
"event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_, _to_,",
"= input(str('Para: ')) #subject = input(str('Assunto: ')) msg = MIMEMultipart() msg['From'] = _from_",
"from email.mime.text import MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor",
"import smtplib import PySimpleGUI as sg from email.mime.multipart import MIMEMultipart from email.mime.text import",
"sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem",
"self.windowMain.read() if event == sg.WINDOW_CLOSED: break if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'],",
"as sg from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Interface: def",
"values['_message_']) def configs(self, _using_server_, _from_, _to_, _matter_, _message_): try: Select = _using_server_ s",
"= sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event, values = self.windowMain.read()",
"size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain =",
"values = self.windowMain.read() if event == sg.WINDOW_CLOSED: break if event == 'Enviar': self.configs(values['_using_server_'],",
"def configs(self, _using_server_, _from_, _to_, _matter_, _message_): try: Select = _using_server_ s =",
"] self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event, values",
"sg from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Interface: def __init__(self):",
"Interface: def __init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))],",
"server = smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...') #email_from = input(str('De: ')) print('Fazendo",
"= MIMEMultipart() msg['From'] = _from_ msg['To'] = _to_ msg['Subject'] = _matter_ #message =",
"5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True:",
"= _matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando a",
"#subject = input(str('Assunto: ')) msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = _to_",
"= _from_ msg['To'] = _to_ msg['Subject'] = _matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_,",
"#SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao enviar o email') except: print('Ops, ocorreu",
"break if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_,",
"sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain",
"True: event, values = self.windowMain.read() if event == sg.WINDOW_CLOSED: break if event ==",
"<reponame>lucas-pixel/SendEmail import smtplib import PySimpleGUI as sg from email.mime.multipart import MIMEMultipart from email.mime.text",
"_from_ msg['To'] = _to_ msg['Subject'] = _matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain'))",
"sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')],",
"event, values = self.windowMain.read() if event == sg.WINDOW_CLOSED: break if event == 'Enviar':",
"#email_from = input(str('De: ')) print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para:",
"layout = [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_',",
"icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event, values = self.windowMain.read() if event == sg.WINDOW_CLOSED:",
"[sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event,",
"input(str('Para: ')) #subject = input(str('Assunto: ')) msg = MIMEMultipart() msg['From'] = _from_ msg['To']",
"email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4') layout",
"'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_, _to_, _matter_, _message_):",
"== 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_, _to_, _matter_,",
"', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0',",
"')) print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject =",
"', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_',",
"import PySimpleGUI as sg from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class",
"MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_',",
"MIMEMultipart() msg['From'] = _from_ msg['To'] = _to_ msg['Subject'] = _matter_ #message = input(str('Mensagem:",
"print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject = input(str('Assunto:",
"text) server.quit() print('Sucesso ao enviar o email') except: print('Ops, ocorreu um erro :(')",
"msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = _to_ msg['Subject'] = _matter_ #message",
"sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico')",
"server.starttls() print('Configurando o server...') #email_from = input(str('De: ')) print('Fazendo o login, aguarde...') server.login(_from_,",
"import MIMEMultipart from email.mime.text import MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4') layout =",
"sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)),",
"smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...') #email_from = input(str('De: ')) print('Fazendo o login,",
"server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject = input(str('Assunto: ')) msg = MIMEMultipart()",
"input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_,",
"class Interface: def __init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21,",
"', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_',",
"= [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))],",
"= smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...') #email_from = input(str('De: ')) print('Fazendo o",
"PySimpleGUI as sg from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Interface:",
"s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...') #email_from =",
"587) server.starttls() print('Configurando o server...') #email_from = input(str('De: ')) print('Fazendo o login, aguarde...')",
"o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject = input(str('Assunto: '))",
"[sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)),",
"', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')]",
"aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject = input(str('Assunto: ')) msg =",
"')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_, text)",
"from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Interface: def __init__(self): sg.theme('DarkPurple4')",
"[sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail",
"open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject = input(str('Assunto: ')) msg = MIMEMultipart() msg['From']",
"= input(str('De: ')) print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: '))",
"_matter_, _message_): try: Select = _using_server_ s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587)",
"layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event, values = self.windowMain.read() if event ==",
"server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao enviar o email') except: print('Ops, ocorreu um",
"_matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando a mensagem...')",
"input(str('Assunto: ')) msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = _to_ msg['Subject'] =",
"msg['To'] = _to_ msg['Subject'] = _matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text",
"_using_server_ s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...') #email_from",
"= msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao enviar",
"input(str('De: ')) print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject",
"= 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...') #email_from = input(str('De:",
"a mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao enviar o email') except:",
"ao enviar o email') except: print('Ops, ocorreu um erro :(') debg = Interface()",
"_using_server_, _from_, _to_, _matter_, _message_): try: Select = _using_server_ s = 'smtp.{}.com'.format(Select) server",
"_to_ msg['Subject'] = _matter_ #message = input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string()",
"_from_, _to_, _matter_, _message_): try: Select = _using_server_ s = 'smtp.{}.com'.format(Select) server =",
"def Home(self): while True: event, values = self.windowMain.read() if event == sg.WINDOW_CLOSED: break",
"print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao enviar o email')",
"= self.windowMain.read() if event == sg.WINDOW_CLOSED: break if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'],",
"while True: event, values = self.windowMain.read() if event == sg.WINDOW_CLOSED: break if event",
"text = msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao",
"configs(self, _using_server_, _from_, _to_, _matter_, _message_): try: Select = _using_server_ s = 'smtp.{}.com'.format(Select)",
"__init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ',",
"size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0', layout,",
"values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_, _to_, _matter_, _message_): try: Select =",
"= _using_server_ s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls() print('Configurando o server...')",
"o server...') #email_from = input(str('De: ')) print('Fazendo o login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to",
"login, aguarde...') server.login(_from_, open('senha.txt').read().strip()) #email_to = input(str('Para: ')) #subject = input(str('Assunto: ')) msg",
"= input(str('Mensagem: ')) msg.attach(MIMEText(_message_, 'plain')) text = msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_,",
"size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))],",
"try: Select = _using_server_ s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s, 587) server.starttls() print('Configurando",
"[sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while",
"if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_,",
"')) msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = _to_ msg['Subject'] = _matter_",
"[sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)),",
"_to_, text) server.quit() print('Sucesso ao enviar o email') except: print('Ops, ocorreu um erro",
"')) #subject = input(str('Assunto: ')) msg = MIMEMultipart() msg['From'] = _from_ msg['To'] =",
"[sg.Text('Logs')], [sg.Output(size=(31, 5))], [sg.Button('Enviar')] ] self.windowMain = sg.Window('SendEmail 1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self):",
"size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ', size=(8,1)), sg.Input(key='_message_', size=(21,2))], [sg.Text('Logs')], [sg.Output(size=(31,",
"msg.as_string() print('Enviando a mensagem...') #SET server.sendmail(_from_, _to_, text) server.quit() print('Sucesso ao enviar o",
"== sg.WINDOW_CLOSED: break if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def",
"size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))], [sg.Text('Mensagem ',",
"event == sg.WINDOW_CLOSED: break if event == 'Enviar': self.configs(values['_using_server_'], values['_from_'], values['_to_'], values['_matter_'], values['_message_'])",
"print('Sucesso ao enviar o email') except: print('Ops, ocorreu um erro :(') debg =",
"[sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ',",
"_to_, _matter_, _message_): try: Select = _using_server_ s = 'smtp.{}.com'.format(Select) server = smtplib.SMTP(s,",
"[ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para",
"Home(self): while True: event, values = self.windowMain.read() if event == sg.WINDOW_CLOSED: break if",
"1.0', layout, icon='Blackvariant-Shadow135-System-Mail.ico') def Home(self): while True: event, values = self.windowMain.read() if event",
"size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)), sg.Input(key='_to_', size=(21,1))], [sg.Text('Assunto ', size=(8,1)), sg.Input(key='_matter_', size=(21,1))],",
"def __init__(self): sg.theme('DarkPurple4') layout = [ [sg.Text('Servidor ', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De",
"', size=(8,1)), sg.Input(key='_using_server_', size=(21, 1))], [sg.Text('De ', size=(8,1)), sg.Input(key='_from_', size=(21,1))], [sg.Text('Para ', size=(8,1)),",
"#email_to = input(str('Para: ')) #subject = input(str('Assunto: ')) msg = MIMEMultipart() msg['From'] =",
"values['_from_'], values['_to_'], values['_matter_'], values['_message_']) def configs(self, _using_server_, _from_, _to_, _matter_, _message_): try: Select"
] |
[
"def handler(request: HttpRequest) -> HttpResponse: name = request.GET.get(\"name\") context = { \"input_name\": name,",
"render_template(TEMPLATE, context) response = HttpResponse(content=document) return response if __name__ == '__main__': x =",
"django.http import HttpRequest, HttpResponse from main.util import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request:",
"response if __name__ == '__main__': x = render_template(TEMPLATE, {'input_name': 1, 'greeting_name': 2}) print(x)",
"\"input_name\": name, \"greeting_name\": name or \"anonymous\", } document = render_template(TEMPLATE, context) response =",
"or \"anonymous\", } document = render_template(TEMPLATE, context) response = HttpResponse(content=document) return response if",
"response = HttpResponse(content=document) return response if __name__ == '__main__': x = render_template(TEMPLATE, {'input_name':",
"{ \"input_name\": name, \"greeting_name\": name or \"anonymous\", } document = render_template(TEMPLATE, context) response",
"= render_template(TEMPLATE, context) response = HttpResponse(content=document) return response if __name__ == '__main__': x",
"HttpRequest) -> HttpResponse: name = request.GET.get(\"name\") context = { \"input_name\": name, \"greeting_name\": name",
"main.util import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse: name =",
"context = { \"input_name\": name, \"greeting_name\": name or \"anonymous\", } document = render_template(TEMPLATE,",
"import HttpRequest, HttpResponse from main.util import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest)",
"import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse: name = request.GET.get(\"name\")",
"return response if __name__ == '__main__': x = render_template(TEMPLATE, {'input_name': 1, 'greeting_name': 2})",
"= HttpResponse(content=document) return response if __name__ == '__main__': x = render_template(TEMPLATE, {'input_name': 1,",
"HttpResponse(content=document) return response if __name__ == '__main__': x = render_template(TEMPLATE, {'input_name': 1, 'greeting_name':",
"document = render_template(TEMPLATE, context) response = HttpResponse(content=document) return response if __name__ == '__main__':",
"name or \"anonymous\", } document = render_template(TEMPLATE, context) response = HttpResponse(content=document) return response",
"\"greeting_name\": name or \"anonymous\", } document = render_template(TEMPLATE, context) response = HttpResponse(content=document) return",
"-> HttpResponse: name = request.GET.get(\"name\") context = { \"input_name\": name, \"greeting_name\": name or",
"handler(request: HttpRequest) -> HttpResponse: name = request.GET.get(\"name\") context = { \"input_name\": name, \"greeting_name\":",
"} document = render_template(TEMPLATE, context) response = HttpResponse(content=document) return response if __name__ ==",
"HttpResponse from main.util import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse:",
"= request.GET.get(\"name\") context = { \"input_name\": name, \"greeting_name\": name or \"anonymous\", } document",
"name, \"greeting_name\": name or \"anonymous\", } document = render_template(TEMPLATE, context) response = HttpResponse(content=document)",
"context) response = HttpResponse(content=document) return response if __name__ == '__main__': x = render_template(TEMPLATE,",
"from django.http import HttpRequest, HttpResponse from main.util import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def",
"HttpRequest, HttpResponse from main.util import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) ->",
"= \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse: name = request.GET.get(\"name\") context = {",
"request.GET.get(\"name\") context = { \"input_name\": name, \"greeting_name\": name or \"anonymous\", } document =",
"render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse: name = request.GET.get(\"name\") context",
"\"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse: name = request.GET.get(\"name\") context = { \"input_name\":",
"HttpResponse: name = request.GET.get(\"name\") context = { \"input_name\": name, \"greeting_name\": name or \"anonymous\",",
"from main.util import render_template TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse: name",
"name = request.GET.get(\"name\") context = { \"input_name\": name, \"greeting_name\": name or \"anonymous\", }",
"\"anonymous\", } document = render_template(TEMPLATE, context) response = HttpResponse(content=document) return response if __name__",
"TEMPLATE = \"tasks/lesson03/task301.html\" def handler(request: HttpRequest) -> HttpResponse: name = request.GET.get(\"name\") context =",
"= { \"input_name\": name, \"greeting_name\": name or \"anonymous\", } document = render_template(TEMPLATE, context)"
] |
[
"dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=1, workers_per_gpu=1,",
"'/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2",
"0, 0], std=[255., 255., 255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True),",
"dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data =",
"dataset settings dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 =",
"val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) ) # optimizer optimizer",
"step=[150, 180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config =",
"iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\"",
"dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [",
"test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type = 'CocoDataset'",
"model settings model = dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict(",
"**img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=1,",
"val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'],",
"warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config",
"lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same as burn-in in",
"keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[",
"policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same as burn-in",
"ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict(",
"#warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10)",
"#dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'),",
"dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations',",
"dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False,",
"multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ]",
"dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540),",
"nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type = 'CocoDataset' train_dir_1 =",
"optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy",
"= \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0],",
"dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config = dict( interval=10) workflow = [('train', 1),",
"val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3",
"std=[255., 255., 255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop',",
"[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad',",
"type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']),",
"ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) )",
"train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255.,",
"= dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True),",
"dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict(",
"\"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\"",
"val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) ) # optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9,",
"]) ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2",
"data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'],",
"nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings",
"'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline,",
"= \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.],",
"(990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize',",
"train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' #",
"val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 +",
"val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person')",
"size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug',",
"darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config =",
"), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig',",
"settings model = dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000,",
"dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2",
"\"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0,",
"dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same as burn-in in darknet #warmup_ratio=1e-6,",
"= \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 =",
"samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline,",
"ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict(",
"+ '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type,",
"0], std=[255., 255., 255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'),",
"max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type =",
"keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'),",
"lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict(",
"\"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\"",
"keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])",
"dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000,",
"model = dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms',",
") ) # optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35,",
"iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type",
") #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 =",
"classes=('pig', 'person') ) ) # optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config",
"608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32),",
"max_epochs=200) checkpoint_config = dict(interval=10) log_config = dict( interval=10) workflow = [('train', 1), ('val',",
"= 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 =",
"+ '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) ) # optimizer optimizer =",
"nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type = 'CocoDataset' train_dir_1",
"'/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1",
") runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config = dict( interval=10) workflow",
"test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize',",
"'/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1",
"180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config = dict(",
"img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) ) # optimizer optimizer = dict(type='SGD', lr=0.002,",
"#dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115, 608)],",
"dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768),",
"), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig',",
"train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 +",
"max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1",
"val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True) train_pipeline",
"flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline =",
"+ '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json',",
"[ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366,",
"type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ),",
"dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2],",
"1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)],",
"num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth'",
"img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 +",
"\"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True)",
"'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline,",
"weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing',",
"burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200)",
"learning policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same as",
"# learning policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same",
"= \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 =",
"val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0,",
"0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize',",
"img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes',",
"transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ])",
"dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor',",
"dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ]",
"train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person')",
"as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner',",
"'/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2",
"'/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) ) # optimizer",
"nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), ) #load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset",
"540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg),",
"+ '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json',",
"optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step',",
"= dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config = dict( interval=10) workflow = [('train',",
"= \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 =",
"flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])",
"img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect',",
"keys=['img']) ]) ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json',",
"policy='step', warmup='linear', warmup_iters=2000, # same as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180],",
"= \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg =",
"+ '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type,",
"warmup_iters=2000, # same as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 )",
"#dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115, 608)], keep_ratio=True,",
"(1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad',",
"pipeline=test_pipeline, classes=('pig', 'person') ) ) # optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005)",
"= \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 =",
"pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1,",
"type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') )",
"min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'),",
"= dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear',",
"dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline",
"dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type,",
"train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3",
"momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( #_delete_=True,",
"_base_ = '../yolo/yolov3_d53_mstrain-608_273e_coco.py' # model settings model = dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000,",
"= dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1,",
"test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person')",
"dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img',",
"#load_from='./checkpoints/yolov3_d53_mstrain-608_273e_coco-139f5633.pth' # dataset settings dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\"",
"dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict(",
"# optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) #",
"#_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1,",
"<reponame>leemengwei/my_mmdetection<filename>configs/fisheye_pig/yolov3_d53_mstrain-608_273e_coco_2passage_pig.py<gh_stars>1-10 _base_ = '../yolo/yolov3_d53_mstrain-608_273e_coco.py' # model settings model = dict( bbox_head=dict( num_classes=2), train_cfg=dict(",
"= dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5),",
"] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'),",
"dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 +",
"'../yolo/yolov3_d53_mstrain-608_273e_coco.py' # model settings model = dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6),",
"\"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True) train_pipeline = [",
") # optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))",
"same as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner =",
"\"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0], std=[255.,",
"# dataset settings dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2",
"val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3",
"settings dataset_type = 'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\"",
"norm_type=2)) # learning policy lr_config = dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, #",
"bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200), )",
"min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True,",
"pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1,",
"keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data",
"classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2],",
"img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ), test=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 +",
"'person') ) ) # optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config =",
"= [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize',",
"type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ),",
"size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict(",
"runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config = dict( interval=10) workflow =",
"'/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) ) # optimizer optimizer = dict(type='SGD',",
"dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config =",
"train_dir_2], pipeline=train_pipeline, classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'],",
"\"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\"",
"# model settings model = dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200),",
"= \"../dataset/4称重台-泉州safe/val\" img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True) train_pipeline =",
"train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\" val_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/val\" train_dir_3 = \"../dataset/4称重台-泉州safe/train\" val_dir_3 = \"../dataset/4称重台-泉州safe/val\" img_norm_cfg",
"#policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150,",
"255., 255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8,",
"to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990,",
"= dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config",
"768), (990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5),",
"train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3",
"dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608),",
"workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 + '/annotation_coco.json'], img_prefix=[train_dir_1, train_dir_2], pipeline=train_pipeline, classes=('pig',",
"= dict( #_delete_=True, #policy='CosineAnnealing', policy='step', warmup='linear', warmup_iters=2000, # same as burn-in in darknet",
"checkpoint_config = dict(interval=10) log_config = dict( interval=10) workflow = [('train', 1), ('val', 1)]",
"'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True),",
"+ '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2], pipeline=test_pipeline, classes=('pig', 'person') ) ) #",
"'CocoDataset' train_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\"",
"img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile',",
"= [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg),",
"\"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/train\" val_dir_1 = \"../dataset/1猪舍-汇研+剪裁ok_cat_and_dogs/val\" train_dir_2 = \"../dataset/2出猪通道-泉州safe/train\" val_dir_2 = \"../dataset/2出猪通道-泉州safe/val\" train_dir_3 = \"../dataset/3出猪台-泉州+剪裁safe/train\"",
"to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0),",
"train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7),",
"] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1 + '/annotation_coco.json', train_dir_2 +",
"classes=('pig', 'person') ), val=dict( type=dataset_type, ann_file=[val_dir_1 + '/annotation_coco.json', val_dir_2 + '/annotation_coco.json'], img_prefix=[val_dir_1, val_dir_2],",
"with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9, 1.0), min_crop_size=0.7), #dict(type='Resize', img_scale=[(1366, 768), (990, 540), (1115,",
"img_scale=[(1366, 768), (990, 540), (1115, 608)], keep_ratio=True, multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip',",
"multiscale_mode='value'), dict(type='Resize', img_scale=[(608,608)], keep_ratio=True, multiscale_mode='value'), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect',",
"optimizer optimizer = dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning",
"warmup='linear', warmup_iters=2000, # same as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10",
"**img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'),",
"= '../yolo/yolov3_d53_mstrain-608_273e_coco.py' # model settings model = dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms',",
"'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize',",
"keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=1, workers_per_gpu=1, train=dict( type=dataset_type, ann_file=[train_dir_1",
"#min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config = dict(interval=10) log_config = dict( interval=10)",
"255.], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile', to_float32=True), dict(type='LoadAnnotations', with_bbox=True), #dict(type='PhotoMetricDistortion'), #dict(type='MinIoURandomCrop', min_ious=(0.8, 0.9,",
"in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner = dict(type='EpochBasedRunner', max_epochs=200) checkpoint_config",
"# same as burn-in in darknet #warmup_ratio=1e-6, warmup_ratio=0.1, step=[150, 180], #min_lr_ratio=1e-10 ) runner",
"dict( bbox_head=dict( num_classes=2), train_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.6), max_per_img=200), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.5), max_per_img=200),",
"dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(608,608), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32),"
] |
[
"Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for camera",
"camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\") self.assertEqual(200,",
"from config import Config as cfg import requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl",
"import requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3] def",
"import unittest from config import Config as cfg import requests class Camera(unittest.TestCase): routeUrl",
"requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self):",
"class Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for",
"test_IsAllCamerasAvailable(self): for camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\") self.assertEqual(200, r.status_code) if __name__ ==",
"+ \"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for camera in self.camerasList: r =",
"routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for camera in",
"import Config as cfg import requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\"",
"Config as cfg import requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList",
"= cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for camera in self.camerasList:",
"cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for camera in self.camerasList: r",
"cfg import requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList = [1,2,3]",
"[1,2,3] def test_IsAllCamerasAvailable(self): for camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\") self.assertEqual(200, r.status_code) if",
"for camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\") self.assertEqual(200, r.status_code) if __name__ == '__main__':",
"as cfg import requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl + \"gallery/camera\" camerasList =",
"\"gallery/camera\" camerasList = [1,2,3] def test_IsAllCamerasAvailable(self): for camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\")",
"= [1,2,3] def test_IsAllCamerasAvailable(self): for camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\") self.assertEqual(200, r.status_code)",
"unittest from config import Config as cfg import requests class Camera(unittest.TestCase): routeUrl =",
"camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\") self.assertEqual(200, r.status_code) if __name__ == '__main__': unittest.main()",
"def test_IsAllCamerasAvailable(self): for camera in self.camerasList: r = requests.get(f\"{self.routeUrl}/{camera}\") self.assertEqual(200, r.status_code) if __name__",
"config import Config as cfg import requests class Camera(unittest.TestCase): routeUrl = cfg.serverUrl +"
] |
[
"to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)),",
"models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')), ], options={ 'ordering': ['-posted_on'],",
"options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post',",
"upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)),",
"related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')), ], options={ 'ordering': ['-posted_on'], }, ), ]",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], }, ),",
"# Generated by Django 3.1.3 on 2020-11-28 20:21 import core.models from django.conf import",
"[ ('core', '0003_user_profile_pic'), ] operations = [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False,",
"primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user',",
"('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[",
"dependencies = [ ('core', '0003_user_profile_pic'), ] operations = [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True,",
"('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')), ],",
"migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True,",
"('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={",
"), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4,",
"import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'),",
"name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)),",
"migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL),",
"import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'), ] operations = [",
"('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)),",
"related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True,",
"on 2020-11-28 20:21 import core.models from django.conf import settings from django.db import migrations,",
"Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'), ] operations = [ migrations.AddField( model_name='user', name='date_joined',",
"class Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'), ] operations = [ migrations.AddField( model_name='user',",
"django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies",
"uuid class Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'), ] operations = [ migrations.AddField(",
"= [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True,",
"models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [ ('core',",
"<reponame>vivek92-tech/SocialSphere-Insta-clone # Generated by Django 3.1.3 on 2020-11-28 20:21 import core.models from django.conf",
"name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),",
"field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)),",
"('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')), ], options={ 'ordering':",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')), ], options={ 'ordering': ['-posted_on'], }, ),",
"('core', '0003_user_profile_pic'), ] operations = [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ),",
"verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')),",
"editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on',",
"model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ),",
"field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post',",
"), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following',",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments',",
"models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ],",
"name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField(",
"related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[",
"serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author',",
"['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)),",
"models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')), ], options={",
"migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL),",
"from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration):",
"django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import",
"related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel(",
"to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering':",
"import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies =",
"default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following',",
"to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id',",
"'0003_user_profile_pic'), ] operations = [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField(",
"name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel(",
"import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid",
"to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment',",
"('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], },",
"[ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers',",
"], options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"import core.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion",
"models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)),",
"migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False,",
"3.1.3 on 2020-11-28 20:21 import core.models from django.conf import settings from django.db import",
"('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes',",
"by Django 3.1.3 on 2020-11-28 20:21 import core.models from django.conf import settings from",
"django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'), ]",
"models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True,",
"serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments',",
"migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [",
"'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text',",
"Django 3.1.3 on 2020-11-28 20:21 import core.models from django.conf import settings from django.db",
"20:21 import core.models from django.conf import settings from django.db import migrations, models import",
"from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone",
"models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'],",
"django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'), ] operations =",
"}, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on',",
"model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True,",
"related_name='user_following', to=settings.AUTH_USER_MODEL), ), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False,",
"primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)),",
"models.ManyToManyField(blank=True, related_name='likers', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-posted_on'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id',",
"2020-11-28 20:21 import core.models from django.conf import settings from django.db import migrations, models",
"), migrations.CreateModel( name='Post', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text',",
"('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True,",
"name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class",
"max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts', to=settings.AUTH_USER_MODEL)), ('likes', models.ManyToManyField(blank=True, related_name='likers',",
"Generated by Django 3.1.3 on 2020-11-28 20:21 import core.models from django.conf import settings",
"('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to=settings.AUTH_USER_MODEL)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='post_comments', to='core.post')), ], options={ 'ordering': ['-posted_on'], },",
"] operations = [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user',",
"preserve_default=False, ), migrations.AddField( model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True,",
"= [ ('core', '0003_user_profile_pic'), ] operations = [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),",
"import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0003_user_profile_pic'), ] operations",
"fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('photo', models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location',",
"models.ImageField(editable=False, upload_to=core.models.image_file_path)), ('text', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_posts',",
"model_name='user', name='followers', field=models.ManyToManyField(blank=True, related_name='user_followers', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(blank=True, related_name='user_following', to=settings.AUTH_USER_MODEL), ),",
"), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)),",
"migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=100)), ('posted_on', models.DateTimeField(auto_now_add=True)), ('author',",
"operations = [ migrations.AddField( model_name='user', name='date_joined', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='followers',",
"core.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion import"
] |
[
"word tokenization, remove stop words and reduce tokens into their roots\"\"\" # Tokenize",
"category \"\"\" Y_pred = model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\"",
"from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import GridSearchCV from",
"= lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\" Return a mechine learning pipeline",
"print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save the model as a pickle",
"the second argument. \\n\\nExample: python '\\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__ == '__main__':",
"column: \\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\"",
"[] for tok in tokens: clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return",
"stemer = PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens:",
"pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names =",
"load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model =",
"import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput",
"def tokenize(text): \"\"\"Clean text, apply word tokenization, remove stop words and reduce tokens",
"category_names def tokenize(text): \"\"\"Clean text, apply word tokenization, remove stop words and reduce",
"= model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" + category_names[i] +",
"import create_engine from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import",
"model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train,",
"import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import",
"df = pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"])",
"mechine learning pipeline optimized by GridSearch to classify multi-output dataset \"\"\" pipeline =",
"evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print a classification report containing recall, precision and",
"else: print('Please provide the filepath of the disaster messages database '\\ 'as the",
"param_grid=parameters, verbose=50) return cv def evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print a classification",
"import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.tree",
"\"\"\" Print a classification report containing recall, precision and f1-score for each predicted",
"reduce tokens into their roots\"\"\" # Tokenize text text = re.sub(r\"[^a-z0-9]\", \" \",",
"print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained",
"file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file: pickle.dump(model, file) def",
"Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names = Y.columns return X, Y, category_names",
"PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok =",
"model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model,",
"test_size=0.2) print('Building model...') model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model,",
"classify multi-output dataset \"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42)))",
"= re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens = word_tokenize(text) # Remove stop words tokens",
"save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the filepath of the disaster",
"'as the first argument and the filepath of the pickle file to '\\",
"re import pandas as pd import numpy as np import pickle from sqlalchemy",
"data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test =",
"RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import GridSearchCV",
"clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\" Return",
"stop words and reduce tokens into their roots\"\"\" # Tokenize text text =",
"import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline from sklearn.metrics import",
"category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...')",
"the model as a pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb')",
"from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from",
"their roots\"\"\" # Tokenize text text = re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens =",
"by GridSearch to classify multi-output dataset \"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf',",
"sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report def load_data(database_filepath):",
"import pandas as pd import numpy as np import pickle from sqlalchemy import",
"of the disaster messages database '\\ 'as the first argument and the filepath",
"WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = stemer.stem(tok).strip() clean_tok =",
"tokens: clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\"",
"create_engine from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer",
"return X, Y, category_names def tokenize(text): \"\"\"Clean text, apply word tokenization, remove stop",
"X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training",
"sqlalchemy import create_engine from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem",
"Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save the model as a pickle file",
"def load_data(database_filepath): \"\"\"Load database and split into features and outputs\"\"\" engine = create_engine('sqlite:///'",
"MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the filepath of",
"\", text.lower()) tokens = word_tokenize(text) # Remove stop words tokens = [w for",
"(1, 2)), 'clf__estimator__max_depth': [3, 6] } cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv",
"nltk.download(['punkt', 'stopwords', 'wordnet', 'averaged_perceptron_tagger']) import re import pandas as pd import numpy as",
"w in tokens if w not in stopwords.words(\"english\")] # Reduce tokens into their",
"\"original\", \"genre\"]) category_names = Y.columns return X, Y, category_names def tokenize(text): \"\"\"Clean text,",
"verbose=50) return cv def evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print a classification report",
"model as a pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as",
"from sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load database and split into features and",
"import re import pandas as pd import numpy as np import pickle from",
"\"\"\"Clean text, apply word tokenization, remove stop words and reduce tokens into their",
"as file: pickle.dump(model, file) def main(): if len(sys.argv) == 3: database_filepath, model_filepath =",
"learning pipeline optimized by GridSearch to classify multi-output dataset \"\"\" pipeline = Pipeline([",
"category_names): \"\"\" Print a classification report containing recall, precision and f1-score for each",
"Remove stop words tokens = [w for w in tokens if w not",
"in stopwords.words(\"english\")] # Reduce tokens into their roots stemer = PorterStemmer() lemmatizer =",
"disaster messages database '\\ 'as the first argument and the filepath of the",
"sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train,",
"PorterStemmer from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split",
"f1-score for each predicted category \"\"\" Y_pred = model.predict(X_test) for i in list(range(Y_pred.shape[1])):",
"import GridSearchCV from sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load database and split into",
"sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection",
"file) def main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n",
"X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)",
"stopwords.words(\"english\")] # Reduce tokens into their roots stemer = PorterStemmer() lemmatizer = WordNetLemmatizer()",
"as a pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file:",
"\"\"\" Save the model as a pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with",
"main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath))",
"the filepath of the disaster messages database '\\ 'as the first argument and",
"clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\" Return a mechine learning pipeline optimized by",
"= { 'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth': [3, 6] } cv =",
"as the second argument. \\n\\nExample: python '\\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__ ==",
"to '\\ 'save the model to as the second argument. \\n\\nExample: python '\\",
"if w not in stopwords.words(\"english\")] # Reduce tokens into their roots stemer =",
"split into features and outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\",",
"build_model(): \"\"\" Return a mechine learning pipeline optimized by GridSearch to classify multi-output",
"tokens into their roots stemer = PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens = []",
"and reduce tokens into their roots\"\"\" # Tokenize text text = re.sub(r\"[^a-z0-9]\", \"",
"text.lower()) tokens = word_tokenize(text) # Remove stop words tokens = [w for w",
"re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens = word_tokenize(text) # Remove stop words tokens =",
"features and outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X",
"words tokens = [w for w in tokens if w not in stopwords.words(\"english\")]",
"create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y = df.drop(columns=[\"id\",",
"('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range': ((1, 1), (1, 2)),",
"print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save the model as a pickle file \"\"\"",
"as np import pickle from sqlalchemy import create_engine from nltk.tokenize import word_tokenize from",
"from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from",
"stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\" Return a mechine",
"return cv def evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print a classification report containing",
"Print a classification report containing recall, precision and f1-score for each predicted category",
"for each predicted category \"\"\" Y_pred = model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report",
"Y_test, category_names): \"\"\" Print a classification report containing recall, precision and f1-score for",
"report containing recall, precision and f1-score for each predicted category \"\"\" Y_pred =",
"dataset \"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters",
"'\\ 'save the model to as the second argument. \\n\\nExample: python '\\ 'train_classifier.py",
"Y_pred = model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" + category_names[i]",
"from sqlalchemy import create_engine from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from",
"import nltk nltk.download(['punkt', 'stopwords', 'wordnet', 'averaged_perceptron_tagger']) import re import pandas as pd import",
"the disaster messages database '\\ 'as the first argument and the filepath of",
"and f1-score for each predicted category \"\"\" Y_pred = model.predict(X_test) for i in",
"print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the",
"print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n MODEL:",
"TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth':",
"list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def",
"file to '\\ 'save the model to as the second argument. \\n\\nExample: python",
"import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble",
"+ category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save the",
"model_filepath): \"\"\" Save the model as a pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\"",
"X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model()",
"multi-output dataset \"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ])",
"with open(pkl_filename, 'wb') as file: pickle.dump(model, file) def main(): if len(sys.argv) == 3:",
"filepath of the pickle file to '\\ 'save the model to as the",
"engine = create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y",
"build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n",
"{}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y,",
"first argument and the filepath of the pickle file to '\\ 'save the",
"remove stop words and reduce tokens into their roots\"\"\" # Tokenize text text",
"tokens = word_tokenize(text) # Remove stop words tokens = [w for w in",
"as pd import numpy as np import pickle from sqlalchemy import create_engine from",
"i in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i]))",
"'wb') as file: pickle.dump(model, file) def main(): if len(sys.argv) == 3: database_filepath, model_filepath",
"pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = {",
"cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def evaluate_model(model, X_test, Y_test, category_names): \"\"\"",
"df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names = Y.columns return X, Y, category_names def tokenize(text):",
"in tokens: clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model():",
"GridSearch to classify multi-output dataset \"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()),",
"roots\"\"\" # Tokenize text text = re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens = word_tokenize(text)",
"np import pickle from sqlalchemy import create_engine from nltk.tokenize import word_tokenize from nltk.corpus",
"for w in tokens if w not in stopwords.words(\"english\")] # Reduce tokens into",
"train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import",
"from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from",
"\"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save the model as a",
"stop words tokens = [w for w in tokens if w not in",
"for tok in tokens: clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens",
"\"\"\" Y_pred = model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" +",
"sys import nltk nltk.download(['punkt', 'stopwords', 'wordnet', 'averaged_perceptron_tagger']) import re import pandas as pd",
"stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline",
"category_names = Y.columns return X, Y, category_names def tokenize(text): \"\"\"Clean text, apply word",
"from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load database and",
"model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model",
"DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report",
"+ \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save the model as",
"into their roots stemer = PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens = [] for",
"model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath))",
"sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from",
"tokenization, remove stop words and reduce tokens into their roots\"\"\" # Tokenize text",
"('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range': ((1, 1),",
"('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth': [3,",
"{ 'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth': [3, 6] } cv = GridSearchCV(pipeline,",
"]) parameters = { 'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth': [3, 6] }",
"saved!') else: print('Please provide the filepath of the disaster messages database '\\ 'as",
"\"genre\"]) category_names = Y.columns return X, Y, category_names def tokenize(text): \"\"\"Clean text, apply",
"Y.columns return X, Y, category_names def tokenize(text): \"\"\"Clean text, apply word tokenization, remove",
"<gh_stars>0 import sys import nltk nltk.download(['punkt', 'stopwords', 'wordnet', 'averaged_perceptron_tagger']) import re import pandas",
"words and reduce tokens into their roots\"\"\" # Tokenize text text = re.sub(r\"[^a-z0-9]\",",
"text = re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens = word_tokenize(text) # Remove stop words",
"numpy as np import pickle from sqlalchemy import create_engine from nltk.tokenize import word_tokenize",
"print('Building model...') model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test,",
"Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath)",
"train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating",
"nltk nltk.download(['punkt', 'stopwords', 'wordnet', 'averaged_perceptron_tagger']) import re import pandas as pd import numpy",
"\\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save",
"clean_tokens = [] for tok in tokens: clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok)",
"pickle from sqlalchemy import create_engine from nltk.tokenize import word_tokenize from nltk.corpus import stopwords",
"= PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok",
"second argument. \\n\\nExample: python '\\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__ == '__main__': main()",
"\"message\", \"original\", \"genre\"]) category_names = Y.columns return X, Y, category_names def tokenize(text): \"\"\"Clean",
"model to as the second argument. \\n\\nExample: python '\\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if",
"'wordnet', 'averaged_perceptron_tagger']) import re import pandas as pd import numpy as np import",
"model saved!') else: print('Please provide the filepath of the disaster messages database '\\",
"Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...')",
"database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\",",
"\" \", text.lower()) tokens = word_tokenize(text) # Remove stop words tokens = [w",
"for i in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i],",
"import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline import",
"= WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = stemer.stem(tok).strip() clean_tok",
"model...') model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test,",
"the first argument and the filepath of the pickle file to '\\ 'save",
"recall, precision and f1-score for each predicted category \"\"\" Y_pred = model.predict(X_test) for",
"containing recall, precision and f1-score for each predicted category \"\"\" Y_pred = model.predict(X_test)",
"into their roots\"\"\" # Tokenize text text = re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens",
"import pickle from sqlalchemy import create_engine from nltk.tokenize import word_tokenize from nltk.corpus import",
"nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter",
"import PorterStemmer from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix from sklearn.model_selection import",
"X_test, Y_test, category_names): \"\"\" Print a classification report containing recall, precision and f1-score",
"import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import",
"pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file: pickle.dump(model, file) def main(): if",
"for column: \\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath):",
"\"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters =",
"sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier from",
"len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y,",
"sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load database and split",
"tokens if w not in stopwords.words(\"english\")] # Reduce tokens into their roots stemer",
"= Y.columns return X, Y, category_names def tokenize(text): \"\"\"Clean text, apply word tokenization,",
"model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names)",
"def evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print a classification report containing recall, precision",
"MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth': [3, 6]",
"# Tokenize text text = re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens = word_tokenize(text) #",
"X, Y, category_names def tokenize(text): \"\"\"Clean text, apply word tokenization, remove stop words",
"database '\\ 'as the first argument and the filepath of the pickle file",
"import numpy as np import pickle from sqlalchemy import create_engine from nltk.tokenize import",
"= \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file: pickle.dump(model, file) def main(): if len(sys.argv)",
"+ database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y = df.drop(columns=[\"id\", \"message\",",
"[w for w in tokens if w not in stopwords.words(\"english\")] # Reduce tokens",
"and the filepath of the pickle file to '\\ 'save the model to",
"= [] for tok in tokens: clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok)",
"from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline from",
"model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the filepath",
"a pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file: pickle.dump(model,",
"= df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names = Y.columns return X, Y, category_names def",
"database and split into features and outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath) df",
"each predicted category \"\"\" Y_pred = model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report for",
"nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix from sklearn.model_selection",
"print(\"Report for column: \\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model,",
"lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\" Return a mechine learning pipeline optimized",
"= create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y =",
"Reduce tokens into their roots stemer = PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens =",
"the filepath of the pickle file to '\\ 'save the model to as",
"print('Please provide the filepath of the disaster messages database '\\ 'as the first",
"and outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X =",
"text text = re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens = word_tokenize(text) # Remove stop",
"argument and the filepath of the pickle file to '\\ 'save the model",
"X_test, Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else:",
"the pickle file to '\\ 'save the model to as the second argument.",
"X = df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names = Y.columns return",
"WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix",
"from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier",
"nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline from sklearn.metrics",
"= df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names = Y.columns return X,",
"Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please",
"classification_report def load_data(database_filepath): \"\"\"Load database and split into features and outputs\"\"\" engine =",
"from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier",
"in tokens if w not in stopwords.words(\"english\")] # Reduce tokens into their roots",
"1), (1, 2)), 'clf__estimator__max_depth': [3, 6] } cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return",
"Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range': ((1,",
"roots stemer = PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in",
"'\\ 'as the first argument and the filepath of the pickle file to",
"and split into features and outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath) df =",
"return clean_tokens def build_model(): \"\"\" Return a mechine learning pipeline optimized by GridSearch",
"save_model(model, model_filepath): \"\"\" Save the model as a pickle file \"\"\" pkl_filename =",
"= Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range':",
"evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!')",
"= [w for w in tokens if w not in stopwords.words(\"english\")] # Reduce",
"import MultiOutputClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load",
"sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics",
"Y, category_names def tokenize(text): \"\"\"Clean text, apply word tokenization, remove stop words and",
"'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth': [3, 6] } cv = GridSearchCV(pipeline, param_grid=parameters,",
"tok in tokens: clean_tok = stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def",
"\"\"\" Return a mechine learning pipeline optimized by GridSearch to classify multi-output dataset",
"= train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...') model.fit(X_train, Y_train)",
"pipeline optimized by GridSearch to classify multi-output dataset \"\"\" pipeline = Pipeline([ ('vect',",
"optimized by GridSearch to classify multi-output dataset \"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)),",
"provide the filepath of the disaster messages database '\\ 'as the first argument",
"messages database '\\ 'as the first argument and the filepath of the pickle",
"Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building",
"pickle.dump(model, file) def main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading",
"from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from",
"def save_model(model, model_filepath): \"\"\" Save the model as a pickle file \"\"\" pkl_filename",
"= build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving",
"a classification report containing recall, precision and f1-score for each predicted category \"\"\"",
"from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer",
"predicted category \"\"\" Y_pred = model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report for column:",
"to classify multi-output dataset \"\"\" pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf',",
"tokens = [w for w in tokens if w not in stopwords.words(\"english\")] #",
"parameters = { 'vect__ngram_range': ((1, 1), (1, 2)), 'clf__estimator__max_depth': [3, 6] } cv",
"the model to as the second argument. \\n\\nExample: python '\\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl')",
"((1, 1), (1, 2)), 'clf__estimator__max_depth': [3, 6] } cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50)",
"'averaged_perceptron_tagger']) import re import pandas as pd import numpy as np import pickle",
"Tokenize text text = re.sub(r\"[^a-z0-9]\", \" \", text.lower()) tokens = word_tokenize(text) # Remove",
"{}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the filepath of the",
"a mechine learning pipeline optimized by GridSearch to classify multi-output dataset \"\"\" pipeline",
"import classification_report def load_data(database_filepath): \"\"\"Load database and split into features and outputs\"\"\" engine",
"# Remove stop words tokens = [w for w in tokens if w",
"category_names) print('Saving model...\\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide",
"pickle file to '\\ 'save the model to as the second argument. \\n\\nExample:",
"TfidfTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import MultiOutputClassifier",
"w not in stopwords.words(\"english\")] # Reduce tokens into their roots stemer = PorterStemmer()",
"sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from",
"print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test",
"6] } cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def evaluate_model(model, X_test, Y_test,",
"def build_model(): \"\"\" Return a mechine learning pipeline optimized by GridSearch to classify",
"precision and f1-score for each predicted category \"\"\" Y_pred = model.predict(X_test) for i",
"word_tokenize(text) # Remove stop words tokens = [w for w in tokens if",
"print('Trained model saved!') else: print('Please provide the filepath of the disaster messages database",
"file: pickle.dump(model, file) def main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:]",
"MultiOutputClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load database",
"to as the second argument. \\n\\nExample: python '\\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__",
"= sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test,",
"GridSearchCV from sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load database and split into features",
"text, apply word tokenization, remove stop words and reduce tokens into their roots\"\"\"",
"\"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file: pickle.dump(model, file) def main():",
"if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X,",
"open(pkl_filename, 'wb') as file: pickle.dump(model, file) def main(): if len(sys.argv) == 3: database_filepath,",
"import sys import nltk nltk.download(['punkt', 'stopwords', 'wordnet', 'averaged_perceptron_tagger']) import re import pandas as",
"engine) X = df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names = Y.columns",
"3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names =",
"confusion_matrix from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import",
"= pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names",
"sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text",
"apply word tokenization, remove stop words and reduce tokens into their roots\"\"\" #",
"category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\") def save_model(model, model_filepath): \"\"\" Save the model",
"= GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print",
"Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...')",
"[3, 6] } cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def evaluate_model(model, X_test,",
"# Reduce tokens into their roots stemer = PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens",
"word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer",
"pandas as pd import numpy as np import pickle from sqlalchemy import create_engine",
"sklearn.metrics import classification_report def load_data(database_filepath): \"\"\"Load database and split into features and outputs\"\"\"",
"CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(DecisionTreeClassifier(random_state=42))) ]) parameters = { 'vect__ngram_range': ((1, 1), (1,",
"not in stopwords.words(\"english\")] # Reduce tokens into their roots stemer = PorterStemmer() lemmatizer",
"CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.multioutput import",
"clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\" Return a mechine learning",
"Return a mechine learning pipeline optimized by GridSearch to classify multi-output dataset \"\"\"",
"\"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file: pickle.dump(model, file) def main(): if len(sys.argv) ==",
"cv def evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print a classification report containing recall,",
"\"\"\"Load database and split into features and outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath)",
"2)), 'clf__estimator__max_depth': [3, 6] } cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def",
"from nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix from",
"== 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names",
"= word_tokenize(text) # Remove stop words tokens = [w for w in tokens",
"model.predict(X_test) for i in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" + category_names[i] + \"\\\"\")",
"DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X,",
"classification report containing recall, precision and f1-score for each predicted category \"\"\" Y_pred",
"GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def evaluate_model(model, X_test, Y_test, category_names): \"\"\" Print a",
"in list(range(Y_pred.shape[1])): print(\"Report for column: \\\"\" + category_names[i] + \"\\\"\") print(classification_report(Y_test.values[:,i], Y_pred[:,i])) print(\"\\n\\n\")",
"'clf__estimator__max_depth': [3, 6] } cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def evaluate_model(model,",
"Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...') model.fit(X_train,",
"'save the model to as the second argument. \\n\\nExample: python '\\ 'train_classifier.py ../data/DisasterResponse.db",
"pd import numpy as np import pickle from sqlalchemy import create_engine from nltk.tokenize",
"model_filepath) print('Trained model saved!') else: print('Please provide the filepath of the disaster messages",
"their roots stemer = PorterStemmer() lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok",
"pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename, 'wb') as file: pickle.dump(model, file)",
"Save the model as a pickle file \"\"\" pkl_filename = \"disaster_response_model.pkl\" with open(pkl_filename,",
"'stopwords', 'wordnet', 'averaged_perceptron_tagger']) import re import pandas as pd import numpy as np",
"of the pickle file to '\\ 'save the model to as the second",
"df[\"message\"] Y = df.drop(columns=[\"id\", \"message\", \"original\", \"genre\"]) category_names = Y.columns return X, Y,",
"database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath)",
"tokenize(text): \"\"\"Clean text, apply word tokenization, remove stop words and reduce tokens into",
"Pipeline from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer,",
"tokens into their roots\"\"\" # Tokenize text text = re.sub(r\"[^a-z0-9]\", \" \", text.lower())",
"lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = stemer.stem(tok).strip()",
"def main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\\n DATABASE:",
"into features and outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine)",
"import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import",
"} cv = GridSearchCV(pipeline, param_grid=parameters, verbose=50) return cv def evaluate_model(model, X_test, Y_test, category_names):",
"import Pipeline from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import",
"clean_tokens def build_model(): \"\"\" Return a mechine learning pipeline optimized by GridSearch to",
"filepath of the disaster messages database '\\ 'as the first argument and the",
"from sklearn.multioutput import MultiOutputClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report def",
"= load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model",
"load_data(database_filepath): \"\"\"Load database and split into features and outputs\"\"\" engine = create_engine('sqlite:///' +",
"nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline",
"= stemer.stem(tok).strip() clean_tok = lemmatizer.lemmatize(clean_tok) clean_tokens.append(clean_tok) return clean_tokens def build_model(): \"\"\" Return a",
"outputs\"\"\" engine = create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table(\"DisasterResponse\", engine) X = df[\"message\"]"
] |
[
"<reponame>uniaim-event-team/watch-link from flask import Blueprint, render_template app = Blueprint(__name__, \"server\") @app.route('/') def route():",
"flask import Blueprint, render_template app = Blueprint(__name__, \"server\") @app.route('/') def route(): return render_template('top.html')",
"from flask import Blueprint, render_template app = Blueprint(__name__, \"server\") @app.route('/') def route(): return"
] |
[
"e) print(\"\\t\", f) print(\"Multiplying both and storing in new: \", x.multiply(e, f, e))",
"and storing in new: \", x.multiply(e, f, e)) print(\"Checking only first encoding changes:",
"\", x.get_lambda()) e = x.sample() print(\"Sample 1:\", e) f = print(\"Sample 2: \",",
"print(\"Checking encodings haven't changed: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both and storing",
"f) print(\"Multiplying both and storing in new: \", x.multiply(e, f, e)) print(\"Checking only",
"\") print(\"\\t\", e) print(\"\\t\", f) print(\"Length of key from first:\", len(x.extract(e))) print(\"Length of",
"not changed: \", f) print(\"Multiplying both and returning new: \", x.multiply(e, f)) print(\"Checking",
"at level 1\", e) f = x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2, e)",
"2: \", e) print(\"Checking copy has not changed: \", f) print(\"Multiplying both and",
"encoding at level 2: \", e) print(\"Checking copy has not changed: \", f)",
"trivial_ges import TrivialGES import sys # Testing l = int(sys.argv[1]) n = int(sys.argv[2])",
"both and returning new: \", x.multiply(e, f)) print(\"Checking encodings haven't changed: \") print(\"\\t\",",
"level 1\", e) f = x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing",
"new: \", x.multiply(e, f)) print(\"Checking encodings haven't changed: \") print(\"\\t\", e) print(\"\\t\", f)",
"of key from first:\", len(x.extract(e))) print(\"Length of key from second:\", len(x.extract(f))) print(\"First two",
"x.get_lambda()) e = x.sample() print(\"Sample 1:\", e) f = print(\"Sample 2: \", x.sample())",
"at level 2: \", e) print(\"Checking copy has not changed: \", f) print(\"Multiplying",
"lambda = \", l, \" n = \", n) x = TrivialGES(l, n)",
"print(\"\\t\", f) print(\"Multiplying both and storing in new: \", x.multiply(e, f, e)) print(\"Checking",
"= \", l, \" n = \", n) x = TrivialGES(l, n) print(\"n:",
"n = int(sys.argv[2]) print(\"Instantiating with lambda = \", l, \" n = \",",
"first sample at level 1\", e) f = x.copy_encoding(e) print(\"Copying encoding: \", f)",
"sys # Testing l = int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with lambda =",
"print(\"\\t\", f) print(\"Length of key from first:\", len(x.extract(e))) print(\"Length of key from second:\",",
"\", e) print(\"Checking copy has not changed: \", f) print(\"Multiplying both and returning",
"key from second:\", len(x.extract(f))) print(\"First two keys are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First",
"two keys are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key and key of",
"storing in new: \", x.multiply(e, f, e)) print(\"Checking only first encoding changes: \")",
"first:\", len(x.extract(e))) print(\"Length of key from second:\", len(x.extract(f))) print(\"First two keys are equal:\",",
"x.get_n()) print(\"lambda: \", x.get_lambda()) e = x.sample() print(\"Sample 1:\", e) f = print(\"Sample",
"in new: \", x.multiply(e, f, e)) print(\"Checking only first encoding changes: \") print(\"\\t\",",
"int(sys.argv[2]) print(\"Instantiating with lambda = \", l, \" n = \", n) x",
"print(\"Sample 3: \", x.sample()) f = print(\"Sample 4: \", x.sample()) e = x.encode(1,",
"\", x.sample()) f = print(\"Sample 3: \", x.sample()) f = print(\"Sample 4: \",",
"equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key and key of copy are equal:\",",
"changed: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both and storing in new: \",",
"second:\", len(x.extract(f))) print(\"First two keys are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key",
"first encoding at level 2: \", e) print(\"Checking copy has not changed: \",",
"are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key and key of copy are",
"x.multiply(e, f)) print(\"Checking encodings haven't changed: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both",
"key from first:\", len(x.extract(e))) print(\"Length of key from second:\", len(x.extract(f))) print(\"First two keys",
"int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with lambda = \", l, \" n =",
"<reponame>stevenengler/witness-encryption from trivial_ges import TrivialGES import sys # Testing l = int(sys.argv[1]) n",
"1\", e) f = x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing first",
"1:\", e) f = print(\"Sample 2: \", x.sample()) f = print(\"Sample 3: \",",
"TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda()) e = x.sample() print(\"Sample 1:\",",
"\" n = \", n) x = TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda:",
"x.sample()) f = print(\"Sample 4: \", x.sample()) e = x.encode(1, e) print(\"Encoding first",
"print(\"Copying encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing first encoding at level 2: \",",
"x.sample()) f = print(\"Sample 3: \", x.sample()) f = print(\"Sample 4: \", x.sample())",
"= int(sys.argv[2]) print(\"Instantiating with lambda = \", l, \" n = \", n)",
"len(x.extract(f))) print(\"First two keys are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key and",
"has not changed: \", f) print(\"Multiplying both and returning new: \", x.multiply(e, f))",
"print(\"Checking only first encoding changes: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Length of key",
"x.sample()) e = x.encode(1, e) print(\"Encoding first sample at level 1\", e) f",
"e)) print(\"Checking only first encoding changes: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Length of",
"\") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both and storing in new: \", x.multiply(e,",
"f) print(\"Length of key from first:\", len(x.extract(e))) print(\"Length of key from second:\", len(x.extract(f)))",
"x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing first encoding at level 2:",
"\", x.get_n()) print(\"lambda: \", x.get_lambda()) e = x.sample() print(\"Sample 1:\", e) f =",
"3: \", x.sample()) f = print(\"Sample 4: \", x.sample()) e = x.encode(1, e)",
"e) print(\"Checking copy has not changed: \", f) print(\"Multiplying both and returning new:",
"e) print(\"Encoding first sample at level 1\", e) f = x.copy_encoding(e) print(\"Copying encoding:",
"changes: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Length of key from first:\", len(x.extract(e))) print(\"Length",
"copy has not changed: \", f) print(\"Multiplying both and returning new: \", x.multiply(e,",
"from first:\", len(x.extract(e))) print(\"Length of key from second:\", len(x.extract(f))) print(\"First two keys are",
"= x.sample() print(\"Sample 1:\", e) f = print(\"Sample 2: \", x.sample()) f =",
"with lambda = \", l, \" n = \", n) x = TrivialGES(l,",
"Testing l = int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with lambda = \", l,",
"changed: \", f) print(\"Multiplying both and returning new: \", x.multiply(e, f)) print(\"Checking encodings",
"print(\"First two keys are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key and key",
"both and storing in new: \", x.multiply(e, f, e)) print(\"Checking only first encoding",
"x.sample() print(\"Sample 1:\", e) f = print(\"Sample 2: \", x.sample()) f = print(\"Sample",
"print(\"Instantiating with lambda = \", l, \" n = \", n) x =",
"print(\"Length of key from first:\", len(x.extract(e))) print(\"Length of key from second:\", len(x.extract(f))) print(\"First",
"haven't changed: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both and storing in new:",
"import sys # Testing l = int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with lambda",
"n = \", n) x = TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda: \",",
"sample at level 1\", e) f = x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2,",
"encoding changes: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Length of key from first:\", len(x.extract(e)))",
"returning new: \", x.multiply(e, f)) print(\"Checking encodings haven't changed: \") print(\"\\t\", e) print(\"\\t\",",
"4: \", x.sample()) e = x.encode(1, e) print(\"Encoding first sample at level 1\",",
"= \", n) x = TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda())",
"keys are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key and key of copy",
"\", x.multiply(e, f)) print(\"Checking encodings haven't changed: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying",
"str(x.extract(f))) print(\"First encoding key and key of copy are equal:\", str(x.extract(e)) == str(x.extract(x.copy_encoding(e))))",
"of key from second:\", len(x.extract(f))) print(\"First two keys are equal:\", str(x.extract(e)) == str(x.extract(f)))",
"f = x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing first encoding at",
"and returning new: \", x.multiply(e, f)) print(\"Checking encodings haven't changed: \") print(\"\\t\", e)",
"print(\"Rerandomizing first encoding at level 2: \", e) print(\"Checking copy has not changed:",
"print(\"Checking copy has not changed: \", f) print(\"Multiplying both and returning new: \",",
"= TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda()) e = x.sample() print(\"Sample",
"= print(\"Sample 2: \", x.sample()) f = print(\"Sample 3: \", x.sample()) f =",
"f = print(\"Sample 2: \", x.sample()) f = print(\"Sample 3: \", x.sample()) f",
"= print(\"Sample 4: \", x.sample()) e = x.encode(1, e) print(\"Encoding first sample at",
"= x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing first encoding at level",
"e) f = print(\"Sample 2: \", x.sample()) f = print(\"Sample 3: \", x.sample())",
"len(x.extract(e))) print(\"Length of key from second:\", len(x.extract(f))) print(\"First two keys are equal:\", str(x.extract(e))",
"print(\"Multiplying both and returning new: \", x.multiply(e, f)) print(\"Checking encodings haven't changed: \")",
"only first encoding changes: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Length of key from",
"x.rerandomize(2, e) print(\"Rerandomizing first encoding at level 2: \", e) print(\"Checking copy has",
"first encoding changes: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Length of key from first:\",",
"e) print(\"Rerandomizing first encoding at level 2: \", e) print(\"Checking copy has not",
"f, e)) print(\"Checking only first encoding changes: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Length",
"f = print(\"Sample 3: \", x.sample()) f = print(\"Sample 4: \", x.sample()) e",
"e = x.sample() print(\"Sample 1:\", e) f = print(\"Sample 2: \", x.sample()) f",
"encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing first encoding at level 2: \", e)",
"== str(x.extract(f))) print(\"First encoding key and key of copy are equal:\", str(x.extract(e)) ==",
"\", f) x.rerandomize(2, e) print(\"Rerandomizing first encoding at level 2: \", e) print(\"Checking",
"= int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with lambda = \", l, \" n",
"f)) print(\"Checking encodings haven't changed: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both and",
"# Testing l = int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with lambda = \",",
"f) x.rerandomize(2, e) print(\"Rerandomizing first encoding at level 2: \", e) print(\"Checking copy",
"from second:\", len(x.extract(f))) print(\"First two keys are equal:\", str(x.extract(e)) == str(x.extract(f))) print(\"First encoding",
"print(\"Encoding first sample at level 1\", e) f = x.copy_encoding(e) print(\"Copying encoding: \",",
"n) print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda()) e = x.sample() print(\"Sample 1:\", e)",
"str(x.extract(e)) == str(x.extract(f))) print(\"First encoding key and key of copy are equal:\", str(x.extract(e))",
"print(\"Sample 1:\", e) f = print(\"Sample 2: \", x.sample()) f = print(\"Sample 3:",
"f = print(\"Sample 4: \", x.sample()) e = x.encode(1, e) print(\"Encoding first sample",
"level 2: \", e) print(\"Checking copy has not changed: \", f) print(\"Multiplying both",
"x.multiply(e, f, e)) print(\"Checking only first encoding changes: \") print(\"\\t\", e) print(\"\\t\", f)",
"print(\"Length of key from second:\", len(x.extract(f))) print(\"First two keys are equal:\", str(x.extract(e)) ==",
"= x.encode(1, e) print(\"Encoding first sample at level 1\", e) f = x.copy_encoding(e)",
"= print(\"Sample 3: \", x.sample()) f = print(\"Sample 4: \", x.sample()) e =",
"\", n) x = TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda()) e",
"print(\"Multiplying both and storing in new: \", x.multiply(e, f, e)) print(\"Checking only first",
"new: \", x.multiply(e, f, e)) print(\"Checking only first encoding changes: \") print(\"\\t\", e)",
"\", x.multiply(e, f, e)) print(\"Checking only first encoding changes: \") print(\"\\t\", e) print(\"\\t\",",
"print(\"Sample 2: \", x.sample()) f = print(\"Sample 3: \", x.sample()) f = print(\"Sample",
"print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda()) e = x.sample() print(\"Sample 1:\", e) f",
"f) print(\"Multiplying both and returning new: \", x.multiply(e, f)) print(\"Checking encodings haven't changed:",
"print(\"lambda: \", x.get_lambda()) e = x.sample() print(\"Sample 1:\", e) f = print(\"Sample 2:",
"n) x = TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda()) e =",
"2: \", x.sample()) f = print(\"Sample 3: \", x.sample()) f = print(\"Sample 4:",
"\", x.sample()) e = x.encode(1, e) print(\"Encoding first sample at level 1\", e)",
"x.encode(1, e) print(\"Encoding first sample at level 1\", e) f = x.copy_encoding(e) print(\"Copying",
"\", f) print(\"Multiplying both and returning new: \", x.multiply(e, f)) print(\"Checking encodings haven't",
"from trivial_ges import TrivialGES import sys # Testing l = int(sys.argv[1]) n =",
"\", l, \" n = \", n) x = TrivialGES(l, n) print(\"n: \",",
"e = x.encode(1, e) print(\"Encoding first sample at level 1\", e) f =",
"x = TrivialGES(l, n) print(\"n: \", x.get_n()) print(\"lambda: \", x.get_lambda()) e = x.sample()",
"TrivialGES import sys # Testing l = int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with",
"print(\"\\t\", e) print(\"\\t\", f) print(\"Length of key from first:\", len(x.extract(e))) print(\"Length of key",
"encodings haven't changed: \") print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both and storing in",
"e) print(\"\\t\", f) print(\"Length of key from first:\", len(x.extract(e))) print(\"Length of key from",
"print(\"\\t\", e) print(\"\\t\", f) print(\"Multiplying both and storing in new: \", x.multiply(e, f,",
"l, \" n = \", n) x = TrivialGES(l, n) print(\"n: \", x.get_n())",
"import TrivialGES import sys # Testing l = int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating",
"\", x.sample()) f = print(\"Sample 4: \", x.sample()) e = x.encode(1, e) print(\"Encoding",
"e) f = x.copy_encoding(e) print(\"Copying encoding: \", f) x.rerandomize(2, e) print(\"Rerandomizing first encoding",
"l = int(sys.argv[1]) n = int(sys.argv[2]) print(\"Instantiating with lambda = \", l, \"",
"print(\"Sample 4: \", x.sample()) e = x.encode(1, e) print(\"Encoding first sample at level"
] |
[
"market minute after @start. This is either the immediate next minute, the open",
"# then return the open of the *next* trading day. return next_open_and_close_hook(start)[0] def",
"end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution minutes for the",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"1: return next_scheduled_day_hook(date) if n == -1: return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days)",
"# ExchangeCalendar and TradingSchedule classes. # These methods live in the helpers module",
"the # ExchangeCalendar and TradingSchedule classes. # These methods live in the helpers",
"raise NoFurtherDataError(msg='Cannot find previous day before %s' % date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook):",
"day if @start is after the close on a trading day, or the",
"NoFurtherDataError(msg='Cannot find previous day before %s' % date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return",
"def normalize_date(date): date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a",
"and end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)]",
"[] for day in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all",
"of the trading calendar, a NoFurtherDataError is raised. Parameters ---------- n : int",
"If start is not in a trading day, or is after the market",
"language governing permissions and # limitations under the License. import pandas as pd",
"i == len(all_days): # nothing found return None j = bisect.bisect_left(all_days, second_date) if",
"minutes and truncate minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n,",
"is before the market open # then return the close of the *previous*",
"start < market_close: return start + pd.Timedelta(minutes=1) # If start is not in",
"day if the given dt is not in the trading calendar. \"\"\" ndt",
"this file except in compliance with the License. # You may obtain a",
"in the calendar after the provided date. Parameters ---------- date : Timestamp The",
"return None distance = j - 1 assert distance >= 0 return distance",
"< 0 or idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d days to",
"+ pd.Timedelta(minutes=1) # If start is not in a trading day, or is",
"open_and_close_hook(day) return pd.date_range(start, end, freq='T') def days_in_range(start, end, all_days): \"\"\" Get all execution",
"normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if i == len(all_days): # nothing found return",
"= open_and_close_hook(day) return pd.date_range(start, end, freq='T') def days_in_range(start, end, all_days): \"\"\" Get all",
"import numpy as np import bisect from zipline.errors import NoFurtherDataError def normalize_date(date): date",
"raised. Parameters ---------- n : int The number of days to add to",
"idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d days to %s' % (n,",
"days to add to date, this can be positive or negative. date :",
"if start > market_open: return start - pd.Timedelta(minutes=1) # If start is not",
"of the given @dt, or the index of the preceding trading day if",
"date before the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=-1) while",
"end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes and truncate minutes before",
"market open # then return the close of the *previous* trading day. return",
"ANY KIND, either express or implied. # See the License for the specific",
"pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\" Return the index of",
"module to avoid code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next",
"market_close # If start is during trading hours, then get previous minute. if",
"= pd.Timedelta(days=-1) while first_trading_day < dt: dt += delta if is_scheduled_day_hook(dt): return dt",
"\"\"\" Convert a datetime.time into a timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second,",
"a datetime.time into a timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def",
">= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d days to %s' % (n, date)",
"previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous session date in the calendar before",
"-1: return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) + n if idx < 0",
"if start > market_close: return market_close # If start is during trading hours,",
"else: return all_trading_days.searchsorted(ndt) - 1 # The following methods are intended to be",
"in a trading day, or is after the market close # then return",
"previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading days to date. If this would fall",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"minutes for the days between start and end, inclusive. \"\"\" start_date = normalize_date(start)",
"def minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day) return pd.date_range(start, end, freq='T') def days_in_range(start,",
"preceding trading day if the given dt is not in the trading calendar.",
"The previous scheduled date before the provided date. \"\"\" dt = normalize_date(date) delta",
"> market_open: return start - pd.Timedelta(minutes=1) # If start is not a trading",
"negative. date : datetime The date to add to. Returns ------- datetime n",
"the market open on a trading day, or the open of the next",
"next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days):",
"end = open_and_close_hook(day) return pd.date_range(start, end, freq='T') def days_in_range(start, end, all_days): \"\"\" Get",
"open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next market minute after @start. This is either",
"open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date,",
"\"\"\" start_date = normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end,",
"return market_close # If start is during trading hours, then get previous minute.",
"# If start before market open on a trading day, return market open.",
"scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date) second_date = normalize_date(second_date) i = bisect.bisect_left(all_days, first_date)",
"next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next market minute after @start. This",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"date is needed. Returns ------- Timestamp The previous scheduled date before the provided",
"---------- date : Timestamp The date whose following date is needed. Returns -------",
"date is needed. Returns ------- Timestamp The next scheduled date after the provided",
"raise NoFurtherDataError( msg='Cannot add %d days to %s' % (n, date) ) return",
"start after the market close, return market close. if start > market_close: return",
"n : int The number of days to add to date, this can",
"helpers module to avoid code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the",
"return all_trading_days.searchsorted(ndt) - 1 # The following methods are intended to be inserted",
"OF ANY KIND, either express or implied. # See the License for the",
"NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert",
"add %d days to %s' % (n, date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days,",
"n trading days to date. If this would fall outside of the trading",
"date in the calendar after the provided date. Parameters ---------- date : Timestamp",
"if @start is after the close on a trading day, or the close",
"minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook,",
"all_trading_days) + n if idx < 0 or idx >= len(all_trading_days): raise NoFurtherDataError(",
"trading day, return market open. if start < market_open: return market_open # If",
"all_minutes = [] for day in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) #",
"this would fall outside of the trading calendar, a NoFurtherDataError is raised. Parameters",
"open_and_close_hook): start, end = open_and_close_hook(day) return pd.date_range(start, end, freq='T') def days_in_range(start, end, all_days):",
"= normalize_date(end) all_minutes = [] for day in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day)",
"is during trading hours, then get previous minute. if start > market_open: return",
"open of the *next* trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook):",
"TradingSchedule classes. # These methods live in the helpers module to avoid code",
"date : Timestamp The date whose following date is needed. Returns ------- Timestamp",
"pd import numpy as np import bisect from zipline.errors import NoFurtherDataError def normalize_date(date):",
"date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=1) while dt <= last_trading_day: dt",
"def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading days to date.",
"to. Returns ------- datetime n trading days added to date. \"\"\" if n",
"to %s' % (n, date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day =",
"return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1 # The following methods are intended",
"the open of the same day if @start is before the market open",
"day, or is after the market close # then return the open of",
"all execution minutes for the days between start and end, inclusive. \"\"\" start_date",
": datetime The date to add to. Returns ------- datetime n trading days",
"of the preceding trading day if the given dt is not in the",
"then return the open of the *next* trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start,",
"day before @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start",
"= pd.Timedelta(days=1) while dt <= last_trading_day: dt += delta if is_scheduled_day_hook(dt): return dt",
"normalize_date(date): date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a datetime.time",
"Returns ------- datetime n trading days added to date. \"\"\" if n ==",
"the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=1) while dt <=",
"in the helpers module to avoid code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\"",
"is either the immediate previous minute, the close of the same day if",
"previous day before %s' % date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def",
"to date. \"\"\" if n == 1: return next_scheduled_day_hook(date) if n == -1:",
"% date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous session date in",
"# Copyright 2016 Quantopian, Inc. # # Licensed under the Apache License, Version",
"j - 1 assert distance >= 0 return distance def minutes_for_day(day, open_and_close_hook): start,",
"= all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the",
"is not in the trading calendar. \"\"\" ndt = normalize_date(dt) if ndt in",
"return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date) second_date = normalize_date(second_date) i",
"close. if start > market_close: return market_close # If start is during trading",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"the trading calendar, a NoFurtherDataError is raised. Parameters ---------- n : int The",
"the next market minute before @start. This is either the immediate previous minute,",
": Timestamp The date whose following date is needed. Returns ------- Timestamp The",
"pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a datetime.time into a timedelta. \"\"\" return pd.Timedelta(",
"n == -1: return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) + n if idx",
"= j - 1 assert distance >= 0 return distance def minutes_for_day(day, open_and_close_hook):",
"permissions and # limitations under the License. import pandas as pd import numpy",
"following methods are intended to be inserted in both the # ExchangeCalendar and",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading days to date. If this would",
"given dt is not in the trading calendar. \"\"\" ndt = normalize_date(dt) if",
"open on a trading day, or the open of the next market day",
"date : Timestamp The date whose previous date is needed. Returns ------- Timestamp",
"datetime The date to add to. Returns ------- datetime n trading days added",
"specific language governing permissions and # limitations under the License. import pandas as",
"first_day = all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook,",
"next market minute after @start. This is either the immediate next minute, the",
"the market close # then return the open of the *next* trading day.",
"scheduled date before the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=-1)",
"day, or the open of the next market day after @start. \"\"\" if",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"nothing found return None j = bisect.bisect_left(all_days, second_date) if j == len(all_days): return",
"to add to. Returns ------- datetime n trading days added to date. \"\"\"",
") def _get_index(dt, all_trading_days): \"\"\" Return the index of the given @dt, or",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"under the License. import pandas as pd import numpy as np import bisect",
"not in the trading calendar. \"\"\" ndt = normalize_date(dt) if ndt in all_trading_days:",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"between start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) return",
"= normalize_date(date) delta = pd.Timedelta(days=1) while dt <= last_trading_day: dt += delta if",
"date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day < dt: dt",
"positive or negative. date : datetime The date to add to. Returns -------",
"if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start before market open on",
"following date is needed. Returns ------- Timestamp The next scheduled date after the",
"a trading day, or is before the market open # then return the",
"session date in the calendar before the provided date. Parameters ---------- date :",
"required by applicable law or agreed to in writing, software # distributed under",
"def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def",
"previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date) second_date",
"all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start,",
"next_scheduled_day_hook(date) if n == -1: return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) + n",
"or the close of the market day before @start. \"\"\" if is_scheduled_day_hook(start): market_open,",
"applicable law or agreed to in writing, software # distributed under the License",
"market_open, market_close = open_and_close_hook(start) # If start after the market close, return market",
"0 or idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d days to %s'",
"the same day if @start is after the close on a trading day,",
"in the trading calendar. \"\"\" ndt = normalize_date(dt) if ndt in all_trading_days: return",
"days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes and truncate minutes",
"\"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\" Return the",
"return start + pd.Timedelta(minutes=1) # If start is not in a trading day,",
"all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1 # The following methods are",
"# If start is during trading hours, then get the next minute. elif",
"is raised. Parameters ---------- n : int The number of days to add",
"if @start is before the market open on a trading day, or the",
"is not a trading day, or is before the market open # then",
"distance >= 0 return distance def minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day) return",
"all_trading_days.searchsorted(ndt) - 1 # The following methods are intended to be inserted in",
"start is during trading hours, then get the next minute. elif start <",
"or agreed to in writing, software # distributed under the License is distributed",
"all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1 # The following methods are intended to",
"dt raise NoFurtherDataError(msg='Cannot find previous day before %s' % date) def next_open_and_close(date, open_and_close_hook,",
"end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) all_minutes = [] for",
"return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next market",
"immediate previous minute, the close of the same day if @start is after",
"bisect.bisect_left(all_days, second_date) if j == len(all_days): return None distance = j - 1",
"open_and_close_hook(start) # If start after the market close, return market close. if start",
"day in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes and",
"Get the next market minute before @start. This is either the immediate previous",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"close of the same day if @start is after the close on a",
"all_trading_days): \"\"\" Return the index of the given @dt, or the index of",
"------- Timestamp The next scheduled date after the provided date. \"\"\" dt =",
"index of the preceding trading day if the given dt is not in",
"pd.Timedelta(days=1) while dt <= last_trading_day: dt += delta if is_scheduled_day_hook(dt): return dt raise",
"as pd import numpy as np import bisect from zipline.errors import NoFurtherDataError def",
"def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution minutes for the days",
"Timestamp The date whose following date is needed. Returns ------- Timestamp The next",
"start - pd.Timedelta(minutes=1) # If start is not a trading day, or is",
"minute before @start. This is either the immediate previous minute, the close of",
"is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find previous day before %s' % date) def",
"before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days):",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"def days_in_range(start, end, all_days): \"\"\" Get all execution days between start and end,",
"or the open of the next market day after @start. \"\"\" if is_scheduled_day_hook(start):",
"minute, the open of the same day if @start is before the market",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"the calendar before the provided date. Parameters ---------- date : Timestamp The date",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"The date whose following date is needed. Returns ------- Timestamp The next scheduled",
"Get the next market minute after @start. This is either the immediate next",
"License. # You may obtain a copy of the License at # #",
"minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\" Return the index of the given",
"if start < market_open: return market_open # If start is during trading hours,",
"next minute. elif start < market_close: return start + pd.Timedelta(minutes=1) # If start",
"Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"next minute, the open of the same day if @start is before the",
"the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day <",
"compliance with the License. # You may obtain a copy of the License",
"either the immediate next minute, the open of the same day if @start",
"None j = bisect.bisect_left(all_days, second_date) if j == len(all_days): return None distance =",
"is during trading hours, then get the next minute. elif start < market_close:",
"\"\"\" ndt = normalize_date(dt) if ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt)",
"delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find next day after %s' %",
"a NoFurtherDataError is raised. Parameters ---------- n : int The number of days",
"If start is during trading hours, then get previous minute. if start >",
"# The following methods are intended to be inserted in both the #",
"last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next market minute after",
"or is before the market open # then return the close of the",
"during trading hours, then get previous minute. if start > market_open: return start",
"for the specific language governing permissions and # limitations under the License. import",
"of the market day before @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start)",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"def delta_from_time(t): \"\"\" Convert a datetime.time into a timedelta. \"\"\" return pd.Timedelta( hours=t.hour,",
"datetime.time into a timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt,",
"seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\" Return the index of the given @dt,",
"# nothing found return None j = bisect.bisect_left(all_days, second_date) if j == len(all_days):",
"this can be positive or negative. date : datetime The date to add",
"Concatenate all minutes and truncate minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC')",
"to avoid code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next session",
"of days to add to date, this can be positive or negative. date",
"> market_close: return market_close # If start is during trading hours, then get",
"same day if @start is after the close on a trading day, or",
"all minutes and truncate minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def",
"before @start. This is either the immediate previous minute, the close of the",
"day, or the close of the market day before @start. \"\"\" if is_scheduled_day_hook(start):",
"%d days to %s' % (n, date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook):",
"not use this file except in compliance with the License. # You may",
"import bisect from zipline.errors import NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date, tz='UTC') return",
"ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1 # The following",
"would fall outside of the trading calendar, a NoFurtherDataError is raised. Parameters ----------",
"the next market day after @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start)",
"= _get_index(date, all_trading_days) + n if idx < 0 or idx >= len(all_trading_days):",
"before the market open on a trading day, or the open of the",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"and TradingSchedule classes. # These methods live in the helpers module to avoid",
"end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def",
"== -1: return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) + n if idx <",
"after the provided date. Parameters ---------- date : Timestamp The date whose following",
"dt raise NoFurtherDataError(msg='Cannot find next day after %s' % date) def previous_scheduled_day(date, first_trading_day,",
"== len(all_days): return None distance = j - 1 assert distance >= 0",
"and # limitations under the License. import pandas as pd import numpy as",
"normalize_date(first_date) second_date = normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if i == len(all_days): #",
"@start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start after the",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) all_minutes =",
"given @dt, or the index of the preceding trading day if the given",
"all_trading_days): \"\"\" Adds n trading days to date. If this would fall outside",
"return market open. if start < market_open: return market_open # If start is",
"date to add to. Returns ------- datetime n trading days added to date.",
"is before the market open on a trading day, or the open of",
"then get previous minute. if start > market_open: return start - pd.Timedelta(minutes=1) #",
"def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next session date in the calendar",
"date. Parameters ---------- date : Timestamp The date whose following date is needed.",
"If start is during trading hours, then get the next minute. elif start",
"\"\"\" start_date = normalize_date(start) end_date = normalize_date(end) all_minutes = [] for day in",
"during trading hours, then get the next minute. elif start < market_close: return",
"live in the helpers module to avoid code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook):",
"end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds",
"def scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date) second_date = normalize_date(second_date) i = bisect.bisect_left(all_days,",
"start is not in a trading day, or is after the market close",
"distance def minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day) return pd.date_range(start, end, freq='T') def",
"close of the market day before @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close =",
"Adds n trading days to date. If this would fall outside of the",
"# you may not use this file except in compliance with the License.",
"the days between start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date =",
"days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution minutes for the days between start and",
"inserted in both the # ExchangeCalendar and TradingSchedule classes. # These methods live",
"duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next session date in the",
"agreed to in writing, software # distributed under the License is distributed on",
"\"\"\" Get all execution minutes for the days between start and end, inclusive.",
"= normalize_date(start) end_date = normalize_date(end) all_minutes = [] for day in days_in_range_hook(start_date, end_date):",
"is_scheduled_day_hook): \"\"\" Returns the next session date in the calendar after the provided",
"for the days between start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date",
": Timestamp The date whose previous date is needed. Returns ------- Timestamp The",
"trading days to date. If this would fall outside of the trading calendar,",
"session date in the calendar after the provided date. Parameters ---------- date :",
"minute after @start. This is either the immediate next minute, the open of",
"before market open on a trading day, return market open. if start <",
"open on a trading day, return market open. if start < market_open: return",
"0 return distance def minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day) return pd.date_range(start, end,",
"(the \"License\"); # you may not use this file except in compliance with",
"before %s' % date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook,",
"the given @dt, or the index of the preceding trading day if the",
"+ n if idx < 0 or idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot",
"normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution",
"Returns ------- Timestamp The previous scheduled date before the provided date. \"\"\" dt",
"market_close = open_and_close_hook(start) # If start after the market close, return market close.",
"len(all_days): # nothing found return None j = bisect.bisect_left(all_days, second_date) if j ==",
"next session date in the calendar after the provided date. Parameters ---------- date",
"minute, the close of the same day if @start is after the close",
"Parameters ---------- date : Timestamp The date whose following date is needed. Returns",
"after %s' % date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous session",
"# Unless required by applicable law or agreed to in writing, software #",
"by applicable law or agreed to in writing, software # distributed under the",
"the trading calendar. \"\"\" ndt = normalize_date(dt) if ndt in all_trading_days: return all_trading_days.searchsorted(ndt)",
"open of the same day if @start is before the market open on",
"trading hours, then get the next minute. elif start < market_close: return start",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"the given dt is not in the trading calendar. \"\"\" ndt = normalize_date(dt)",
"both the # ExchangeCalendar and TradingSchedule classes. # These methods live in the",
"trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next",
"trading hours, then get previous minute. if start > market_open: return start -",
"date : datetime The date to add to. Returns ------- datetime n trading",
"\"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day < dt: dt +=",
"the provided date. Parameters ---------- date : Timestamp The date whose following date",
"first_date = normalize_date(first_date) second_date = normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if i ==",
"the close on a trading day, or the close of the market day",
"Inc. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"calendar. \"\"\" ndt = normalize_date(dt) if ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else: return",
"market close, return market close. if start > market_close: return market_close # If",
"< dt: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find previous",
"add to. Returns ------- datetime n trading days added to date. \"\"\" if",
"- 1 assert distance >= 0 return distance def minutes_for_day(day, open_and_close_hook): start, end",
"after the market close # then return the open of the *next* trading",
"the open of the next market day after @start. \"\"\" if is_scheduled_day_hook(start): market_open,",
"file except in compliance with the License. # You may obtain a copy",
"import NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\"",
"Return the index of the given @dt, or the index of the preceding",
"n if idx < 0 or idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add",
"whose previous date is needed. Returns ------- Timestamp The previous scheduled date before",
"governing permissions and # limitations under the License. import pandas as pd import",
"zipline.errors import NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t):",
"add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading days to date. If",
"trading days added to date. \"\"\" if n == 1: return next_scheduled_day_hook(date) if",
"trading day, or is after the market close # then return the open",
"normalize_date(date) delta = pd.Timedelta(days=1) while dt <= last_trading_day: dt += delta if is_scheduled_day_hook(dt):",
"intended to be inserted in both the # ExchangeCalendar and TradingSchedule classes. #",
"License for the specific language governing permissions and # limitations under the License.",
"if idx < 0 or idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d",
"previous scheduled date before the provided date. \"\"\" dt = normalize_date(date) delta =",
"add to date, this can be positive or negative. date : datetime The",
"to in writing, software # distributed under the License is distributed on an",
"return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\" Return the index",
">= 0 return distance def minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day) return pd.date_range(start,",
"minute. if start > market_open: return start - pd.Timedelta(minutes=1) # If start is",
"in all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1 # The following methods",
"datetime n trading days added to date. \"\"\" if n == 1: return",
"outside of the trading calendar, a NoFurtherDataError is raised. Parameters ---------- n :",
"implied. # See the License for the specific language governing permissions and #",
"before @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start after",
"numpy as np import bisect from zipline.errors import NoFurtherDataError def normalize_date(date): date =",
"\"License\"); # you may not use this file except in compliance with the",
"NoFurtherDataError(msg='Cannot find next day after %s' % date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\"",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"raise NoFurtherDataError(msg='Cannot find next day after %s' % date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook):",
"while dt <= last_trading_day: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot",
"Timestamp The date whose previous date is needed. Returns ------- Timestamp The previous",
"truncate minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook,",
"start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\"",
"Timestamp The next scheduled date after the provided date. \"\"\" dt = normalize_date(date)",
"close, return market close. if start > market_close: return market_close # If start",
"normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day < dt: dt += delta if is_scheduled_day_hook(dt):",
"len(all_days): return None distance = j - 1 assert distance >= 0 return",
"Convert a datetime.time into a timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, )",
"The date to add to. Returns ------- datetime n trading days added to",
"dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find next day after",
"is_scheduled_day_hook): \"\"\" Returns the previous session date in the calendar before the provided",
"a timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\"",
"= normalize_date(first_date) second_date = normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if i == len(all_days):",
"or implied. # See the License for the specific language governing permissions and",
"is after the market close # then return the open of the *next*",
"License. import pandas as pd import numpy as np import bisect from zipline.errors",
"delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find previous day before %s' %",
"= normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if i == len(all_days): # nothing found",
"\"\"\" Adds n trading days to date. If this would fall outside of",
"date. \"\"\" if n == 1: return next_scheduled_day_hook(date) if n == -1: return",
"== len(all_days): # nothing found return None j = bisect.bisect_left(all_days, second_date) if j",
"a trading day, or is after the market close # then return the",
"not a trading day, or is before the market open # then return",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"trading day if the given dt is not in the trading calendar. \"\"\"",
"return dt raise NoFurtherDataError(msg='Cannot find previous day before %s' % date) def next_open_and_close(date,",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"provided date. Parameters ---------- date : Timestamp The date whose previous date is",
"Get all execution minutes for the days between start and end, inclusive. \"\"\"",
"for day in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes",
"next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next session date in the calendar after",
"whose following date is needed. Returns ------- Timestamp The next scheduled date after",
"calendar, a NoFurtherDataError is raised. Parameters ---------- n : int The number of",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"the index of the given @dt, or the index of the preceding trading",
"the immediate previous minute, the close of the same day if @start is",
"in writing, software # distributed under the License is distributed on an \"AS",
"trading day, or the open of the next market day after @start. \"\"\"",
"\"\"\" if n == 1: return next_scheduled_day_hook(date) if n == -1: return previous_scheduled_day_hook(date)",
"int The number of days to add to date, this can be positive",
"immediate next minute, the open of the same day if @start is before",
"to be inserted in both the # ExchangeCalendar and TradingSchedule classes. # These",
"first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous session date in the calendar before the",
"day, return market open. if start < market_open: return market_open # If start",
"on a trading day, or the open of the next market day after",
"1 assert distance >= 0 return distance def minutes_for_day(day, open_and_close_hook): start, end =",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
") return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day = all_days[-1] return",
"calendar after the provided date. Parameters ---------- date : Timestamp The date whose",
"@start. This is either the immediate previous minute, the close of the same",
"classes. # These methods live in the helpers module to avoid code duplication.",
"methods are intended to be inserted in both the # ExchangeCalendar and TradingSchedule",
"or is after the market close # then return the open of the",
"all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\"",
"def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date)",
"be positive or negative. date : datetime The date to add to. Returns",
"pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a datetime.time into a timedelta.",
"np import bisect from zipline.errors import NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date, tz='UTC')",
"delta_from_time(t): \"\"\" Convert a datetime.time into a timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute,",
"- 1 # The following methods are intended to be inserted in both",
"+= delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find next day after %s'",
"methods live in the helpers module to avoid code duplication. def next_scheduled_day(date, last_trading_day,",
"inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start,",
"normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\"",
"(n, date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day =",
"in both the # ExchangeCalendar and TradingSchedule classes. # These methods live in",
"pd.Timedelta(days=-1) while first_trading_day < dt: dt += delta if is_scheduled_day_hook(dt): return dt raise",
"start is not a trading day, or is before the market open #",
"the previous session date in the calendar before the provided date. Parameters ----------",
"_get_index(date, all_trading_days) + n if idx < 0 or idx >= len(all_trading_days): raise",
"after @start. This is either the immediate next minute, the open of the",
"open # then return the close of the *previous* trading day. return previous_open_and_close_hook(start)[1]",
"the next market minute after @start. This is either the immediate next minute,",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day) return pd.date_range(start, end, freq='T') def days_in_range(start, end,",
"delta = pd.Timedelta(days=-1) while first_trading_day < dt: dt += delta if is_scheduled_day_hook(dt): return",
"if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start after the market close,",
"are intended to be inserted in both the # ExchangeCalendar and TradingSchedule classes.",
"# These methods live in the helpers module to avoid code duplication. def",
"The next scheduled date after the provided date. \"\"\" dt = normalize_date(date) delta",
"execution minutes for the days between start and end, inclusive. \"\"\" start_date =",
"return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n",
"start, end = open_and_close_hook(day) return pd.date_range(start, end, freq='T') def days_in_range(start, end, all_days): \"\"\"",
"\"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start before market open",
"get the next minute. elif start < market_close: return start + pd.Timedelta(minutes=1) #",
"and truncate minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date,",
"next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date,",
"next_open_and_close_hook): \"\"\" Get the next market minute after @start. This is either the",
"use this file except in compliance with the License. # You may obtain",
"is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start after the market close, return",
"the close of the same day if @start is after the close on",
"minutes_for_days_in_range_hook): first_day = all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook,",
"<gh_stars>0 # # Copyright 2016 Quantopian, Inc. # # Licensed under the Apache",
"is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next market minute before @start. This is",
"j = bisect.bisect_left(all_days, second_date) if j == len(all_days): return None distance = j",
"index of the given @dt, or the index of the preceding trading day",
"_get_index(dt, all_trading_days): \"\"\" Return the index of the given @dt, or the index",
"= normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook):",
"normalize_date(end) all_minutes = [] for day in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes)",
"This is either the immediate previous minute, the close of the same day",
"the same day if @start is before the market open on a trading",
"can be positive or negative. date : datetime The date to add to.",
"# limitations under the License. import pandas as pd import numpy as np",
"dt = normalize_date(date) delta = pd.Timedelta(days=1) while dt <= last_trading_day: dt += delta",
"a trading day, return market open. if start < market_open: return market_open #",
"the helpers module to avoid code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"market close. if start > market_close: return market_close # If start is during",
"limitations under the License. import pandas as pd import numpy as np import",
"= normalize_date(dt) if ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1",
"the next session date in the calendar after the provided date. Parameters ----------",
"end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get",
"the open of the *next* trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook,",
"open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next market minute before @start. This is either",
"== 1: return next_scheduled_day_hook(date) if n == -1: return previous_scheduled_day_hook(date) idx = _get_index(date,",
"second_date = normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if i == len(all_days): # nothing",
"trading day, or is before the market open # then return the close",
"delta = pd.Timedelta(days=1) while dt <= last_trading_day: dt += delta if is_scheduled_day_hook(dt): return",
"the market open # then return the close of the *previous* trading day.",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"<= last_trading_day: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find next",
"return None j = bisect.bisect_left(all_days, second_date) if j == len(all_days): return None distance",
"minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution minutes for the days between",
"return the open of the *next* trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook,",
"------- Timestamp The previous scheduled date before the provided date. \"\"\" dt =",
"market open on a trading day, return market open. if start < market_open:",
"the index of the preceding trading day if the given dt is not",
"start_date = normalize_date(start) end_date = normalize_date(end) all_minutes = [] for day in days_in_range_hook(start_date,",
"ExchangeCalendar and TradingSchedule classes. # These methods live in the helpers module to",
"if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find next day after %s' % date)",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"dt: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find previous day",
"@dt, or the index of the preceding trading day if the given dt",
"if i == len(all_days): # nothing found return None j = bisect.bisect_left(all_days, second_date)",
"market_open: return start - pd.Timedelta(minutes=1) # If start is not a trading day,",
"trading day, or the close of the market day before @start. \"\"\" if",
"needed. Returns ------- Timestamp The next scheduled date after the provided date. \"\"\"",
"start + pd.Timedelta(minutes=1) # If start is not in a trading day, or",
"from zipline.errors import NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def",
"copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading days",
"fall outside of the trading calendar, a NoFurtherDataError is raised. Parameters ---------- n",
"start_date = normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook,",
"# # Unless required by applicable law or agreed to in writing, software",
"is needed. Returns ------- Timestamp The next scheduled date after the provided date.",
"end_date = normalize_date(end) all_minutes = [] for day in days_in_range_hook(start_date, end_date): day_minutes =",
"after the market close, return market close. if start > market_close: return market_close",
"express or implied. # See the License for the specific language governing permissions",
"a trading day, or the open of the next market day after @start.",
"= open_and_close_hook(start) # If start before market open on a trading day, return",
"day after %s' % date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous",
"NoFurtherDataError is raised. Parameters ---------- n : int The number of days to",
"msg='Cannot add %d days to %s' % (n, date) ) return all_trading_days[idx] def",
"code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next session date in",
"day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next market",
"---------- n : int The number of days to add to date, this",
"%s' % date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous session date",
"idx = _get_index(date, all_trading_days) + n if idx < 0 or idx >=",
"calendar before the provided date. Parameters ---------- date : Timestamp The date whose",
"into a timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days):",
"normalize_date(dt) if ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1 #",
"return dt raise NoFurtherDataError(msg='Cannot find next day after %s' % date) def previous_scheduled_day(date,",
"assert distance >= 0 return distance def minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day)",
"len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d days to %s' % (n, date) )",
"either express or implied. # See the License for the specific language governing",
"all_days): first_date = normalize_date(first_date) second_date = normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if i",
"execution days between start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date =",
"# # Copyright 2016 Quantopian, Inc. # # Licensed under the Apache License,",
"scheduled date after the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=1)",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"\"\"\" Returns the previous session date in the calendar before the provided date.",
"all_minutes.append(day_minutes) # Concatenate all minutes and truncate minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes),",
"market minute before @start. This is either the immediate previous minute, the close",
"return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a datetime.time into a timedelta. \"\"\" return",
"last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next session date in the calendar after the",
"second_date, all_days): first_date = normalize_date(first_date) second_date = normalize_date(second_date) i = bisect.bisect_left(all_days, first_date) if",
"These methods live in the helpers module to avoid code duplication. def next_scheduled_day(date,",
"all execution days between start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date",
"day before %s' % date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date,",
"or idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d days to %s' %",
"day if @start is before the market open on a trading day, or",
"next market day after @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) #",
"days added to date. \"\"\" if n == 1: return next_scheduled_day_hook(date) if n",
"\"\"\" Get the next market minute before @start. This is either the immediate",
"j == len(all_days): return None distance = j - 1 assert distance >=",
"all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next",
"If start after the market close, return market close. if start > market_close:",
"Copyright 2016 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0",
"# If start is not in a trading day, or is after the",
"n == 1: return next_scheduled_day_hook(date) if n == -1: return previous_scheduled_day_hook(date) idx =",
"the calendar after the provided date. Parameters ---------- date : Timestamp The date",
"---------- date : Timestamp The date whose previous date is needed. Returns -------",
"return distance def minutes_for_day(day, open_and_close_hook): start, end = open_and_close_hook(day) return pd.date_range(start, end, freq='T')",
"start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) return all_days[all_days.slice_indexer(start_date,",
"find next day after %s' % date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns",
"of the *next* trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\"",
"the next minute. elif start < market_close: return start + pd.Timedelta(minutes=1) # If",
"the License. # You may obtain a copy of the License at #",
"first_date) if i == len(all_days): # nothing found return None j = bisect.bisect_left(all_days,",
"is after the close on a trading day, or the close of the",
"market_close: return market_close # If start is during trading hours, then get previous",
"if ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) - 1 # The",
"= minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes and truncate minutes before start/after end.",
"date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day = all_days[-1]",
"return market_open # If start is during trading hours, then get the next",
"dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find previous day before",
"to date, this can be positive or negative. date : datetime The date",
"This is either the immediate next minute, the open of the same day",
"open of the next market day after @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"ndt = normalize_date(dt) if ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else: return all_trading_days.searchsorted(ndt) -",
"previous session date in the calendar before the provided date. Parameters ---------- date",
"\"\"\" Get all execution days between start and end, inclusive. \"\"\" start_date =",
"previous_open_and_close_hook): \"\"\" Get the next market minute before @start. This is either the",
"# If start is during trading hours, then get previous minute. if start",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"date in the calendar before the provided date. Parameters ---------- date : Timestamp",
"= open_and_close_hook(start) # If start after the market close, return market close. if",
"all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day)",
"Returns the next session date in the calendar after the provided date. Parameters",
"< market_close: return start + pd.Timedelta(minutes=1) # If start is not in a",
"pd.DatetimeIndex(np.concatenate(all_minutes), copy=False, tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading",
"days to date. If this would fall outside of the trading calendar, a",
"days to %s' % (n, date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day",
"the *next* trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get",
"end, freq='T') def days_in_range(start, end, all_days): \"\"\" Get all execution days between start",
"get previous minute. if start > market_open: return start - pd.Timedelta(minutes=1) # If",
"if n == 1: return next_scheduled_day_hook(date) if n == -1: return previous_scheduled_day_hook(date) idx",
"def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def",
"is either the immediate next minute, the open of the same day if",
"NoFurtherDataError( msg='Cannot add %d days to %s' % (n, date) ) return all_trading_days[idx]",
"date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous session date in the",
"the immediate next minute, the open of the same day if @start is",
"return start - pd.Timedelta(minutes=1) # If start is not a trading day, or",
"in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes and truncate",
"inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) all_minutes = [] for day",
"date after the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=1) while",
"\"\"\" Returns the next session date in the calendar after the provided date.",
"- pd.Timedelta(minutes=1) # If start is not a trading day, or is before",
"The number of days to add to date, this can be positive or",
"If start is not a trading day, or is before the market open",
"2016 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the",
"= pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a datetime.time into a",
"minutes_for_day_hook): \"\"\" Get all execution minutes for the days between start and end,",
"the market close, return market close. if start > market_close: return market_close #",
"def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next market minute before @start.",
"previous minute. if start > market_open: return start - pd.Timedelta(minutes=1) # If start",
"return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next market minute",
"before the provided date. Parameters ---------- date : Timestamp The date whose previous",
"the specific language governing permissions and # limitations under the License. import pandas",
"= [] for day in days_in_range_hook(start_date, end_date): day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate",
"with the License. # You may obtain a copy of the License at",
"\"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=1) while dt <= last_trading_day: dt +=",
"date whose previous date is needed. Returns ------- Timestamp The previous scheduled date",
"days between start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end)",
"provided date. Parameters ---------- date : Timestamp The date whose following date is",
"is not in a trading day, or is after the market close #",
"first_trading_day < dt: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find",
"previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) + n if idx < 0 or idx",
"end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution minutes for the days between start",
"Parameters ---------- date : Timestamp The date whose previous date is needed. Returns",
"# If start is not a trading day, or is before the market",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"previous date is needed. Returns ------- Timestamp The previous scheduled date before the",
"return market close. if start > market_close: return market_close # If start is",
"the close of the market day before @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close",
"provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=1) while dt <= last_trading_day:",
"Returns the previous session date in the calendar before the provided date. Parameters",
"# If start after the market close, return market close. if start >",
"\"\"\" Get the next market minute after @start. This is either the immediate",
"law or agreed to in writing, software # distributed under the License is",
"market_open, market_close = open_and_close_hook(start) # If start before market open on a trading",
"the market day before @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) #",
"the License for the specific language governing permissions and # limitations under the",
"market day after @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If",
"*next* trading day. return next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the",
"minute. elif start < market_close: return start + pd.Timedelta(minutes=1) # If start is",
"find previous day before %s' % date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date))",
"market_close = open_and_close_hook(start) # If start before market open on a trading day,",
"@start is after the close on a trading day, or the close of",
"a trading day, or the close of the market day before @start. \"\"\"",
"be inserted in both the # ExchangeCalendar and TradingSchedule classes. # These methods",
"pandas as pd import numpy as np import bisect from zipline.errors import NoFurtherDataError",
"If this would fall outside of the trading calendar, a NoFurtherDataError is raised.",
"of the next market day after @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close =",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"to date. If this would fall outside of the trading calendar, a NoFurtherDataError",
"and end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) all_minutes = []",
"return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution minutes",
"= all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook):",
"Parameters ---------- n : int The number of days to add to date,",
"The following methods are intended to be inserted in both the # ExchangeCalendar",
"import pandas as pd import numpy as np import bisect from zipline.errors import",
"close on a trading day, or the close of the market day before",
"bisect from zipline.errors import NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date)",
"trading calendar. \"\"\" ndt = normalize_date(dt) if ndt in all_trading_days: return all_trading_days.searchsorted(ndt) else:",
"market_open # If start is during trading hours, then get the next minute.",
"on a trading day, or the close of the market day before @start.",
"date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date))",
"either the immediate previous minute, the close of the same day if @start",
"dt <= last_trading_day: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find",
"%s' % date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook):",
"is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start before market open on a",
"date whose following date is needed. Returns ------- Timestamp The next scheduled date",
"Returns ------- Timestamp The next scheduled date after the provided date. \"\"\" dt",
"open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date) second_date =",
"the provided date. Parameters ---------- date : Timestamp The date whose previous date",
"avoid code duplication. def next_scheduled_day(date, last_trading_day, is_scheduled_day_hook): \"\"\" Returns the next session date",
"= bisect.bisect_left(all_days, second_date) if j == len(all_days): return None distance = j -",
"The date whose previous date is needed. Returns ------- Timestamp The previous scheduled",
"in compliance with the License. # You may obtain a copy of the",
"If start before market open on a trading day, return market open. if",
"minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes and truncate minutes before start/after end. return",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start after the market",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"pd.Timedelta(minutes=1) # If start is not a trading day, or is before the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"market day before @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If",
"@start is before the market open on a trading day, or the open",
"distance = j - 1 assert distance >= 0 return distance def minutes_for_day(day,",
"return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) + n if idx < 0 or",
"return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day,",
"after the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=1) while dt",
"trading calendar, a NoFurtherDataError is raised. Parameters ---------- n : int The number",
"to add to date, this can be positive or negative. date : datetime",
"See the License for the specific language governing permissions and # limitations under",
"provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day < dt:",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"next market minute before @start. This is either the immediate previous minute, the",
"start is during trading hours, then get previous minute. if start > market_open:",
"next day after %s' % date) def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the",
"number of days to add to date, this can be positive or negative.",
"as np import bisect from zipline.errors import NoFurtherDataError def normalize_date(date): date = pd.Timestamp(date,",
"Timestamp The previous scheduled date before the provided date. \"\"\" dt = normalize_date(date)",
"next scheduled date after the provided date. \"\"\" dt = normalize_date(date) delta =",
"start before market open on a trading day, return market open. if start",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"@start. This is either the immediate next minute, the open of the same",
"days_in_range(start, end, all_days): \"\"\" Get all execution days between start and end, inclusive.",
"def _get_index(dt, all_trading_days): \"\"\" Return the index of the given @dt, or the",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"the preceding trading day if the given dt is not in the trading",
"hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\" Return the index of the",
"open_and_close_hook(start) # If start before market open on a trading day, return market",
"return next_scheduled_day_hook(date) if n == -1: return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) +",
"= bisect.bisect_left(all_days, first_date) if i == len(all_days): # nothing found return None j",
"previous minute, the close of the same day if @start is after the",
"% (n, date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0] last_day",
"def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next market minute after @start.",
"on a trading day, return market open. if start < market_open: return market_open",
"date. Parameters ---------- date : Timestamp The date whose previous date is needed.",
"# Concatenate all minutes and truncate minutes before start/after end. return pd.DatetimeIndex(np.concatenate(all_minutes), copy=False,",
"if the given dt is not in the trading calendar. \"\"\" ndt =",
"if j == len(all_days): return None distance = j - 1 assert distance",
"= normalize_date(end) return all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all",
"same day if @start is before the market open on a trading day,",
"market open on a trading day, or the open of the next market",
"end, all_days): \"\"\" Get all execution days between start and end, inclusive. \"\"\"",
"dt = normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day < dt: dt += delta",
"after the close on a trading day, or the close of the market",
"while first_trading_day < dt: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot",
"market_close: return start + pd.Timedelta(minutes=1) # If start is not in a trading",
"or negative. date : datetime The date to add to. Returns ------- datetime",
"open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date =",
"------- datetime n trading days added to date. \"\"\" if n == 1:",
"is needed. Returns ------- Timestamp The previous scheduled date before the provided date.",
"all_days): \"\"\" Get all execution days between start and end, inclusive. \"\"\" start_date",
"after @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start before",
"+= delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find previous day before %s'",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"of the same day if @start is after the close on a trading",
"except in compliance with the License. # You may obtain a copy of",
"day after @start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start",
"of the same day if @start is before the market open on a",
"Get all execution days between start and end, inclusive. \"\"\" start_date = normalize_date(start)",
"is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find next day after %s' % date) def",
"timedelta. \"\"\" return pd.Timedelta( hours=t.hour, minutes=t.minute, seconds=t.second, ) def _get_index(dt, all_trading_days): \"\"\" Return",
"last_day = all_days[-1] return minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get",
"before the provided date. \"\"\" dt = normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day",
"previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date) second_date = normalize_date(second_date)",
"open. if start < market_open: return market_open # If start is during trading",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): \"\"\" Returns the previous session date in the calendar",
"day_minutes = minutes_for_day_hook(day) all_minutes.append(day_minutes) # Concatenate all minutes and truncate minutes before start/after",
"added to date. \"\"\" if n == 1: return next_scheduled_day_hook(date) if n ==",
"% date) def next_open_and_close(date, open_and_close_hook, next_scheduled_day_hook): return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return",
"tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a datetime.time into a timedelta. \"\"\"",
"if n == -1: return previous_scheduled_day_hook(date) idx = _get_index(date, all_trading_days) + n if",
"market_open: return market_open # If start is during trading hours, then get the",
"elif start < market_close: return start + pd.Timedelta(minutes=1) # If start is not",
"n trading days added to date. \"\"\" if n == 1: return next_scheduled_day_hook(date)",
"found return None j = bisect.bisect_left(all_days, second_date) if j == len(all_days): return None",
"if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find previous day before %s' % date)",
"previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next market minute before @start. This",
"second_date) if j == len(all_days): return None distance = j - 1 assert",
"minutes_for_days_in_range_hook(first_day, last_day) def next_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next market minute",
"all_days[all_days.slice_indexer(start_date, end_date)] def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): \"\"\" Get all execution minutes for",
"market close # then return the open of the *next* trading day. return",
"start > market_open: return start - pd.Timedelta(minutes=1) # If start is not a",
"i = bisect.bisect_left(all_days, first_date) if i == len(all_days): # nothing found return None",
"bisect.bisect_left(all_days, first_date) if i == len(all_days): # nothing found return None j =",
"is_scheduled_day_hook, open_and_close_hook, next_open_and_close_hook): \"\"\" Get the next market minute after @start. This is",
"before the market open # then return the close of the *previous* trading",
"hours, then get previous minute. if start > market_open: return start - pd.Timedelta(minutes=1)",
"%s' % (n, date) ) return all_trading_days[idx] def all_scheduled_minutes(all_days, minutes_for_days_in_range_hook): first_day = all_days[0]",
"next_open_and_close_hook(start)[0] def previous_scheduled_minute(start, is_scheduled_day_hook, open_and_close_hook, previous_open_and_close_hook): \"\"\" Get the next market minute before",
"the License. import pandas as pd import numpy as np import bisect from",
"open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date = normalize_date(first_date) second_date = normalize_date(second_date) i =",
"< market_open: return market_open # If start is during trading hours, then get",
"\"\"\" Return the index of the given @dt, or the index of the",
"dt is not in the trading calendar. \"\"\" ndt = normalize_date(dt) if ndt",
"freq='T') def days_in_range(start, end, all_days): \"\"\" Get all execution days between start and",
"between start and end, inclusive. \"\"\" start_date = normalize_date(start) end_date = normalize_date(end) all_minutes",
"pd.date_range(start, end, freq='T') def days_in_range(start, end, all_days): \"\"\" Get all execution days between",
"date = pd.Timestamp(date, tz='UTC') return pd.tseries.tools.normalize_date(date) def delta_from_time(t): \"\"\" Convert a datetime.time into",
"then get the next minute. elif start < market_close: return start + pd.Timedelta(minutes=1)",
"or the index of the preceding trading day if the given dt is",
"start > market_close: return market_close # If start is during trading hours, then",
"day, or is before the market open # then return the close of",
"start < market_open: return market_open # If start is during trading hours, then",
"date, this can be positive or negative. date : datetime The date to",
"last_trading_day: dt += delta if is_scheduled_day_hook(dt): return dt raise NoFurtherDataError(msg='Cannot find next day",
"= normalize_date(date) delta = pd.Timedelta(days=-1) while first_trading_day < dt: dt += delta if",
"close # then return the open of the *next* trading day. return next_open_and_close_hook(start)[0]",
"return pd.date_range(start, end, freq='T') def days_in_range(start, end, all_days): \"\"\" Get all execution days",
"date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading days to date. If this",
"pd.Timedelta(minutes=1) # If start is not in a trading day, or is after",
"not in a trading day, or is after the market close # then",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"None distance = j - 1 assert distance >= 0 return distance def",
"1 # The following methods are intended to be inserted in both the",
"tz='UTC') def add_scheduled_days(n, date, next_scheduled_day_hook, previous_scheduled_day_hook, all_trading_days): \"\"\" Adds n trading days to",
"normalize_date(start) end_date = normalize_date(end) all_minutes = [] for day in days_in_range_hook(start_date, end_date): day_minutes",
"in the calendar before the provided date. Parameters ---------- date : Timestamp The",
"market open. if start < market_open: return market_open # If start is during",
"date. If this would fall outside of the trading calendar, a NoFurtherDataError is",
"@start. \"\"\" if is_scheduled_day_hook(start): market_open, market_close = open_and_close_hook(start) # If start before market",
"return open_and_close_hook(next_scheduled_day_hook(date)) def previous_open_and_close(date, open_and_close_hook, previous_scheduled_day_hook): return open_and_close_hook(previous_scheduled_day_hook(date)) def scheduled_day_distance(first_date, second_date, all_days): first_date",
"needed. Returns ------- Timestamp The previous scheduled date before the provided date. \"\"\"",
": int The number of days to add to date, this can be",
"hours, then get the next minute. elif start < market_close: return start +",
"idx < 0 or idx >= len(all_trading_days): raise NoFurtherDataError( msg='Cannot add %d days"
] |
[] |
[
"# -*- coding: utf-8 -*- \"\"\"Reactions.\"\"\" from ._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes,",
"-*- coding: utf-8 -*- \"\"\"Reactions.\"\"\" from ._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction",
"._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__ = [ \"reaction\", \"CustomReaction\", \"UniqueAttributes\",",
"import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__ = [ \"reaction\", \"CustomReaction\", \"UniqueAttributes\", \"LimitChildren\",",
"CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__ = [ \"reaction\", \"CustomReaction\", \"UniqueAttributes\", \"LimitChildren\", \"Limit\",",
"coding: utf-8 -*- \"\"\"Reactions.\"\"\" from ._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__",
"\"\"\"Reactions.\"\"\" from ._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__ = [ \"reaction\",",
"from ._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__ = [ \"reaction\", \"CustomReaction\",",
"utf-8 -*- \"\"\"Reactions.\"\"\" from ._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__ =",
"-*- \"\"\"Reactions.\"\"\" from ._reactions import CustomReaction, Limit, LimitChildren, UniqueAttributes, reaction __all__ = [",
"Limit, LimitChildren, UniqueAttributes, reaction __all__ = [ \"reaction\", \"CustomReaction\", \"UniqueAttributes\", \"LimitChildren\", \"Limit\", ]"
] |
[
"import Any, Dict, Optional, Union, List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import",
"db: Session, *, owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self,",
"import Debit from app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self,",
"obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db:",
"Dict[str, Any]]) -> Debit: if isinstance(obj_in, dict): update_data = obj_in else: update_data =",
"skip: int = 0, limit: int = 100) -> List[Dict]: # return (db.query(self.model).offset(skip).limit(limit).all())",
"update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) # def",
"jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self, db:",
"DebitCreate, owner_id: int) -> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj)",
"int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db: Session, *, db_obj:",
"update_status(self, db: Session, *, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit: if",
"owner_id: int) -> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit()",
"return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db: Session, *, db_obj: Debit, obj_in: Union[DebitUpdate,",
"dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) #",
"db_obj def get_by_owner(self, db: Session, *, owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id ==",
"Session, *, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit: if isinstance(obj_in, dict):",
"Any]]) -> Debit: if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True)",
"= 0, limit: int = 100) -> List[Dict]: # return (db.query(self.model).offset(skip).limit(limit).all()) debit =",
"Debit: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj",
"*, owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db: Session,",
"db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self, db: Session,",
"*, obj_in: DebitCreate, owner_id: int) -> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data,",
"CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session, *, obj_in: DebitCreate, owner_id: int) ->",
"import CRUDBase from app.models.debit import Debit from app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit,",
"super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db: Session, *, # skip: int =",
"DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session, *, obj_in: DebitCreate,",
"Session from app.crud.base import CRUDBase from app.models.debit import Debit from app.schemas.debit import DebitCreate,",
"update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db: Session, *,",
"jsonable_encoder from sqlalchemy.orm import Session from app.crud.base import CRUDBase from app.models.debit import Debit",
"int = 0, limit: int = 100) -> List[Dict]: # return (db.query(self.model).offset(skip).limit(limit).all()) debit",
"obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit: if isinstance(obj_in, dict): update_data = obj_in else:",
"app.models.debit import Debit from app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def",
"Dict, Optional, Union, List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from",
"return super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db: Session, *, # skip: int",
"obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def",
"sqlalchemy.orm import Session from app.crud.base import CRUDBase from app.models.debit import Debit from app.schemas.debit",
"owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db: Session, *,",
"from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app.crud.base import CRUDBase from",
"Session, *, # skip: int = 0, limit: int = 100) -> List[Dict]:",
"db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db: Session, *, # skip: int = 0,",
"def get_by_owner(self, db: Session, *, owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first()",
"-> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db: Session, *, db_obj: Debit,",
"Session, *, owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db:",
"if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj,",
"= obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db: Session, *, #",
"class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session, *, obj_in: DebitCreate, owner_id: int)",
"Union, List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app.crud.base import",
"owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self, db: Session, *, owner_id: int)",
"owner_id).first() def update_status(self, db: Session, *, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) ->",
"from app.crud.base import CRUDBase from app.models.debit import Debit from app.schemas.debit import DebitCreate, DebitUpdate",
"db: Session, *, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit: if isinstance(obj_in,",
"Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit: if isinstance(obj_in, dict): update_data = obj_in",
"from app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session,",
"else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db: Session,",
"db: Session, *, # skip: int = 0, limit: int = 100) ->",
"obj_in=obj_in) # def get_multi(self, db: Session, *, # skip: int = 0, limit:",
"0, limit: int = 100) -> List[Dict]: # return (db.query(self.model).offset(skip).limit(limit).all()) debit = CRUDDebit(Debit)",
"Debit from app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db:",
"DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session, *, obj_in: DebitCreate, owner_id: int) -> Debit:",
"def get_multi(self, db: Session, *, # skip: int = 0, limit: int =",
"from sqlalchemy.orm import Session from app.crud.base import CRUDBase from app.models.debit import Debit from",
"db.refresh(db_obj) return db_obj def get_by_owner(self, db: Session, *, owner_id: int) -> Optional[Debit]: return",
"= jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self,",
"Optional, Union, List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app.crud.base",
"int) -> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj)",
"== owner_id).first() def update_status(self, db: Session, *, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]])",
"import jsonable_encoder from sqlalchemy.orm import Session from app.crud.base import CRUDBase from app.models.debit import",
"Debit: if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db,",
"List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app.crud.base import CRUDBase",
"= self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self, db: Session, *,",
"db: Session, *, obj_in: DebitCreate, owner_id: int) -> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj",
"# skip: int = 0, limit: int = 100) -> List[Dict]: # return",
"isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in)",
"db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self, db: Session, *, owner_id: int) -> Optional[Debit]:",
"obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self, db: Session, *, # skip:",
"db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self, db: Session, *, owner_id: int) ->",
"*, # skip: int = 0, limit: int = 100) -> List[Dict]: #",
"-> Debit: if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) return",
"get_by_owner(self, db: Session, *, owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def",
"db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit: if isinstance(obj_in, dict): update_data =",
"from app.models.debit import Debit from app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]):",
"obj_in: DebitCreate, owner_id: int) -> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id)",
"create_with_owner(self, db: Session, *, obj_in: DebitCreate, owner_id: int) -> Debit: obj_in_data = jsonable_encoder(obj_in)",
"Optional[Debit]: return db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db: Session, *, db_obj: Debit, obj_in:",
"import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session, *, obj_in:",
"return db_obj def get_by_owner(self, db: Session, *, owner_id: int) -> Optional[Debit]: return db.query(Debit).filter(Debit.owner_id",
"get_multi(self, db: Session, *, # skip: int = 0, limit: int = 100)",
"import Session from app.crud.base import CRUDBase from app.models.debit import Debit from app.schemas.debit import",
"# def get_multi(self, db: Session, *, # skip: int = 0, limit: int",
"def create_with_owner(self, db: Session, *, obj_in: DebitCreate, owner_id: int) -> Debit: obj_in_data =",
"Session, *, obj_in: DebitCreate, owner_id: int) -> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj =",
"Union[DebitUpdate, Dict[str, Any]]) -> Debit: if isinstance(obj_in, dict): update_data = obj_in else: update_data",
"fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app.crud.base import CRUDBase from app.models.debit",
"from typing import Any, Dict, Optional, Union, List from fastapi.encoders import jsonable_encoder from",
"CRUDBase from app.models.debit import Debit from app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate,",
"db.query(Debit).filter(Debit.owner_id == owner_id).first() def update_status(self, db: Session, *, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str,",
"= obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=obj_in) # def get_multi(self,",
"app.crud.base import CRUDBase from app.models.debit import Debit from app.schemas.debit import DebitCreate, DebitUpdate class",
"DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session, *, obj_in: DebitCreate, owner_id:",
"Any, Dict, Optional, Union, List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session",
"-> Debit: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return",
"*, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit: if isinstance(obj_in, dict): update_data",
"typing import Any, Dict, Optional, Union, List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm",
"DebitUpdate]): def create_with_owner(self, db: Session, *, obj_in: DebitCreate, owner_id: int) -> Debit: obj_in_data",
"self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def get_by_owner(self, db: Session, *, owner_id:",
"def update_status(self, db: Session, *, db_obj: Debit, obj_in: Union[DebitUpdate, Dict[str, Any]]) -> Debit:",
"app.schemas.debit import DebitCreate, DebitUpdate class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate]): def create_with_owner(self, db: Session, *,"
] |
[
"transaction from .proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc']",
"= MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc'] = 123 print(session) transaction.commit() proxy2 =",
"port 11211 import transaction from .proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session =",
"11211 import transaction from .proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar')",
"Run this test from 'zopectl run' # Requires that we are running a",
"# Run this test from 'zopectl run' # Requires that we are running",
"'zopectl run' # Requires that we are running a memcached on localhost, port",
"session = proxy.new_or_existing('foobar') print(session) session['abc'] = 123 print(session) transaction.commit() proxy2 = MemCacheProxy(['localhost:11211']) print(proxy2.get('foobar'))",
"<reponame>zms-publishing/Products.mcdutils # Run this test from 'zopectl run' # Requires that we are",
"proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc'] = 123 print(session) transaction.commit() proxy2",
"test from 'zopectl run' # Requires that we are running a memcached on",
"from .proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc'] =",
"are running a memcached on localhost, port 11211 import transaction from .proxy import",
"import transaction from .proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session)",
"from 'zopectl run' # Requires that we are running a memcached on localhost,",
"memcached on localhost, port 11211 import transaction from .proxy import MemCacheProxy proxy =",
"# Requires that we are running a memcached on localhost, port 11211 import",
"on localhost, port 11211 import transaction from .proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211'])",
"MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc'] = 123 print(session) transaction.commit() proxy2 = MemCacheProxy(['localhost:11211'])",
"that we are running a memcached on localhost, port 11211 import transaction from",
"import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc'] = 123 print(session)",
"run' # Requires that we are running a memcached on localhost, port 11211",
"MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc'] = 123 print(session) transaction.commit()",
"localhost, port 11211 import transaction from .proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session",
"this test from 'zopectl run' # Requires that we are running a memcached",
"running a memcached on localhost, port 11211 import transaction from .proxy import MemCacheProxy",
"we are running a memcached on localhost, port 11211 import transaction from .proxy",
"Requires that we are running a memcached on localhost, port 11211 import transaction",
"a memcached on localhost, port 11211 import transaction from .proxy import MemCacheProxy proxy",
".proxy import MemCacheProxy proxy = MemCacheProxy(['localhost:11211']) session = proxy.new_or_existing('foobar') print(session) session['abc'] = 123"
] |
[
"for x in top_idx] results[qid] = result with Pool(args.threads) as p: for _",
"= [], [], [] tokens = token_dict.keys() col = [] data = []",
"(matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors = [] with open(args.topics) as",
"with Pool(args.threads) as p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run,",
"parser.add_argument('--run', type=str, help='path to run file', required=True) parser.add_argument('--threads', type=int, help='threads for hnsw', required=False,",
"= json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager = Manager() results =",
"tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data,",
"vectors = [] matrix_row, matrix_col, matrix_data = [], [], [] for i, d",
"= weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)),",
"os from scipy.sparse import csr_matrix from tqdm import tqdm import numpy as np",
"idx corpus = [] for file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if",
"corpus = [] for file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if file.endswith('json')",
"token_dict.keys() col = [] data = [] for tok in tokens: if tok",
"matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors = [] with open(args.topics) as topic_f:",
"col = [] data = [] for tok in tokens: if tok in",
"if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector =",
"open(args.topics) as topic_f: for line in topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id))",
"= result with Pool(args.threads) as p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass",
"topic_ids = [] topic_vectors = [] with open(args.topics) as topic_f: for line in",
"with vectors', required=True) parser.add_argument('--tokens', type=str, help='path to token list', required=True) parser.add_argument('--run', type=str, help='path",
"matrix_data = [], [], [] tokens = token_dict.keys() col = [] data =",
"data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id)))",
"with open(args.run, 'w') as f: for qid in results: for idx, item in",
"= [] data = [] for tok in tokens: if tok in token2id:",
"'w') as f: for qid in results: for idx, item in enumerate(results[qid]): did",
"token list', required=True) parser.add_argument('--run', type=str, help='path to run file', required=True) parser.add_argument('--threads', type=int, help='threads",
"tokens = token_dict.keys() col = [] data = [] for tok in tokens:",
"to topics with vectors', required=True) parser.add_argument('--tokens', type=str, help='path to token list', required=True) parser.add_argument('--run',",
"type=str, help='path to run file', required=True) parser.add_argument('--threads', type=int, help='threads for hnsw', required=False, default=12)",
"[] tokens = token_dict.keys() col = [] data = [] for tok in",
"help='threads for hnsw', required=False, default=12) args = parser.parse_args() token2id = {} with open(args.tokens)",
"in enumerate(tok_f): tok = line.rstrip() token2id[tok] = idx corpus = [] for file",
"[] with open(args.topics) as topic_f: for line in topic_f: info = json.loads(line) topic_ids.append(info['id'])",
"d in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens = weight_dict.keys() col = [token2id[tok] for",
"ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors =",
"i, d in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens = weight_dict.keys() col = [token2id[tok]",
"open(args.run, 'w') as f: for qid in results: for idx, item in enumerate(results[qid]):",
"[], [], [] for i, d in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens =",
"in top_idx] results[qid] = result with Pool(args.threads) as p: for _ in tqdm(p.imap_unordered(run_search,",
"vectors', required=True) parser.add_argument('--tokens', type=str, help='path to token list', required=True) parser.add_argument('--run', type=str, help='path to",
"= [] matrix_row, matrix_col, matrix_data = [], [], [] for i, d in",
"for idx, item in enumerate(results[qid]): did = item[0] score = item[1] f.write(f'{qid} Q0",
"token2id[tok] = idx corpus = [] for file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus,",
"= csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors = [] with",
"matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return vector parser = argparse.ArgumentParser()",
"token2id)) vectors_T = vectors.T manager = Manager() results = manager.dict() def run_search(idx): global",
"parser.add_argument('--threads', type=int, help='threads for hnsw', required=False, default=12) args = parser.parse_args() token2id = {}",
"token2id = {} with open(args.tokens) as tok_f: for idx, line in enumerate(tok_f): tok",
"[] for file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'):",
"data = [] for tok in tokens: if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok])",
"open(file, 'r') as f: for idx, line in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info)",
"idx, item in enumerate(results[qid]): did = item[0] score = item[1] f.write(f'{qid} Q0 {did}",
"sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result = [(ids[x], scores[x]) for x in top_idx]",
"numpy as np from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col,",
"os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r') as f:",
"total=len(topic_ids)): pass with open(args.run, 'w') as f: for qid in results: for idx,",
"= idx corpus = [] for file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file)",
"import csr_matrix from tqdm import tqdm import numpy as np from multiprocessing import",
"for i, d in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens = weight_dict.keys() col =",
"Pool(args.threads) as p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w')",
"p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w') as f:",
"token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)),",
"or file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r') as f: for idx, line in",
"csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors = [] with open(args.topics)",
"topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager = Manager()",
"[] for i, d in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens = weight_dict.keys() col",
"json.loads(line) corpus.append(info) ids = [] vectors = [] matrix_row, matrix_col, matrix_data = [],",
"[], [], [] tokens = token_dict.keys() col = [] data = [] for",
"= csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str,",
"default=12) args = parser.parse_args() token2id = {} with open(args.tokens) as tok_f: for idx,",
"vectors.T manager = Manager() results = manager.dict() def run_search(idx): global results qid =",
"qid = topic_ids[idx] t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda",
"parser.add_argument('--topics', type=str, help='path to topics with vectors', required=True) parser.add_argument('--tokens', type=str, help='path to token",
"idx, line in enumerate(tok_f): tok = line.rstrip() token2id[tok] = idx corpus = []",
"tok_f: for idx, line in enumerate(tok_f): tok = line.rstrip() token2id[tok] = idx corpus",
"shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors = [] with open(args.topics) as topic_f: for",
"manager = Manager() results = manager.dict() def run_search(idx): global results qid = topic_ids[idx]",
"weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus),",
"to token list', required=True) parser.add_argument('--run', type=str, help='path to run file', required=True) parser.add_argument('--threads', type=int,",
"required=False, default=12) args = parser.parse_args() token2id = {} with open(args.tokens) as tok_f: for",
"enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids = [] vectors = [] matrix_row, matrix_col,",
"corpus.append(info) ids = [] vectors = [] matrix_row, matrix_col, matrix_data = [], [],",
"key=lambda x: scores[x], reverse=True)[:1000] result = [(ids[x], scores[x]) for x in top_idx] results[qid]",
"in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with",
"result = [(ids[x], scores[x]) for x in top_idx] results[qid] = result with Pool(args.threads)",
"= [(ids[x], scores[x]) for x in top_idx] results[qid] = result with Pool(args.threads) as",
"matrix_col)), shape=(1, len(token2id))) return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus",
"item in enumerate(results[qid]): did = item[0] score = item[1] f.write(f'{qid} Q0 {did} {idx+1}",
"[token2id[tok] for tok in tokens] data = weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data)",
"f: for idx, line in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids = []",
"for hnsw', required=False, default=12) args = parser.parse_args() token2id = {} with open(args.tokens) as",
"[] matrix_row, matrix_col, matrix_data = [], [], [] for i, d in enumerate(tqdm(corpus)):",
"in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row,",
"= json.loads(line) corpus.append(info) ids = [] vectors = [] matrix_row, matrix_col, matrix_data =",
"= sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result = [(ids[x], scores[x]) for x in",
"result with Pool(args.threads) as p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with",
"global results qid = topic_ids[idx] t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx =",
"with vectors', required=True) parser.add_argument('--topics', type=str, help='path to topics with vectors', required=True) parser.add_argument('--tokens', type=str,",
"parser.parse_args() token2id = {} with open(args.tokens) as tok_f: for idx, line in enumerate(tok_f):",
"multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [], [],",
"topics with vectors', required=True) parser.add_argument('--tokens', type=str, help='path to token list', required=True) parser.add_argument('--run', type=str,",
"vectors_T = vectors.T manager = Manager() results = manager.dict() def run_search(idx): global results",
"for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w') as f: for",
"tokens: if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector",
"for tok in tokens] data = weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id'])",
"file = os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r')",
"vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors = []",
"= Manager() results = manager.dict() def run_search(idx): global results qid = topic_ids[idx] t_vec",
"len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids =",
"f: for qid in results: for idx, item in enumerate(results[qid]): did = item[0]",
"= vectors.T manager = Manager() results = manager.dict() def run_search(idx): global results qid",
"as f: for idx, line in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids =",
"scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result = [(ids[x],",
"= manager.dict() def run_search(idx): global results qid = topic_ids[idx] t_vec = topic_vectors[idx] scores",
"vectors', required=True) parser.add_argument('--topics', type=str, help='path to topics with vectors', required=True) parser.add_argument('--tokens', type=str, help='path",
"weight_dict = d['vector'] tokens = weight_dict.keys() col = [token2id[tok] for tok in tokens]",
"required=True) parser.add_argument('--tokens', type=str, help='path to token list', required=True) parser.add_argument('--run', type=str, help='path to run",
"[(ids[x], scores[x]) for x in top_idx] results[qid] = result with Pool(args.threads) as p:",
"Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [], [], [] tokens =",
"tok in tokens: if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col)",
"= parser.parse_args() token2id = {} with open(args.tokens) as tok_f: for idx, line in",
"= os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r') as",
"sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with open(file,",
"list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w') as f: for qid in results: for",
"topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager = Manager() results = manager.dict() def",
"* len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return vector",
"* len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids",
"vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus with vectors', required=True) parser.add_argument('--topics',",
"corpus with vectors', required=True) parser.add_argument('--topics', type=str, help='path to topics with vectors', required=True) parser.add_argument('--tokens',",
"file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r') as f: for idx, line in enumerate(tqdm(f.readlines())):",
"with open(file, 'r') as f: for idx, line in enumerate(tqdm(f.readlines())): info = json.loads(line)",
"qid in results: for idx, item in enumerate(results[qid]): did = item[0] score =",
"np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result = [(ids[x], scores[x]) for",
"from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [],",
"enumerate(tok_f): tok = line.rstrip() token2id[tok] = idx corpus = [] for file in",
"len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return vector parser",
"col = [token2id[tok] for tok in tokens] data = weight_dict.values() matrix_row.extend([i] * len(weight_dict))",
"as f: for qid in results: for idx, item in enumerate(results[qid]): did =",
"x in top_idx] results[qid] = result with Pool(args.threads) as p: for _ in",
"topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager = Manager() results = manager.dict() def run_search(idx):",
"(matrix_row, matrix_col)), shape=(1, len(token2id))) return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to",
"{} with open(args.tokens) as tok_f: for idx, line in enumerate(tok_f): tok = line.rstrip()",
"with open(args.topics) as topic_f: for line in topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'],",
"in topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager =",
"t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000]",
"scores[x]) for x in top_idx] results[qid] = result with Pool(args.threads) as p: for",
"parser.add_argument('--tokens', type=str, help='path to token list', required=True) parser.add_argument('--run', type=str, help='path to run file',",
"tok = line.rstrip() token2id[tok] = idx corpus = [] for file in sorted(os.listdir(args.corpus)):",
"[] data = [] for tok in tokens: if tok in token2id: col.append(token2id[tok])",
"line in topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager",
"import tqdm import numpy as np from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict,",
"matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return vector parser =",
"np from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data =",
"= topic_ids[idx] t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x:",
"Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [], [], [] tokens",
"Manager() results = manager.dict() def run_search(idx): global results qid = topic_ids[idx] t_vec =",
"scipy.sparse import csr_matrix from tqdm import tqdm import numpy as np from multiprocessing",
"file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r') as f: for",
"= topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result",
"help='path to token list', required=True) parser.add_argument('--run', type=str, help='path to run file', required=True) parser.add_argument('--threads',",
"as tok_f: for idx, line in enumerate(tok_f): tok = line.rstrip() token2id[tok] = idx",
"help='path to corpus with vectors', required=True) parser.add_argument('--topics', type=str, help='path to topics with vectors',",
"= [] for tok in tokens: if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0]",
"as topic_f: for line in topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T",
"len(token2id))) return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus with vectors',",
"print(f'Loading {file}') with open(file, 'r') as f: for idx, line in enumerate(tqdm(f.readlines())): info",
"for qid in results: for idx, item in enumerate(results[qid]): did = item[0] score",
"data = weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row,",
"argparse import json import os from scipy.sparse import csr_matrix from tqdm import tqdm",
"manager.dict() def run_search(idx): global results qid = topic_ids[idx] t_vec = topic_vectors[idx] scores =",
"x: scores[x], reverse=True)[:1000] result = [(ids[x], scores[x]) for x in top_idx] results[qid] =",
"tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w') as f: for qid in results:",
"info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager = Manager() results",
"required=True) parser.add_argument('--run', type=str, help='path to run file', required=True) parser.add_argument('--threads', type=int, help='threads for hnsw',",
"args = parser.parse_args() token2id = {} with open(args.tokens) as tok_f: for idx, line",
"results = manager.dict() def run_search(idx): global results qid = topic_ids[idx] t_vec = topic_vectors[idx]",
"argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus with vectors', required=True) parser.add_argument('--topics', type=str, help='path to",
"parser.add_argument('--corpus', type=str, help='path to corpus with vectors', required=True) parser.add_argument('--topics', type=str, help='path to topics",
"for line in topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T",
"file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}')",
"results[qid] = result with Pool(args.threads) as p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)):",
"import argparse import json import os from scipy.sparse import csr_matrix from tqdm import",
"csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path",
"tok in tokens] data = weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors",
"json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T = vectors.T manager = Manager() results = manager.dict()",
"results: for idx, item in enumerate(results[qid]): did = item[0] score = item[1] f.write(f'{qid}",
"= {} with open(args.tokens) as tok_f: for idx, line in enumerate(tok_f): tok =",
"= [] for file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if file.endswith('json') or",
"= [], [], [] for i, d in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens",
"idx, line in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids = [] vectors =",
"for file in sorted(os.listdir(args.corpus)): file = os.path.join(args.corpus, file) if file.endswith('json') or file.endswith('jsonl'): print(f'Loading",
"matrix_data = [], [], [] for i, d in enumerate(tqdm(corpus)): weight_dict = d['vector']",
"in results: for idx, item in enumerate(results[qid]): did = item[0] score = item[1]",
"help='path to run file', required=True) parser.add_argument('--threads', type=int, help='threads for hnsw', required=False, default=12) args",
"in tokens: if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data)",
"scores[x], reverse=True)[:1000] result = [(ids[x], scores[x]) for x in top_idx] results[qid] = result",
"parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus with vectors', required=True) parser.add_argument('--topics', type=str,",
"file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r') as f: for idx, line",
"with open(args.tokens) as tok_f: for idx, line in enumerate(tok_f): tok = line.rstrip() token2id[tok]",
"pass with open(args.run, 'w') as f: for qid in results: for idx, item",
"import json import os from scipy.sparse import csr_matrix from tqdm import tqdm import",
"topic_f: for line in topic_f: info = json.loads(line) topic_ids.append(info['id']) topic_vectors.append(token_dict_to_sparse_vector(info['vector'], token2id)) vectors_T =",
"hnsw', required=False, default=12) args = parser.parse_args() token2id = {} with open(args.tokens) as tok_f:",
"ids = [] vectors = [] matrix_row, matrix_col, matrix_data = [], [], []",
"for idx, line in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids = [] vectors",
"def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [], [], [] tokens = token_dict.keys()",
"enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens = weight_dict.keys() col = [token2id[tok] for tok in",
"for idx, line in enumerate(tok_f): tok = line.rstrip() token2id[tok] = idx corpus =",
"in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens = weight_dict.keys() col = [token2id[tok] for tok",
"= [] with open(args.topics) as topic_f: for line in topic_f: info = json.loads(line)",
"= argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus with vectors', required=True) parser.add_argument('--topics', type=str, help='path",
"[] vectors = [] matrix_row, matrix_col, matrix_data = [], [], [] for i,",
"from scipy.sparse import csr_matrix from tqdm import tqdm import numpy as np from",
"json import os from scipy.sparse import csr_matrix from tqdm import tqdm import numpy",
"type=str, help='path to corpus with vectors', required=True) parser.add_argument('--topics', type=str, help='path to topics with",
"= line.rstrip() token2id[tok] = idx corpus = [] for file in sorted(os.listdir(args.corpus)): file",
"matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = []",
"reverse=True)[:1000] result = [(ids[x], scores[x]) for x in top_idx] results[qid] = result with",
"[] for tok in tokens: if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] *",
"import os from scipy.sparse import csr_matrix from tqdm import tqdm import numpy as",
"import numpy as np from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row,",
"= [] topic_vectors = [] with open(args.topics) as topic_f: for line in topic_f:",
"to run file', required=True) parser.add_argument('--threads', type=int, help='threads for hnsw', required=False, default=12) args =",
"as np from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data",
"tokens] data = weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data,",
"vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus',",
"results qid = topic_ids[idx] t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)),",
"import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [], [], []",
"from tqdm import tqdm import numpy as np from multiprocessing import Pool, Manager",
"col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1,",
"matrix_row.extend([0] * len(col)) matrix_col.extend(col) matrix_data.extend(data) vector = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(1, len(token2id))) return",
"line.rstrip() token2id[tok] = idx corpus = [] for file in sorted(os.listdir(args.corpus)): file =",
"'r') as f: for idx, line in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids",
"token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [], [], [] tokens = token_dict.keys() col",
"len(token2id))) topic_ids = [] topic_vectors = [] with open(args.topics) as topic_f: for line",
"top_idx = sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result = [(ids[x], scores[x]) for x",
"to corpus with vectors', required=True) parser.add_argument('--topics', type=str, help='path to topics with vectors', required=True)",
"help='path to topics with vectors', required=True) parser.add_argument('--tokens', type=str, help='path to token list', required=True)",
"tokens = weight_dict.keys() col = [token2id[tok] for tok in tokens] data = weight_dict.values()",
"type=str, help='path to topics with vectors', required=True) parser.add_argument('--tokens', type=str, help='path to token list',",
"required=True) parser.add_argument('--topics', type=str, help='path to topics with vectors', required=True) parser.add_argument('--tokens', type=str, help='path to",
"d['vector'] tokens = weight_dict.keys() col = [token2id[tok] for tok in tokens] data =",
"token2id): matrix_row, matrix_col, matrix_data = [], [], [] tokens = token_dict.keys() col =",
"run file', required=True) parser.add_argument('--threads', type=int, help='threads for hnsw', required=False, default=12) args = parser.parse_args()",
"line in enumerate(tok_f): tok = line.rstrip() token2id[tok] = idx corpus = [] for",
"weight_dict.keys() col = [token2id[tok] for tok in tokens] data = weight_dict.values() matrix_row.extend([i] *",
"for tok in tokens: if tok in token2id: col.append(token2id[tok]) data.append(token_dict[tok]) matrix_row.extend([0] * len(col))",
"topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result =",
"matrix_col, matrix_data = [], [], [] tokens = token_dict.keys() col = [] data",
"top_idx] results[qid] = result with Pool(args.threads) as p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))),",
"file', required=True) parser.add_argument('--threads', type=int, help='threads for hnsw', required=False, default=12) args = parser.parse_args() token2id",
"_ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w') as f: for qid",
"csr_matrix from tqdm import tqdm import numpy as np from multiprocessing import Pool,",
"in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids = [] vectors = [] matrix_row,",
"[], [] for i, d in enumerate(tqdm(corpus)): weight_dict = d['vector'] tokens = weight_dict.keys()",
"{file}') with open(file, 'r') as f: for idx, line in enumerate(tqdm(f.readlines())): info =",
"[], [] tokens = token_dict.keys() col = [] data = [] for tok",
"topic_vectors = [] with open(args.topics) as topic_f: for line in topic_f: info =",
"def run_search(idx): global results qid = topic_ids[idx] t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0]",
"= np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x: scores[x], reverse=True)[:1000] result = [(ids[x], scores[x])",
"enumerate(results[qid]): did = item[0] score = item[1] f.write(f'{qid} Q0 {did} {idx+1} {score} bf\\n')",
"type=int, help='threads for hnsw', required=False, default=12) args = parser.parse_args() token2id = {} with",
"tqdm import numpy as np from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id):",
"matrix_col, matrix_data = [], [], [] for i, d in enumerate(tqdm(corpus)): weight_dict =",
"as p: for _ in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w') as",
"= [token2id[tok] for tok in tokens] data = weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col)",
"matrix_row, matrix_col, matrix_data = [], [], [] tokens = token_dict.keys() col = []",
"shape=(1, len(token2id))) return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus with",
"open(args.tokens) as tok_f: for idx, line in enumerate(tok_f): tok = line.rstrip() token2id[tok] =",
"= d['vector'] tokens = weight_dict.keys() col = [token2id[tok] for tok in tokens] data",
"in tqdm(p.imap_unordered(run_search, list(range(len(topic_ids)))), total=len(topic_ids)): pass with open(args.run, 'w') as f: for qid in",
"tqdm import tqdm import numpy as np from multiprocessing import Pool, Manager def",
"if file.endswith('json') or file.endswith('jsonl'): print(f'Loading {file}') with open(file, 'r') as f: for idx,",
"required=True) parser.add_argument('--threads', type=int, help='threads for hnsw', required=False, default=12) args = parser.parse_args() token2id =",
"= weight_dict.keys() col = [token2id[tok] for tok in tokens] data = weight_dict.values() matrix_row.extend([i]",
"info = json.loads(line) corpus.append(info) ids = [] vectors = [] matrix_row, matrix_col, matrix_data",
"line in enumerate(tqdm(f.readlines())): info = json.loads(line) corpus.append(info) ids = [] vectors = []",
"= [] vectors = [] matrix_row, matrix_col, matrix_data = [], [], [] for",
"= token_dict.keys() col = [] data = [] for tok in tokens: if",
"in tokens] data = weight_dict.values() matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors =",
"type=str, help='path to token list', required=True) parser.add_argument('--run', type=str, help='path to run file', required=True)",
"in enumerate(results[qid]): did = item[0] score = item[1] f.write(f'{qid} Q0 {did} {idx+1} {score}",
"list', required=True) parser.add_argument('--run', type=str, help='path to run file', required=True) parser.add_argument('--threads', type=int, help='threads for",
"matrix_row.extend([i] * len(weight_dict)) matrix_col.extend(col) matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id)))",
"matrix_row, matrix_col, matrix_data = [], [], [] for i, d in enumerate(tqdm(corpus)): weight_dict",
"[] topic_vectors = [] with open(args.topics) as topic_f: for line in topic_f: info",
"run_search(idx): global results qid = topic_ids[idx] t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx",
"topic_ids[idx] t_vec = topic_vectors[idx] scores = np.array(t_vec.dot(vectors_T).todense())[0] top_idx = sorted(range(len(scores)), key=lambda x: scores[x],",
"matrix_data.extend(data) ids.append(d['id']) vectors = csr_matrix((matrix_data, (matrix_row, matrix_col)), shape=(len(corpus), len(token2id))) topic_ids = [] topic_vectors",
"return vector parser = argparse.ArgumentParser() parser.add_argument('--corpus', type=str, help='path to corpus with vectors', required=True)"
] |
[] |
[
"parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted function for p in",
"= numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted function for p in parts:",
"between 0 and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only in",
"parts: p.x = numpy.random.random() * domain p.y = numpy.random.random() * domain p.z =",
"def create_n_random_particles(n, m, domain=1): ''' Creates `n` particles with mass `m` with random",
"`domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted function for",
"coordinates between 0 and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only",
"#attribute access only in @jitted function for p in parts: p.x = numpy.random.random()",
"= numpy.random.random() * domain p.z = numpy.random.random() * domain p.m = m p.phi",
"numpy.random.random() * domain p.z = numpy.random.random() * domain p.m = m p.phi =",
"with random coordinates between 0 and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute",
"Creates `n` particles with mass `m` with random coordinates between 0 and `domain`",
"domain p.z = numpy.random.random() * domain p.m = m p.phi = 0 return",
"0 and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted",
"with mass `m` with random coordinates between 0 and `domain` ''' parts =",
"numpy.random.random() * domain p.y = numpy.random.random() * domain p.z = numpy.random.random() * domain",
"dtype=particle_dtype) #attribute access only in @jitted function for p in parts: p.x =",
"particles with mass `m` with random coordinates between 0 and `domain` ''' parts",
"p.z = numpy.random.random() * domain p.m = m p.phi = 0 return parts",
"@jitted function for p in parts: p.x = numpy.random.random() * domain p.y =",
"@njit def create_n_random_particles(n, m, domain=1): ''' Creates `n` particles with mass `m` with",
"numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted function for p in parts: p.x",
"p in parts: p.x = numpy.random.random() * domain p.y = numpy.random.random() * domain",
"mass `m` with random coordinates between 0 and `domain` ''' parts = numpy.zeros((n),",
"''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted function for p",
"only in @jitted function for p in parts: p.x = numpy.random.random() * domain",
"for p in parts: p.x = numpy.random.random() * domain p.y = numpy.random.random() *",
"function for p in parts: p.x = numpy.random.random() * domain p.y = numpy.random.random()",
"p.y = numpy.random.random() * domain p.z = numpy.random.random() * domain p.m = m",
"m, domain=1): ''' Creates `n` particles with mass `m` with random coordinates between",
"`m` with random coordinates between 0 and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype)",
"''' Creates `n` particles with mass `m` with random coordinates between 0 and",
"random coordinates between 0 and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access",
"p.x = numpy.random.random() * domain p.y = numpy.random.random() * domain p.z = numpy.random.random()",
"= numpy.random.random() * domain p.y = numpy.random.random() * domain p.z = numpy.random.random() *",
"in @jitted function for p in parts: p.x = numpy.random.random() * domain p.y",
"* domain p.z = numpy.random.random() * domain p.m = m p.phi = 0",
"domain=1): ''' Creates `n` particles with mass `m` with random coordinates between 0",
"`n` particles with mass `m` with random coordinates between 0 and `domain` '''",
"create_n_random_particles(n, m, domain=1): ''' Creates `n` particles with mass `m` with random coordinates",
"in parts: p.x = numpy.random.random() * domain p.y = numpy.random.random() * domain p.z",
"access only in @jitted function for p in parts: p.x = numpy.random.random() *",
"* domain p.y = numpy.random.random() * domain p.z = numpy.random.random() * domain p.m",
"and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted function",
"domain p.y = numpy.random.random() * domain p.z = numpy.random.random() * domain p.m ="
] |
[
"ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean =",
"perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar",
"statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans",
"# ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1.",
"perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy",
"def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum()",
"ans=dict() # use observed dispersion rather than statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0]",
"import copy def clipmean_one(y,ivar,mask,nsig=3): w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy =",
"in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar =",
"ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean",
"def clipmean_one(y,ivar,mask,nsig=3): w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0,",
"in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans",
"w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def",
"ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k in",
"ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b in newy.keys():",
"ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for",
"ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar =",
"y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean",
"return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b in",
"for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in",
"b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy = numpy.convolve(y[b]*ivar[b],ncon,mode='valid') newy = newy/newivar newmask=numpy.convolve(mask[b],ncon,mode='valid') return perres_SN(y,ivar,mask,nsig=nsig)",
"k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar",
"ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar =",
"<filename>desidiff/src/scores.py import numpy import copy def clipmean_one(y,ivar,mask,nsig=3): w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean =",
"ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10):",
"def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion rather than statistical for k in",
"refmask): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar",
"return ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar",
"ans = copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict()",
"numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum() ansmean =",
"ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y)",
"ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b",
"def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean =",
"k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return",
"observed dispersion rather than statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std #",
"newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy = numpy.convolve(y[b]*ivar[b],ncon,mode='valid') newy",
"k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10):",
"= ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar",
"ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar,",
"import numpy import copy def clipmean_one(y,ivar,mask,nsig=3): w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar",
"ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for",
"= numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans",
"w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict()",
"in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0]",
"y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def",
"numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3):",
"ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion rather than statistical for k",
"for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0]",
"dispersion rather than statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w])",
"ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon =",
"ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean",
"for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def",
"ncon = numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy = numpy.convolve(y[b]*ivar[b],ncon,mode='valid') newy =",
"than statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return",
"ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0]",
"rather than statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum()",
"ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar =",
"newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar",
"# use observed dispersion rather than statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std()",
"ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar)",
"y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar)",
"w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask)",
"copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k",
"ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() #",
"= numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy = numpy.convolve(y[b]*ivar[b],ncon,mode='valid') newy = newy/newivar",
"ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion",
"numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig)",
"ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0]",
"= copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for",
"ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict()",
"numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy = numpy.convolve(y[b]*ivar[b],ncon,mode='valid') newy = newy/newivar newmask=numpy.convolve(mask[b],ncon,mode='valid')",
"nsig]))[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans =",
"w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) <",
"< nsig]))[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans",
"return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return",
"refivar, refmask): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean =",
"= y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return",
"newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy =",
"refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed",
"y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans",
"ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return",
"ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum()",
"copy def clipmean_one(y,ivar,mask,nsig=3): w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean",
"w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy,",
"k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys():",
"for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston",
"std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon",
"w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean",
"use observed dispersion rather than statistical for k in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std",
"return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion rather than statistical for",
"= numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar = ivar[w].sum() ansmean",
"numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k in",
"ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar",
"return ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum()",
"ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion rather than statistical",
"= numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k",
"numpy import copy def clipmean_one(y,ivar,mask,nsig=3): w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy",
"clipmean_one(y,ivar,mask,nsig=3): w=numpy.where(mask==0)[0] ansivar = ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar))",
"for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy = numpy.convolve(y[b]*ivar[b],ncon,mode='valid') newy = newy/newivar newmask=numpy.convolve(mask[b],ncon,mode='valid') return",
"= ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for",
"def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y) newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid')",
"= refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use",
"numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion rather than",
"= ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar newy = y-ansmean w=numpy.where(numpy.logical_and.reduce([mask==0, numpy.abs(newy*numpy.sqrt(ivar)) < nsig]))[0] ansivar",
"= ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar, refmask):",
"perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion rather than statistical for k in y.keys():",
"ston=numpy.abs(ansmean)*numpy.sqrt(ansivar) ans[k]=ston return ans def perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k in y.keys():",
"ans def perband_SN(y,ivar,mask,nsig=10): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean",
"ivar[w].sum() ansmean = numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k",
"perband_increase(y,ivar,mask,refy, refivar, refmask): ans=dict() for k in y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean",
"= numpy.sum(y[w]*ivar[w])/ansivar return y-ansmean def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k in ans.keys():",
"y.keys(): w=numpy.where(mask[k]==0)[0] ansivar = ivar[k][w].sum() ansmean = numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum()",
"newivar=dict(ivar) newmask=dict(mask) ncon = numpy.zeros(ncon)+1. for b in newy.keys(): newivar=numpy.convolve(ivar[b],ncon,mode='valid') newy = numpy.convolve(y[b]*ivar[b],ncon,mode='valid')",
"def clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def",
"in y.keys(): w=numpy.where(mask[k]==0)[0] std=y[k][w].std() ston=numpy.abs(y[k][w])/std # ston=numpy.abs(y[k][w])*numpy.sqrt(ivar[k][w]) ans[k]=(ston>10).sum() return ans def perconv_SN(y,ivar,mask,ncon=3,nsig=10): newy=dict(y)",
"clipmean(y,ivar,mask,nsig=3): ans = copy.deepcopy(y) for k in ans.keys(): ans[k]=clipmean_one(y[k],ivar[k],mask[k],nsig=nsig) return ans def perband_SN(y,ivar,mask,nsig=10):",
"numpy.sum(y[k][w]*ivar[k][w])/ansivar ans[k]=ansmean w=numpy.where(refmask[k]==0)[0] ansivar = refivar[k][w].sum() ansmean = numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def",
"= numpy.sum(refy[k][w]*refivar[k][w])/ansivar ans[k]=ans[k]/ansmean return ans def perres_SN(y,ivar,mask,nsig=10): ans=dict() # use observed dispersion rather"
] |
[
"while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata: # print",
"text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text in zip(a,data): text=text.split() i=0",
"data.append(strtemp) strtemp=\"\" var=query fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for",
") : i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0):",
"k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata: # print (x) return newdata def",
"fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0",
"text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text in",
"= csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 =",
"fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i < len(temp12)-1): templist=[] if ( temp12[i]==\"-1\"",
"csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline()",
"newdata: # print (x) return newdata def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except",
"if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL', '",
"list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL', ' Label Weight', 'Esemble Weight','ML",
"strtemp=\"\" var=query fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y",
"strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata:",
"['Label', 'URL', ' Label Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f:",
"for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i <",
"swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0 and",
"a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\")",
"text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2])))",
"while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\"",
"#for x in newdata: # print (x) return newdata def read_from_file(): try: fin",
", re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page , re.IGNORECASE) ) )",
"page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page , re.IGNORECASE) )",
"min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and",
"fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i < len(temp12)-1): templist=[] if (",
"csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\")",
"re import csv data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4]",
"#word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) : word1=words[i] i=i+1 if word1 not in a:",
"= open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words)",
") : word1=words[i] i=i+1 if word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W'",
"elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0",
",\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) : word1=words[i] i=i+1 if",
"requests import re import csv data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2]",
"int(text[j+6]) !=0 and int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2])",
"'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header)",
"print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL', ' Label Weight', 'Esemble",
"import csv data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5]",
"!=0 and int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2]) <",
"swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for",
"x in newdata: # print (x) return newdata def read_from_file(): try: fin =",
"while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query",
"learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for url in",
"\"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1",
"templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label',",
"return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\")",
"): swap(text,j) elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2]) < int(text[j+7]) + int(text[j+6]) +",
"while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]),",
"int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2]) < int(text[j+7]) +",
"header = ['Label', 'URL', ' Label Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt')",
"+ \"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1):",
"page=requests.get(url).text except : test=0 if test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page ,",
"regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\") print(word1)",
"print(word1) for url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except :",
"text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text in zip(a,data):",
"k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata: #",
"(x) return newdata def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0",
"except : return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"): query=fin.readline()",
"strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata: # print (x)",
"read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query",
"strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata: # print (x) return newdata def read_from_file():",
"while( i < len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2",
"#fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2)",
"elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0",
"search import requests import re import csv data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j]",
"def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3",
"in newdata: # print (x) return newdata def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\")",
"write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\")",
"open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0",
"not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine learning\"",
"if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or",
"data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7]",
"import requests import re import csv data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1]",
"var=query while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp)",
"and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close()",
"temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for",
"if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except : test=0 if test!=0 : print(url) fout.write(url) fout.write(\"\\n\")",
"int(text[j+3]) + int(text[j+1]) + int(text[j+2]) < int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j)",
"csv data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6]",
"read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #----------------------------------",
"i < len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2 else:",
"fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data):",
"regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for url",
"temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2])",
") ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) ) ) fout.write(\"",
") ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) ) ) fout.write(\" \")",
") ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page , re.IGNORECASE) ) ) ) fout.write(\"\\n\") fout.write(\"-1\\n\")",
"#set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) :",
"return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\")",
"strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return 1 read_from_file()",
"set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) : word1=words[i]",
"\"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for url in search(query, tld='com', stop=10):",
"temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[]",
"int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0 ) ): swap(text,j)",
"strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query):",
"templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #-------------------------------------------------------------------",
"query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var)",
"except : test=0 if test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE)",
"while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )):",
") ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page , re.IGNORECASE) ) ) ) fout.write(\"\\n\")",
"text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0",
"def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\")",
"return newdata def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline()",
"text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5):",
"stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except : test=0 if test!=0 : print(url) fout.write(url)",
"< len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split()",
"1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y)",
"or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0 ) ): swap(text,j) elif(",
"text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4):",
"in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i < len(temp12)-1): templist=[]",
"min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6])",
",\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) : word1=words[i] i=i+1 if word1 not",
"\") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page ,",
"zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]),",
"+ int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\"",
"word1=words[i] i=i+1 if word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" +",
"with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header",
"csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2",
"from googlesearch import search import requests import re import csv data=[] a=[] student=\"Mam\"",
"and int(text[j+6]) !=0 and int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3]) + int(text[j+1]) +",
"query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return 1 read_from_file() data=sort_urls(data)",
"while(i<len(words) ) : word1=words[i] i=i+1 if word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine",
"(int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3]) + int(text[j+1])",
": print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) ) ) fout.write(\" \")",
"temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data):",
"int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\"",
"query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout=",
"temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if",
"w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2",
"# print (x) return newdata def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except :",
"+ int(text[j+2]) < int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\"",
"Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) #",
"elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2]) < int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ):",
"min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and",
"= ['Label', 'URL', ' Label Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as",
"templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\")",
"data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y",
")): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0",
"' Label Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer =",
"query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\")",
"temp12=y temp12=temp12.splitlines() i=0 while( i < len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\"",
"fout.write(word1+\"\\n\") print(word1) for url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except",
"try: page=requests.get(url).text except : test=0 if test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page",
"zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i < len(temp12)-1): templist=[] if",
"in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if(",
"words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) : word1=words[i] i=i+1 if word1 not in",
"newdata def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline() strtemp=\"\"",
"text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text in zip(a,data): text=text.split()",
"'wt') as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1",
"\"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata: # print (x) return",
"tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except : test=0 if test!=0 : print(url)",
", re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) )",
"< int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3):",
"min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0",
"for word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j)",
"int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3])",
"or temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist)",
"a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1",
": i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): #",
"student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2",
"if word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" +",
"fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page ,",
"else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist)",
"quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline()",
"f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\")",
"x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i < len(temp12)-1):",
"query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return",
"print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2,",
") ): swap(text,j) elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2]) < int(text[j+7]) + int(text[j+6])",
"int(text[j+2]) < int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0",
"( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1])",
"(int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL', ' Label",
"search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except : test=0 if test!=0 :",
"test=1 try: page=requests.get(url).text except : test=0 if test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1,",
"swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or",
"csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\")",
"#---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i < len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or",
"+ int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4",
"test=0 if test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) )",
"if test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) ) )",
"fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page , re.IGNORECASE)",
"as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1) #fin1 =",
"+ \"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for url in search(query, tld='com',",
"if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j)",
"open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"):",
"text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def sort_urls(data): newdata=[] for word,text",
"0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline()",
"< min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0",
"#print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL',",
"#print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL', ' Label Weight', 'Esemble Weight','ML Weight'] with",
"sort_urls(data): newdata=[] for word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5])",
"\"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in newdata: # print (x) return newdata",
"templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header =",
"url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except : test=0 if",
"query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close()",
"newdata.append(strtemp) #for x in newdata: # print (x) return newdata def read_from_file(): try:",
"fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a)",
"and int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2]) < int(text[j+7])",
"word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine",
"): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif( int(text[j+3])==0",
"temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4 def",
"word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])):",
"templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header",
"header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\"",
"for url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except : test=0",
"fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query",
"a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[]",
"Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write",
"i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL', ' Label Weight', 'Esemble Weight','ML Weight']",
"newdata=[] for word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ):",
") fout.write(\" \") fout.write(str(len(re.findall(regex3, page , re.IGNORECASE) ) ) ) fout.write(\"\\n\") fout.write(\"-1\\n\") fout.write(\"-2\\n\")",
"#print(a) while(i<len(words) ) : word1=words[i] i=i+1 if word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W'",
"len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split() templist.append(x)",
"def sort_urls(data): newdata=[] for word,text in zip(a,data): text=text.split() i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if(",
"list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while( i",
"i=0 #print(a) while(i<len(words) ) : word1=words[i] i=i+1 if word1 not in a: regex1='\\W'+word1+'\\W'",
"learning\" ' fout.write(word1+\"\\n\") print(word1) for url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try:",
"re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) ) )",
"i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0]) templist.append(w8[1]) templist.append(w8[2]) #print(templist) if (int(w8[0])!=0): # print(w8[0])",
"re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page , re.IGNORECASE) ) ) )",
"fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3, page",
": word1=words[i] i=i+1 if word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\"",
"j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x",
"'URL', ' Label Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer",
"#set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) : word1=words[i] i=i+1",
"test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) ) ) fout.write(\"",
"Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL)",
"open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL) csv_writer.writerow(header) # write header csv_writer.writerows(list_1)",
"regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for",
"swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3] text[j]=text[j+4] text[j+1]=text[j+5] text[j+2]=text[j+6] text[j+3]=text[j+7] text[j+4]=temp1 text[j+5]=temp2 text[j+6]=temp3 text[j+7]=temp4",
"open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines() i=0 while(",
": test=0 if test!=0 : print(url) fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) )",
"and (int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0 ) ): swap(text,j) elif( int(text[j+3]) +",
"var=query fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in",
"temp12=temp12.splitlines() i=0 while( i < len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" )",
"set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) ) : word1=words[i] i=i+1 if word1",
"#------------------------------------------------------------------- header = ['Label', 'URL', ' Label Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv',",
"j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5]))",
"in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\" + \"machine learning\" '",
"i=0 while( i < len(temp12)-1): templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) :",
"= open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\")",
"int(text[j+1]) + int(text[j+2]) < int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4",
"swap(text,j) elif( int(text[j+3]) + int(text[j+1]) + int(text[j+2]) < int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0",
"open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\" ,\") set2=set2.split(\" ,\") words=list(set2) #word1=word1.replace(\"\\n\",\"\") i=0 #print(a) while(i<len(words) )",
"int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\"",
"int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) < min(int(text[j+7]), min(int(text[j+6]),int(text[j+5])) )): swap(text,j) elif(",
"googlesearch import search import requests import re import csv data=[] a=[] student=\"Mam\" def",
"import re import csv data=[] a=[] student=\"Mam\" def swap(text,j): temp1=text[j] temp2=text[j+1] temp3=text[j+2] temp4=text[j+3]",
"+ int(text[j+1]) + int(text[j+2]) < int(text[j+7]) + int(text[j+6]) + int(text[j+5])!=0 ): swap(text,j) j=j+4",
"# write header csv_writer.writerows(list_1) #fin1 = open(\"Experiment2/Results(Mam).txt\",\"r\") fin2 = open(\"Experiment2/Results(\"+student+\").txt\",\"r\") #set1=fin1.readline() set2=fin2.readline() #set1=set1.split(\"",
"import search import requests import re import csv data=[] a=[] student=\"Mam\" def swap(text,j):",
"' fout.write(word1+\"\\n\") print(word1) for url in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text",
") fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex3,",
"in search(query, tld='com', stop=10): if(url.find(\".pdf\",len(url)-5)==-1): test=1 try: page=requests.get(url).text except : test=0 if test!=0",
"i=0 while(i<len(text)-4): j=0 while(j<len(text)-5): if( int(text[j+1])<int(text[j+5]) ): swap(text,j) elif(int(text[j+1])==int(text[j+5])): if( min(int(text[j+3]), min(int(text[j+1]),int(text[j+2]))) <",
"try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query):",
"or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0 ) ):",
"): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp)",
": return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and query!=\"-1\"): query=fin.readline() strtemp+=query",
"query=fin.readline() strtemp+=query query=query.replace(\"\\n\",\"\") query=fin.readline() query=query.replace(\"\\n\",\"\") if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return 1",
"if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i]) templist.append(w8[0])",
"# print(w8[0]) list_1.append(templist) i=i+2 #print(\"\\n\") #------------------------------------------------------------------- header = ['Label', 'URL', ' Label Weight',",
"fout.write(url) fout.write(\"\\n\") fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page",
"templist=[] if ( temp12[i]==\"-1\" or temp12[i+1]==\"-1\" ) : i=i+2 else: w8=temp12[i+1].split() templist.append(x) templist.append(temp12[i])",
"= open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return 0 query=fin.readline() strtemp=\"\" query=query.replace(\"\\n\",\"\") var=query while(query): while(query and",
"open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\") list_1=[] for x,y in zip(a,data): fout.write(x+\"\\n\") fout.write(y) #---------------------------------- temp12=y temp12=temp12.splitlines()",
"fout.write(str(len(re.findall(regex1, page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE)",
"print (x) return newdata def read_from_file(): try: fin = open(\"Experiment2/urlw8\"+student+\"new.txt\") except : return",
"Label Weight', 'Esemble Weight','ML Weight'] with open('Experiment2/'+student+'new.csv', 'wt') as f: csv_writer = csv.writer(f,",
"i=i+1 if word1 not in a: regex1='\\W'+word1+'\\W' regex2='\\Wensemble\\W' regex3='\\Wmachine learning\\W' query='\"'+word1+'\" + \"ensemble\"",
"query='\"'+word1+'\" + \"ensemble\" + \"machine learning\" ' fout.write(word1+\"\\n\") print(word1) for url in search(query,",
"page , re.IGNORECASE) ) ) ) fout.write(\" \") fout.write(str(len(re.findall(regex2, page , re.IGNORECASE) )",
"i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\" newdata.append(strtemp) #for x in",
"int(text[j+3])==0 or int(text[j+1])==0 or int(text[j+2])==0 and (int(text[j+7])!=0 and int(text[j+6]) !=0 and int(text[j+5])!=0 )",
"if(query): a.append(var) data.append(strtemp) strtemp=\"\" var=query fin.close() return 1 read_from_file() data=sort_urls(data) open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\").close() fout= open(\"Experiment2/urlw8\"+student+\"new.txt\",\"w\")",
"int(text[j+5])!=0 ): swap(text,j) j=j+4 i=i+4 strtemp=\"\" k=0 while(k<len(text)-3): strtemp+=text[k]+\"\\n\"+text[k+1]+\" \"+text[k+2]+\" \"+text[k+3]+\"\\n\" k=k+4 strtemp=strtemp+\"-1\\n\""
] |
[
"tag.startswith('NN'): print(word) if item[1] < freq: return freq = item[1] # no appropriate",
"no_pun_text = article _punctuation = string.punctuation.replace('\\'', '') # delete punctuation except ''' for",
"pun in _punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records = dict()",
"not freq: print(items[0][0]) def process_file(filename): with open(filename, 'r') as file: article = file.read()",
"for pun in _punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records =",
"delete punctuation except ''' for pun in _punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text",
"file.read() no_pun_text = article _punctuation = string.punctuation.replace('\\'', '') # delete punctuation except '''",
"for item in items: word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1]",
"'have' elif parts[1] == 'll': parts[1] = 'will' elif parts[1] == 'd': if",
"== 't': parts[1] = 'not' elif parts[1] == 've': parts[1] = 'have' elif",
"'ve': parts[1] = 'have' elif parts[1] == 'll': parts[1] = 'will' elif parts[1]",
"word like: it's => it is def extend_word(text): if text.find('\\'') > 0: old2new",
"text.find('\\'') > 0: old2new = dict() words = text.split() for word in words:",
"changed items = sorted(records.items(), key=return_order_key, reverse=True) # frequency of word freq = 0",
"no appropriate word found if not freq: print(items[0][0]) def process_file(filename): with open(filename, 'r')",
"string.punctuation.replace('\\'', '') # delete punctuation except ''' for pun in _punctuation: no_pun_text =",
"parts[1] = 'have' elif parts[1] == 'll': parts[1] = 'will' elif parts[1] ==",
"import nltk import string import os # simply extend word like: it's =>",
"item[1] < freq: return freq = item[1] # no appropriate word found if",
"'is' elif parts[1] == 're': parts[1] = 'are' elif parts[1] == 't': parts[1]",
"extend_word(no_pun_text) records = dict() for word in complete_text.lower().split(): records[word] = records.get(word, 0) +",
"old2new[old_word]) return _text def return_order_key(record): return record[1] def show_important_word(records): # only this function",
"== 'd': if words[words.index(word) + 1] == 'better': parts[1] = 'had' else: parts[1]",
"parts[1] == 'm': parts[1] = 'am' elif parts[1] == 's': parts[1] = 'is'",
"elif parts[1] == 's': parts[1] = 'is' elif parts[1] == 're': parts[1] =",
"if item[1] < freq: return freq = item[1] # no appropriate word found",
"items: word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1] < freq: return",
"tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1] < freq: return freq =",
"== 'll': parts[1] = 'will' elif parts[1] == 'd': if words[words.index(word) + 1]",
"return record[1] def show_important_word(records): # only this function was changed items = sorted(records.items(),",
"sorted(records.items(), key=return_order_key, reverse=True) # frequency of word freq = 0 for item in",
"freq = item[1] # no appropriate word found if not freq: print(items[0][0]) def",
"= sorted(records.items(), key=return_order_key, reverse=True) # frequency of word freq = 0 for item",
"records = dict() for word in complete_text.lower().split(): records[word] = records.get(word, 0) + 1",
"_text def return_order_key(record): return record[1] def show_important_word(records): # only this function was changed",
"'will' elif parts[1] == 'd': if words[words.index(word) + 1] == 'better': parts[1] =",
"if parts[1] == 'm': parts[1] = 'am' elif parts[1] == 's': parts[1] =",
"= no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records = dict() for word in complete_text.lower().split():",
"'d': if words[words.index(word) + 1] == 'better': parts[1] = 'had' else: parts[1] =",
"parts[1] = 'is' elif parts[1] == 're': parts[1] = 'are' elif parts[1] ==",
"parts[1] = 'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] = ' '.join(parts) _text",
"parts[1] == 've': parts[1] = 'have' elif parts[1] == 'll': parts[1] = 'will'",
"# no appropriate word found if not freq: print(items[0][0]) def process_file(filename): with open(filename,",
"= string.punctuation.replace('\\'', '') # delete punctuation except ''' for pun in _punctuation: no_pun_text",
"= dict() for word in complete_text.lower().split(): records[word] = records.get(word, 0) + 1 print('='*30)",
"filename) print('-'*20) show_important_word(records) def process_files(path='.'): files = os.listdir(path) for file in files: if",
"parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] = ' '.join(parts) _text = text for old_word",
"= 0 for item in items: word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word)",
"word in complete_text.lower().split(): records[word] = records.get(word, 0) + 1 print('='*30) print('current file:', filename)",
"'had' else: parts[1] = 'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] = '",
"+ 1 print('='*30) print('current file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'): files = os.listdir(path)",
"# simply extend word like: it's => it is def extend_word(text): if text.find('\\'')",
"'not' elif parts[1] == 've': parts[1] = 'have' elif parts[1] == 'll': parts[1]",
"print('-'*20) show_important_word(records) def process_files(path='.'): files = os.listdir(path) for file in files: if file.endswith('.txt'):",
"if word.find('\\'') > 0: parts = word.split('\\'') if parts[1] == 'm': parts[1] =",
"'re': parts[1] = 'are' elif parts[1] == 't': parts[1] = 'not' elif parts[1]",
"complete_text.lower().split(): records[word] = records.get(word, 0) + 1 print('='*30) print('current file:', filename) print('-'*20) show_important_word(records)",
"== 'm': parts[1] = 'am' elif parts[1] == 's': parts[1] = 'is' elif",
"= item[1] # no appropriate word found if not freq: print(items[0][0]) def process_file(filename):",
"= parts[0][:-1] old2new[word] = ' '.join(parts) _text = text for old_word in old2new.keys():",
"old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return _text def return_order_key(record): return record[1] def show_important_word(records):",
"parts[0] = parts[0][:-1] old2new[word] = ' '.join(parts) _text = text for old_word in",
"it is def extend_word(text): if text.find('\\'') > 0: old2new = dict() words =",
"# frequency of word freq = 0 for item in items: word, tag",
"item in items: word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1] <",
"_punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records = dict() for word",
"if words[words.index(word) + 1] == 'better': parts[1] = 'had' else: parts[1] = 'would'",
"'ll': parts[1] = 'will' elif parts[1] == 'd': if words[words.index(word) + 1] ==",
"function was changed items = sorted(records.items(), key=return_order_key, reverse=True) # frequency of word freq",
"print('current file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'): files = os.listdir(path) for file in",
"item[1] # no appropriate word found if not freq: print(items[0][0]) def process_file(filename): with",
"word.find('\\'') > 0: parts = word.split('\\'') if parts[1] == 'm': parts[1] = 'am'",
"for old_word in old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return _text def return_order_key(record): return",
"'better': parts[1] = 'had' else: parts[1] = 'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1]",
"= 'have' elif parts[1] == 'll': parts[1] = 'will' elif parts[1] == 'd':",
"if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] = ' '.join(parts) _text = text for",
"' '.join(parts) _text = text for old_word in old2new.keys(): _text = _text.replace(old_word, old2new[old_word])",
"appropriate word found if not freq: print(items[0][0]) def process_file(filename): with open(filename, 'r') as",
"= extend_word(no_pun_text) records = dict() for word in complete_text.lower().split(): records[word] = records.get(word, 0)",
"show_important_word(records) def process_files(path='.'): files = os.listdir(path) for file in files: if file.endswith('.txt'): process_file(os.path.join(path,",
"= records.get(word, 0) + 1 print('='*30) print('current file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'):",
"= 'am' elif parts[1] == 's': parts[1] = 'is' elif parts[1] == 're':",
"complete_text = extend_word(no_pun_text) records = dict() for word in complete_text.lower().split(): records[word] = records.get(word,",
"parts[1] == 'll': parts[1] = 'will' elif parts[1] == 'd': if words[words.index(word) +",
"words: if word.find('\\'') > 0: parts = word.split('\\'') if parts[1] == 'm': parts[1]",
"parts[1] = 'had' else: parts[1] = 'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word]",
"0) + 1 print('='*30) print('current file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'): files =",
"word.split('\\'') if parts[1] == 'm': parts[1] = 'am' elif parts[1] == 's': parts[1]",
"''' for pun in _punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records",
"as file: article = file.read() no_pun_text = article _punctuation = string.punctuation.replace('\\'', '') #",
"records.get(word, 0) + 1 print('='*30) print('current file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'): files",
"= nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1] < freq: return freq = item[1]",
"print('='*30) print('current file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'): files = os.listdir(path) for file",
"return_order_key(record): return record[1] def show_important_word(records): # only this function was changed items =",
"1 print('='*30) print('current file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'): files = os.listdir(path) for",
"is def extend_word(text): if text.find('\\'') > 0: old2new = dict() words = text.split()",
"import os # simply extend word like: it's => it is def extend_word(text):",
"> 0: parts = word.split('\\'') if parts[1] == 'm': parts[1] = 'am' elif",
"for word in words: if word.find('\\'') > 0: parts = word.split('\\'') if parts[1]",
"_text.replace(old_word, old2new[old_word]) return _text def return_order_key(record): return record[1] def show_important_word(records): # only this",
"import string import os # simply extend word like: it's => it is",
"in words: if word.find('\\'') > 0: parts = word.split('\\'') if parts[1] == 'm':",
"in items: word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1] < freq:",
"+ 1] == 'better': parts[1] = 'had' else: parts[1] = 'would' if parts[0].endswith('n'):",
"= 'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] = ' '.join(parts) _text =",
"old2new[word] = ' '.join(parts) _text = text for old_word in old2new.keys(): _text =",
"<filename>A1014280203/6/6.py import nltk import string import os # simply extend word like: it's",
"word in words: if word.find('\\'') > 0: parts = word.split('\\'') if parts[1] ==",
"elif parts[1] == 'd': if words[words.index(word) + 1] == 'better': parts[1] = 'had'",
"'s': parts[1] = 'is' elif parts[1] == 're': parts[1] = 'are' elif parts[1]",
"if not freq: print(items[0][0]) def process_file(filename): with open(filename, 'r') as file: article =",
"string import os # simply extend word like: it's => it is def",
"items = sorted(records.items(), key=return_order_key, reverse=True) # frequency of word freq = 0 for",
"frequency of word freq = 0 for item in items: word, tag =",
"return freq = item[1] # no appropriate word found if not freq: print(items[0][0])",
"'m': parts[1] = 'am' elif parts[1] == 's': parts[1] = 'is' elif parts[1]",
"'r') as file: article = file.read() no_pun_text = article _punctuation = string.punctuation.replace('\\'', '')",
"= text.split() for word in words: if word.find('\\'') > 0: parts = word.split('\\'')",
"only this function was changed items = sorted(records.items(), key=return_order_key, reverse=True) # frequency of",
"extend_word(text): if text.find('\\'') > 0: old2new = dict() words = text.split() for word",
"reverse=True) # frequency of word freq = 0 for item in items: word,",
"= word.split('\\'') if parts[1] == 'm': parts[1] = 'am' elif parts[1] == 's':",
"words[words.index(word) + 1] == 'better': parts[1] = 'had' else: parts[1] = 'would' if",
"= _text.replace(old_word, old2new[old_word]) return _text def return_order_key(record): return record[1] def show_important_word(records): # only",
"no_pun_text = no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records = dict() for word in",
"0: old2new = dict() words = text.split() for word in words: if word.find('\\'')",
"open(filename, 'r') as file: article = file.read() no_pun_text = article _punctuation = string.punctuation.replace('\\'',",
"parts[1] == 's': parts[1] = 'is' elif parts[1] == 're': parts[1] = 'are'",
"words = text.split() for word in words: if word.find('\\'') > 0: parts =",
"article _punctuation = string.punctuation.replace('\\'', '') # delete punctuation except ''' for pun in",
"dict() for word in complete_text.lower().split(): records[word] = records.get(word, 0) + 1 print('='*30) print('current",
"found if not freq: print(items[0][0]) def process_file(filename): with open(filename, 'r') as file: article",
"# delete punctuation except ''' for pun in _punctuation: no_pun_text = no_pun_text.replace(pun, '')",
"file: article = file.read() no_pun_text = article _punctuation = string.punctuation.replace('\\'', '') # delete",
"= 'will' elif parts[1] == 'd': if words[words.index(word) + 1] == 'better': parts[1]",
"== 've': parts[1] = 'have' elif parts[1] == 'll': parts[1] = 'will' elif",
"parts[1] = 'am' elif parts[1] == 's': parts[1] = 'is' elif parts[1] ==",
"= 'is' elif parts[1] == 're': parts[1] = 'are' elif parts[1] == 't':",
"was changed items = sorted(records.items(), key=return_order_key, reverse=True) # frequency of word freq =",
"word found if not freq: print(items[0][0]) def process_file(filename): with open(filename, 'r') as file:",
"parts[1] == 'd': if words[words.index(word) + 1] == 'better': parts[1] = 'had' else:",
"freq = 0 for item in items: word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'):",
"0 for item in items: word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if",
"print(items[0][0]) def process_file(filename): with open(filename, 'r') as file: article = file.read() no_pun_text =",
"# only this function was changed items = sorted(records.items(), key=return_order_key, reverse=True) # frequency",
"= article _punctuation = string.punctuation.replace('\\'', '') # delete punctuation except ''' for pun",
"= 'are' elif parts[1] == 't': parts[1] = 'not' elif parts[1] == 've':",
"file:', filename) print('-'*20) show_important_word(records) def process_files(path='.'): files = os.listdir(path) for file in files:",
"> 0: old2new = dict() words = text.split() for word in words: if",
"if tag.startswith('NN'): print(word) if item[1] < freq: return freq = item[1] # no",
"word freq = 0 for item in items: word, tag = nltk.pos_tag([item[0]])[0] if",
"text for old_word in old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return _text def return_order_key(record):",
"with open(filename, 'r') as file: article = file.read() no_pun_text = article _punctuation =",
"=> it is def extend_word(text): if text.find('\\'') > 0: old2new = dict() words",
"print(word) if item[1] < freq: return freq = item[1] # no appropriate word",
"like: it's => it is def extend_word(text): if text.find('\\'') > 0: old2new =",
"def show_important_word(records): # only this function was changed items = sorted(records.items(), key=return_order_key, reverse=True)",
"key=return_order_key, reverse=True) # frequency of word freq = 0 for item in items:",
"= ' '.join(parts) _text = text for old_word in old2new.keys(): _text = _text.replace(old_word,",
"if text.find('\\'') > 0: old2new = dict() words = text.split() for word in",
"for word in complete_text.lower().split(): records[word] = records.get(word, 0) + 1 print('='*30) print('current file:',",
"process_files(path='.'): files = os.listdir(path) for file in files: if file.endswith('.txt'): process_file(os.path.join(path, file)) process_files()",
"1] == 'better': parts[1] = 'had' else: parts[1] = 'would' if parts[0].endswith('n'): parts[0]",
"def process_file(filename): with open(filename, 'r') as file: article = file.read() no_pun_text = article",
"'.join(parts) _text = text for old_word in old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return",
"def extend_word(text): if text.find('\\'') > 0: old2new = dict() words = text.split() for",
"= 'not' elif parts[1] == 've': parts[1] = 'have' elif parts[1] == 'll':",
"elif parts[1] == 't': parts[1] = 'not' elif parts[1] == 've': parts[1] =",
"parts[1] == 't': parts[1] = 'not' elif parts[1] == 've': parts[1] = 'have'",
"== 'better': parts[1] = 'had' else: parts[1] = 'would' if parts[0].endswith('n'): parts[0] =",
"os # simply extend word like: it's => it is def extend_word(text): if",
"text.split() for word in words: if word.find('\\'') > 0: parts = word.split('\\'') if",
"records[word] = records.get(word, 0) + 1 print('='*30) print('current file:', filename) print('-'*20) show_important_word(records) def",
"word, tag = nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1] < freq: return freq",
"in _punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records = dict() for",
"old_word in old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return _text def return_order_key(record): return record[1]",
"= 'had' else: parts[1] = 'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] =",
"< freq: return freq = item[1] # no appropriate word found if not",
"punctuation except ''' for pun in _punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text =",
"parts[1] = 'will' elif parts[1] == 'd': if words[words.index(word) + 1] == 'better':",
"elif parts[1] == 're': parts[1] = 'are' elif parts[1] == 't': parts[1] =",
"of word freq = 0 for item in items: word, tag = nltk.pos_tag([item[0]])[0]",
"parts[1] = 'not' elif parts[1] == 've': parts[1] = 'have' elif parts[1] ==",
"article = file.read() no_pun_text = article _punctuation = string.punctuation.replace('\\'', '') # delete punctuation",
"parts[0][:-1] old2new[word] = ' '.join(parts) _text = text for old_word in old2new.keys(): _text",
"'am' elif parts[1] == 's': parts[1] = 'is' elif parts[1] == 're': parts[1]",
"freq: print(items[0][0]) def process_file(filename): with open(filename, 'r') as file: article = file.read() no_pun_text",
"extend word like: it's => it is def extend_word(text): if text.find('\\'') > 0:",
"== 're': parts[1] = 'are' elif parts[1] == 't': parts[1] = 'not' elif",
"elif parts[1] == 'll': parts[1] = 'will' elif parts[1] == 'd': if words[words.index(word)",
"_text = text for old_word in old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return _text",
"this function was changed items = sorted(records.items(), key=return_order_key, reverse=True) # frequency of word",
"no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text) records = dict() for word in complete_text.lower().split(): records[word]",
"'') complete_text = extend_word(no_pun_text) records = dict() for word in complete_text.lower().split(): records[word] =",
"it's => it is def extend_word(text): if text.find('\\'') > 0: old2new = dict()",
"'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] = ' '.join(parts) _text = text",
"'t': parts[1] = 'not' elif parts[1] == 've': parts[1] = 'have' elif parts[1]",
"return _text def return_order_key(record): return record[1] def show_important_word(records): # only this function was",
"def return_order_key(record): return record[1] def show_important_word(records): # only this function was changed items",
"_text = _text.replace(old_word, old2new[old_word]) return _text def return_order_key(record): return record[1] def show_important_word(records): #",
"'') # delete punctuation except ''' for pun in _punctuation: no_pun_text = no_pun_text.replace(pun,",
"= file.read() no_pun_text = article _punctuation = string.punctuation.replace('\\'', '') # delete punctuation except",
"simply extend word like: it's => it is def extend_word(text): if text.find('\\'') >",
"freq: return freq = item[1] # no appropriate word found if not freq:",
"= text for old_word in old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return _text def",
"nltk.pos_tag([item[0]])[0] if tag.startswith('NN'): print(word) if item[1] < freq: return freq = item[1] #",
"nltk import string import os # simply extend word like: it's => it",
"0: parts = word.split('\\'') if parts[1] == 'm': parts[1] = 'am' elif parts[1]",
"record[1] def show_important_word(records): # only this function was changed items = sorted(records.items(), key=return_order_key,",
"process_file(filename): with open(filename, 'r') as file: article = file.read() no_pun_text = article _punctuation",
"dict() words = text.split() for word in words: if word.find('\\'') > 0: parts",
"parts[1] == 're': parts[1] = 'are' elif parts[1] == 't': parts[1] = 'not'",
"except ''' for pun in _punctuation: no_pun_text = no_pun_text.replace(pun, '') complete_text = extend_word(no_pun_text)",
"= dict() words = text.split() for word in words: if word.find('\\'') > 0:",
"in old2new.keys(): _text = _text.replace(old_word, old2new[old_word]) return _text def return_order_key(record): return record[1] def",
"def process_files(path='.'): files = os.listdir(path) for file in files: if file.endswith('.txt'): process_file(os.path.join(path, file))",
"parts[1] = 'are' elif parts[1] == 't': parts[1] = 'not' elif parts[1] ==",
"else: parts[1] = 'would' if parts[0].endswith('n'): parts[0] = parts[0][:-1] old2new[word] = ' '.join(parts)",
"_punctuation = string.punctuation.replace('\\'', '') # delete punctuation except ''' for pun in _punctuation:",
"old2new = dict() words = text.split() for word in words: if word.find('\\'') >",
"== 's': parts[1] = 'is' elif parts[1] == 're': parts[1] = 'are' elif",
"elif parts[1] == 've': parts[1] = 'have' elif parts[1] == 'll': parts[1] =",
"'are' elif parts[1] == 't': parts[1] = 'not' elif parts[1] == 've': parts[1]",
"show_important_word(records): # only this function was changed items = sorted(records.items(), key=return_order_key, reverse=True) #",
"in complete_text.lower().split(): records[word] = records.get(word, 0) + 1 print('='*30) print('current file:', filename) print('-'*20)",
"parts = word.split('\\'') if parts[1] == 'm': parts[1] = 'am' elif parts[1] =="
] |
[
"bot.admins = data[\"admins\"] @bot.listen() async def on_close(loop): await bot.session.close() del bot.mysql bot.mysql =",
"= rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\",",
"= (prefixes,) kwargs = { \"help_command\": None, \"intents\": intents } bot = commands.Bot(",
"del bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] ==",
"import data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret = ujson.load(f)",
"bot.test = argv[1] != \"production\" bot.data = data bot.colors = RTCHAN_COLORS bot.is_admin =",
"\"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members = True",
"data bot.colors = RTCHAN_COLORS bot.is_admin = is_admin async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner",
"= commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1] != \"production\" bot.data = data",
"(\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents = discord.Intents.default()",
"import ClientSession from sys import argv import ujson import rtlib from data import",
"open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes =",
"= ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"]",
"\"r\", encoding=\"utf-8_sig\") as f: secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"]",
"async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner = _is_owner del is_admin, _is_owner setup(bot) bot.run(TOKEN)",
"password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False",
"sys import argv import ujson import rtlib from data import data, is_admin, RTCHAN_COLORS",
"is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret = ujson.load(f) TOKEN =",
"with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes",
"if argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1, maxsize=30,",
"data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret = ujson.load(f) TOKEN",
") bot.test = argv[1] != \"production\" bot.data = data bot.colors = RTCHAN_COLORS bot.is_admin",
"少女起動中...\"\"\" print(desc) from discord.ext import commands import discord # routeは無効にする。 commands.Cog.route = lambda",
"print(desc) from discord.ext import commands import discord # routeは無効にする。 commands.Cog.route = lambda *args,",
"LICENSE : ./LICENSE README : ./readme.md \"\"\" desc = \"\"\"りつたん - (C) 2021",
"not bot._loaded: bot.session = ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name)",
"for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\")",
"rtlib from data import data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f:",
"if not bot._loaded: bot.session = ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"):",
"aiohttp import ClientSession from sys import argv import ujson import rtlib from data",
"bot._loaded = False @bot.event async def on_ready(): if not bot._loaded: bot.session = ClientSession(loop=bot.loop)",
"from aiohttp import ClientSession from sys import argv import ujson import rtlib from",
"command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1] != \"production\" bot.data = data bot.colors =",
": ./LICENSE README : ./readme.md \"\"\" desc = \"\"\"りつたん - (C) 2021 RT-Team",
"\"intents\": intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1] !=",
"bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1]",
"bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async def on_ready(): if not bot._loaded: bot.session =",
"as f: secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot):",
"True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members = True intents.typing = False intents.guild_typing =",
"bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members = True intents.typing",
"discord.Intents.default() intents.members = True intents.typing = False intents.guild_typing = False intents.dm_typing = False",
"= RTCHAN_COLORS bot.is_admin = is_admin async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner = _is_owner",
"bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\"",
"\"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members",
"= data[\"admins\"] @bot.listen() async def on_close(loop): await bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"]",
"argv[1] != \"production\" bot.data = data bot.colors = RTCHAN_COLORS bot.is_admin = is_admin async",
"= False intents.dm_typing = False args = (prefixes,) kwargs = { \"help_command\": None,",
"import ujson import rtlib from data import data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\",",
"RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"]",
"prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"] @bot.listen() async def on_close(loop): await",
"async def on_ready(): if not bot._loaded: bot.session = ClientSession(loop=bot.loop) for name in (\"cogs.tts\",",
"\"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import commands import discord",
"False @bot.event async def on_ready(): if not bot._loaded: bot.session = ClientSession(loop=bot.loop) for name",
"secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"] @bot.listen() async def on_close(loop):",
"intents.typing = False intents.guild_typing = False intents.dm_typing = False args = (prefixes,) kwargs",
"*args, **kwargs: (args, kwargs) from aiohttp import ClientSession from sys import argv import",
"import rtlib from data import data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as",
"rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool",
"= True intents.typing = False intents.guild_typing = False intents.dm_typing = False args =",
"= secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"] @bot.listen() async def",
"bot.session = ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded",
"autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async def on_ready(): if not bot._loaded:",
"routeは無効にする。 commands.Cog.route = lambda *args, **kwargs: lambda *args, **kwargs: (args, kwargs) from aiohttp",
"RT-Team LICENSE : ./LICENSE README : ./readme.md \"\"\" desc = \"\"\"りつたん - (C)",
"\"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\")",
"False intents.guild_typing = False intents.dm_typing = False args = (prefixes,) kwargs = {",
"import argv import ujson import rtlib from data import data, is_admin, RTCHAN_COLORS with",
"<filename>sub.py \"\"\"りつたん! (C) 2020 RT-Team LICENSE : ./LICENSE README : ./readme.md \"\"\" desc",
"from discord.ext import commands import discord # routeは無効にする。 commands.Cog.route = lambda *args, **kwargs:",
"2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import commands import discord # routeは無効にする。 commands.Cog.route",
"discord # routeは無効にする。 commands.Cog.route = lambda *args, **kwargs: lambda *args, **kwargs: (args, kwargs)",
"argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1, maxsize=30, autocommit=True)",
"maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async def on_ready(): if not",
"is_admin async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner = _is_owner del is_admin, _is_owner setup(bot)",
"./readme.md \"\"\" desc = \"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext",
"None, \"intents\": intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1]",
"(args, kwargs) from aiohttp import ClientSession from sys import argv import ujson import",
"lambda *args, **kwargs: (args, kwargs) from aiohttp import ClientSession from sys import argv",
"bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\" else",
"intents.dm_typing = False args = (prefixes,) kwargs = { \"help_command\": None, \"intents\": intents",
"from sys import argv import ujson import rtlib from data import data, is_admin,",
"commands import discord # routeは無効にする。 commands.Cog.route = lambda *args, **kwargs: lambda *args, **kwargs:",
"host=\"192.168.3.11\" if argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1,",
"intents.members = True intents.typing = False intents.guild_typing = False intents.dm_typing = False args",
"**kwargs ) bot.test = argv[1] != \"production\" bot.data = data bot.colors = RTCHAN_COLORS",
"bot.colors = RTCHAN_COLORS bot.is_admin = is_admin async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner =",
"./LICENSE README : ./readme.md \"\"\" desc = \"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\"",
"ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"] @bot.listen()",
"= ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded =",
"= bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\" else \"localhost\",",
"README : ./readme.md \"\"\" desc = \"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\" print(desc)",
"setup(bot): bot.admins = data[\"admins\"] @bot.listen() async def on_close(loop): await bot.session.close() del bot.mysql bot.mysql",
"= lambda *args, **kwargs: lambda *args, **kwargs: (args, kwargs) from aiohttp import ClientSession",
"= True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async def",
"name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents",
"intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1] != \"production\"",
"= True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members = True intents.typing = False intents.guild_typing",
"data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"] @bot.listen() async def on_close(loop): await bot.session.close() del",
"kwargs) from aiohttp import ClientSession from sys import argv import ujson import rtlib",
"# routeは無効にする。 commands.Cog.route = lambda *args, **kwargs: lambda *args, **kwargs: (args, kwargs) from",
"= False args = (prefixes,) kwargs = { \"help_command\": None, \"intents\": intents }",
"discord.ext import commands import discord # routeは無効にする。 commands.Cog.route = lambda *args, **kwargs: lambda",
"\"\"\"りつたん! (C) 2020 RT-Team LICENSE : ./LICENSE README : ./readme.md \"\"\" desc =",
"\"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members =",
"\"production\" bot.data = data bot.colors = RTCHAN_COLORS bot.is_admin = is_admin async def _is_owner(user):",
"def on_close(loop): await bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"],",
"= data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"] @bot.listen() async def on_close(loop): await bot.session.close()",
"print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members = True intents.typing = False intents.guild_typing = False",
"= data bot.colors = RTCHAN_COLORS bot.is_admin = is_admin async def _is_owner(user): return bot.is_admin(user.id)",
"- (C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import commands import discord #",
"encoding=\"utf-8_sig\") as f: secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def",
"ClientSession from sys import argv import ujson import rtlib from data import data,",
"(C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import commands import discord # routeは無効にする。",
": ./readme.md \"\"\" desc = \"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from",
"True intents.typing = False intents.guild_typing = False intents.dm_typing = False args = (prefixes,)",
"RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import commands import discord # routeは無効にする。 commands.Cog.route =",
"= argv[1] != \"production\" bot.data = data bot.colors = RTCHAN_COLORS bot.is_admin = is_admin",
"db=\"mysql\", pool = True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event",
"bot.is_admin = is_admin async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner = _is_owner del is_admin,",
"= \"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import commands import",
"async def on_close(loop): await bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop,",
"ujson import rtlib from data import data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\")",
"kwargs = { \"help_command\": None, \"intents\": intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs",
"rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async def on_ready(): if not bot._loaded: bot.session",
"bot._loaded = True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members = True intents.typing = False",
"data[\"admins\"] @bot.listen() async def on_close(loop): await bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"] =",
"else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded",
"commands.Cog.route = lambda *args, **kwargs: lambda *args, **kwargs: (args, kwargs) from aiohttp import",
"(prefixes,) kwargs = { \"help_command\": None, \"intents\": intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"],",
"commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1] != \"production\" bot.data = data bot.colors",
"RTCHAN_COLORS bot.is_admin = is_admin async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner = _is_owner del",
"@bot.listen() async def on_close(loop): await bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager(",
"def on_ready(): if not bot._loaded: bot.session = ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\",",
"in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents =",
"bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1] != \"production\" bot.data =",
"2020 RT-Team LICENSE : ./LICENSE README : ./readme.md \"\"\" desc = \"\"\"りつたん -",
"await bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if",
"loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool =",
"pool = True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async",
"bot.dispatch(\"full_ready\") bot._loaded = True print(\"少女絶賛稼働中!\") intents = discord.Intents.default() intents.members = True intents.typing =",
"False args = (prefixes,) kwargs = { \"help_command\": None, \"intents\": intents } bot",
"bot.data = data bot.colors = RTCHAN_COLORS bot.is_admin = is_admin async def _is_owner(user): return",
"argv import ujson import rtlib from data import data, is_admin, RTCHAN_COLORS with open(\"token.secret\",",
"*args, **kwargs: lambda *args, **kwargs: (args, kwargs) from aiohttp import ClientSession from sys",
"== \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot)",
"f: secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins",
"user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True,",
"desc = \"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import commands",
"import commands import discord # routeは無効にする。 commands.Cog.route = lambda *args, **kwargs: lambda *args,",
"!= \"production\" bot.data = data bot.colors = RTCHAN_COLORS bot.is_admin = is_admin async def",
"= False @bot.event async def on_ready(): if not bot._loaded: bot.session = ClientSession(loop=bot.loop) for",
"**kwargs: lambda *args, **kwargs: (args, kwargs) from aiohttp import ClientSession from sys import",
"False intents.dm_typing = False args = (prefixes,) kwargs = { \"help_command\": None, \"intents\":",
"intents.guild_typing = False intents.dm_typing = False args = (prefixes,) kwargs = { \"help_command\":",
"bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\" if argv[1] == \"production\" else \"localhost\", password=secret[\"mysql\"][\"password\"],",
"= { \"help_command\": None, \"intents\": intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs )",
"**kwargs: (args, kwargs) from aiohttp import ClientSession from sys import argv import ujson",
"minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async def on_ready(): if",
"{ \"help_command\": None, \"intents\": intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test",
"(C) 2020 RT-Team LICENSE : ./LICENSE README : ./readme.md \"\"\" desc = \"\"\"りつたん",
"TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins = data[\"admins\"] @bot.listen() async",
"def setup(bot): bot.admins = data[\"admins\"] @bot.listen() async def on_close(loop): await bot.session.close() del bot.mysql",
"import discord # routeは無効にする。 commands.Cog.route = lambda *args, **kwargs: lambda *args, **kwargs: (args,",
"intents = discord.Intents.default() intents.members = True intents.typing = False intents.guild_typing = False intents.dm_typing",
"args = (prefixes,) kwargs = { \"help_command\": None, \"intents\": intents } bot =",
"True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded = False @bot.event async def on_ready():",
"on_ready(): if not bot._loaded: bot.session = ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\",",
"\"\"\" desc = \"\"\"りつたん - (C) 2021 RT-Team 少女起動中...\"\"\" print(desc) from discord.ext import",
"} bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test = argv[1] != \"production\" bot.data",
"data import data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret =",
"\"localhost\", password=secret[\"mysql\"][\"password\"], db=\"mysql\", pool = True, minsize=1, maxsize=30, autocommit=True) rtlib.setup(bot) bot.load_extension(\"jishaku\") bot._loaded =",
"lambda *args, **kwargs: lambda *args, **kwargs: (args, kwargs) from aiohttp import ClientSession from",
"= False intents.guild_typing = False intents.dm_typing = False args = (prefixes,) kwargs =",
"ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\") bot._loaded = True",
"from data import data, is_admin, RTCHAN_COLORS with open(\"token.secret\", \"r\", encoding=\"utf-8_sig\") as f: secret",
"@bot.event async def on_ready(): if not bot._loaded: bot.session = ClientSession(loop=bot.loop) for name in",
"secret = ujson.load(f) TOKEN = secret[\"token\"][\"sub\"] prefixes = data[\"prefixes\"][\"sub\"] def setup(bot): bot.admins =",
"\"help_command\": None, \"intents\": intents } bot = commands.Bot( command_prefix=data[\"prefixes\"][\"sub\"], **kwargs ) bot.test =",
"= is_admin async def _is_owner(user): return bot.is_admin(user.id) bot.is_owner = _is_owner del is_admin, _is_owner",
"on_close(loop): await bot.session.close() del bot.mysql bot.mysql = bot.data[\"mysql\"] = rtlib.mysql.MySQLManager( loop=bot.loop, user=secret[\"mysql\"][\"user\"], host=\"192.168.3.11\"",
"bot._loaded: bot.session = ClientSession(loop=bot.loop) for name in (\"cogs.tts\", \"cogs.music\", \"cogs._sub\", \"cogs.language\"): bot.load_extension(name) bot.dispatch(\"full_ready\")",
"= discord.Intents.default() intents.members = True intents.typing = False intents.guild_typing = False intents.dm_typing ="
] |
[
"creates text input field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color,",
"to mouse and kb events NOTE: kb events related to input box and",
"kez are handled in update function\"\"\" events = pygame.event.get() for event in events:",
"method: # self.text_input.update(events) if event.key == self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP: for",
"# getters/setters def get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try() not in",
"if there is no text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text",
"self.text_input_rect) # draw all buttons pos_mouse = pygame.mouse.get_pos() for button in self.buttons: if",
"= self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether input text is",
"self.app.settings.key_quit): self.app.quit_game() return [] # this is so the text input does not",
"for current word \"\"\" current_input = self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if self.get_previous_try()",
"\"\"\" implements changes that are needed by H2R at every tick, based on",
"text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame for input field",
"images self.str_english_img, self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect = None, None # create",
"to return input field to default color if text # was erased if",
"text input does not activate while app is quitting if event.type == pygame.KEYUP:",
"= self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame)",
"self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons",
"current word \"\"\" current_input = self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if self.get_previous_try() ==",
"box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init attributes",
"pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of",
"self.text_input.get_text(): # only if there is no text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect)",
"vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self):",
"= [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial status self.word = self._pick_word()",
"word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether input text",
"kana word img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates",
"and the user needs to enter the correct romaji transliteration\"\"\" def __init__(self, app):",
"to enter the correct romaji transliteration\"\"\" def __init__(self, app): \"\"\" initialises the Hiragana",
"draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): # only if",
"== self.app.settings.key_quit): self.app.quit_game() return [] # this is so the text input does",
"if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws each element of H2R \"\"\"",
"antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame for input",
"return input field to default color if text # was erased if not",
"button in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT HANDLING",
"each element of H2R \"\"\" # draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en,",
"\"right\", \"wrong\"): raise TypeError(\"Wrong argument for previous try.\") self.previous_try = previous_try # HELPERS",
"self.app.settings.h2r_font_english_color, self.container_english) # creates kana word img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana,",
"= previous_try # HELPERS def _pick_word(self): \"\"\" picks a random Word instance from",
"not in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument for previous try.\") self.previous_try =",
"elements self.container_english, \\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen, (5 /",
"in which a hiragana word is displayed, and the user needs to enter",
"self.app.quit_game() return [] # this is so the text input does not activate",
"if event.type == pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse() return events # getters/setters",
"\"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word() self.text_input.clear_text()",
"all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): # only if there",
"initial status self.word = self._pick_word() self.previous_try = None # determines background of text",
"raise TypeError(\"Wrong argument for previous try.\") self.previous_try = previous_try # HELPERS def _pick_word(self):",
"self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init attributes for",
"# draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons pos_mouse =",
") # creates background frame for input field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width",
"= self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons =",
"20), layout=\"V\") # creates text input field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size),",
"return events # getters/setters def get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try()",
"== pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game() return []",
"Button import text class H2R(object): \"\"\" A mode in which a hiragana word",
"all buttons pos_mouse = pygame.mouse.get_pos() for button in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen)",
"\"\"\" A mode in which a hiragana word is displayed, and the user",
"self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons)",
"self.container_buttons = create_containers( self.app.screen, (5 / 20, 6 / 20, 5 / 20,",
"def check_events(self): \"\"\"Checks for and responds to mouse and kb events NOTE: kb",
"for different UI elements self.container_english, \\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons = create_containers(",
"text # was erased if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws each",
"\"\"\" self.app = app # create and place container rects for different UI",
"== self.app.settings.key_confirm: # commented out because this is # handled in update method:",
"def draw_screen(self): \"\"\" draws each element of H2R \"\"\" # draw backgrounds of",
"- selects a word - updates and draws screen accordingly \"\"\" self.app =",
"# create and place container rects for different UI elements self.container_english, \\ self.container_kana,",
"_help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether input",
"# determines background of text input field as feedback def update_screen(self, events): \"\"\"",
"# creates english word img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english)",
"Hiragana to Romaji exercise - creates container rects for the 3 main screen",
"= create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input box if self.text_input.update(events):",
"draws screen accordingly \"\"\" self.app = app # create and place container rects",
"self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt, function=function, color_base=self.app.settings.h2r_button_color,",
"self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) #",
"on user events \"\"\" # creates english word img self.str_english_img, self.str_english_rect = create_centered_text(",
"# only if there is no text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) #",
"\"\"\" # creates english word img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color,",
"self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) #",
"initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background",
"# draw all buttons pos_mouse = pygame.mouse.get_pos() for button in self.buttons: if not",
"self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word =",
"self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial status self.word = self._pick_word() self.previous_try = None",
"field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length",
"# creates background frame for input field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width +",
"buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game)",
"input field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center",
"of text input field as feedback def update_screen(self, events): \"\"\" implements changes that",
"self.input_tip_rect) # draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons pos_mouse",
"\"\"\" # draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana)",
"input does not activate while app is quitting if event.type == pygame.KEYUP: #",
"== \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word()",
"= pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates rect",
"out because this is # handled in update method: # self.text_input.update(events) if event.key",
"/ 20, 4 / 20), layout=\"V\") # creates text input field self.text_input =",
"input box if self.text_input.update(events): self._confirm_word() # updates previous try, to return input field",
"class H2R(object): \"\"\" A mode in which a hiragana word is displayed, and",
"helper.pygame_helpers import create_centered_text, create_containers, place_buttons from helper.button import Button import text class H2R(object):",
"is correct for current word \"\"\" current_input = self.text_input.get_text().lower().strip() if current_input == self.word.romaji:",
"self.word = self._pick_word() self.previous_try = None # determines background of text input field",
"== pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game() return [] # this is so",
"\"\"\" initialises the Hiragana to Romaji exercise - creates container rects for the",
"erased if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws each element of H2R",
"\"\"\"Checks for and responds to mouse and kb events NOTE: kb events related",
"= None # determines background of text input field as feedback def update_screen(self,",
"and draws screen accordingly \"\"\" self.app = app # create and place container",
"self.input_frame.center # init attributes for text rects and images self.str_english_img, self.str_english_rect = None,",
"based on user events \"\"\" # creates english word img self.str_english_img, self.str_english_rect =",
"events = pygame.event.get() for event in events: if event.type == pygame.QUIT or (event.type",
"events NOTE: kb events related to input box and RETURN kez are handled",
"random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks",
"import create_centered_text, create_containers, place_buttons from helper.button import Button import text class H2R(object): \"\"\"",
"rects and images self.str_english_img, self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect = None, None",
"text input field as feedback def update_screen(self, events): \"\"\" implements changes that are",
"\"\"\" draws each element of H2R \"\"\" # draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark)",
"self.container_english, \\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen, (5 / 20,",
"self._pick_word() self.previous_try = None # determines background of text input field as feedback",
"is so the text input does not activate while app is quitting if",
"create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check",
"self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana word img",
"rects for different UI elements self.container_english, \\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons =",
"def _help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether",
"self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check,",
"pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of text input box",
"draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons pos_mouse = pygame.mouse.get_pos()",
"instance from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji self.text_input.set_text(word)",
"argument for previous try.\") self.previous_try = previous_try # HELPERS def _pick_word(self): \"\"\" picks",
"whether input text is correct for current word \"\"\" current_input = self.text_input.get_text().lower().strip() if",
"app is quitting if event.type == pygame.KEYUP: # if event.key == self.app.settings.key_confirm: #",
"create_centered_text, create_containers, place_buttons from helper.button import Button import text class H2R(object): \"\"\" A",
"that are needed by H2R at every tick, based on user events \"\"\"",
"check_events(self): \"\"\"Checks for and responds to mouse and kb events NOTE: kb events",
"event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game() return",
"and RETURN kez are handled in update function\"\"\" events = pygame.event.get() for event",
"5 / 20, 4 / 20), layout=\"V\") # creates text input field self.text_input",
"input box if self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color",
"word img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana",
"word - updates and draws screen accordingly \"\"\" self.app = app # create",
"self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse() return events",
"mode in which a hiragana word is displayed, and the user needs to",
"to Romaji exercise - creates container rects for the 3 main screen areas",
"romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img,",
"random Word instance from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word =",
"import Button import text class H2R(object): \"\"\" A mode in which a hiragana",
"changes that are needed by H2R at every tick, based on user events",
"self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function): return Button(((0,",
"draw bg of text input box if self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color",
"event.key == self.app.settings.key_quit): self.app.quit_game() return [] # this is so the text input",
"self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): # only if there is no text in",
"- creates container rects for the 3 main screen areas - selects a",
"HANDLING def check_events(self): \"\"\"Checks for and responds to mouse and kb events NOTE:",
"self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of text input box if",
"+ 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates rect for input box self.text_input_rect",
"at every tick, based on user events \"\"\" # creates english word img",
"A mode in which a hiragana word is displayed, and the user needs",
"self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates rect for input box self.text_input_rect = pygame.Rect(0,",
"# self.text_input.update(events) if event.key == self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP: for button",
"None # determines background of text input field as feedback def update_screen(self, events):",
"of text input box if self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success",
"else: self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function): return",
"and event.key == self.app.settings.key_quit): self.app.quit_game() return [] # this is so the text",
"None, None self.str_kana_img, self.str_kana_rect = None, None # create and place input tip",
"= self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial",
"self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw",
"self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init attributes for text rects and images",
"self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): # only if there is no",
"self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana word img self.str_kana_img,",
"self.str_kana_img, self.str_kana_rect = None, None # create and place input tip self.input_tip_img, self.input_tip_rect",
"if self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color",
"= self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all texts",
"self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana word img self.str_kana_img, self.str_kana_rect = create_centered_text(",
"screen areas - selects a word - updates and draws screen accordingly \"\"\"",
"self.previous_try = None # determines background of text input field as feedback def",
"create and place container rects for different UI elements self.container_english, \\ self.container_kana, \\",
"self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input box if self.text_input.update(events): self._confirm_word() # updates previous",
"handled in update function\"\"\" events = pygame.event.get() for event in events: if event.type",
"\\ self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen, (5 / 20, 6 / 20,",
"[] # this is so the text input does not activate while app",
"button.draw(self.app.screen, alt=True) # EVENT HANDLING def check_events(self): \"\"\"Checks for and responds to mouse",
"determines background of text input field as feedback def update_screen(self, events): \"\"\" implements",
"previous try.\") self.previous_try = previous_try # HELPERS def _pick_word(self): \"\"\" picks a random",
"font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame",
"implements changes that are needed by H2R at every tick, based on user",
"font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame for",
"self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input box if self.text_input.update(events): self._confirm_word() # updates",
"pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init attributes for text rects",
"else: button.draw(self.app.screen, alt=True) # EVENT HANDLING def check_events(self): \"\"\"Checks for and responds to",
"while app is quitting if event.type == pygame.KEYUP: # if event.key == self.app.settings.key_confirm:",
"(None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument for previous try.\") self.previous_try = previous_try #",
"self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons",
"txt, function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt, function=function, color_base=self.app.settings.h2r_button_color, color_alt=self.app.settings.h2r_button_color_alt, font=self.app.settings.h2r_button_font, font_color=self.app.settings.h2r_button_font_color, font_color_alt=self.app.settings.h2r_button_font_color_alt",
"img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana word",
"self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial status",
"draw all buttons pos_mouse = pygame.mouse.get_pos() for button in self.buttons: if not button.is_inside(pos_mouse):",
"are handled in update function\"\"\" events = pygame.event.get() for event in events: if",
"self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help = self._h2r_button(text.h2r_button_help,",
"is # handled in update method: # self.text_input.update(events) if event.key == self.app.settings.key_help: self._help()",
"in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument for previous try.\") self.previous_try = previous_try",
"the Hiragana to Romaji exercise - creates container rects for the 3 main",
"pygame.KEYUP: # if event.key == self.app.settings.key_confirm: # commented out because this is #",
"self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana word img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana,",
"bg of text input box if self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color =",
"def _h2r_button(self, txt, function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt, function=function, color_base=self.app.settings.h2r_button_color, color_alt=self.app.settings.h2r_button_color_alt, font=self.app.settings.h2r_button_font,",
"status self.word = self._pick_word() self.previous_try = None # determines background of text input",
"H2R(object): \"\"\" A mode in which a hiragana word is displayed, and the",
"= pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init attributes for text",
"self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates",
"field to default color if text # was erased if not self.text_input.get_text(): self.set_previous_try(None)",
"text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check =",
"is displayed, and the user needs to enter the correct romaji transliteration\"\"\" def",
"= create_containers( self.app.screen, (5 / 20, 6 / 20, 5 / 20, 4",
"picks a random Word instance from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self):",
"app # create and place container rects for different UI elements self.container_english, \\",
"= self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons,",
"quitting if event.type == pygame.KEYUP: # if event.key == self.app.settings.key_confirm: # commented out",
"from helper.button import Button import text class H2R(object): \"\"\" A mode in which",
"in update function\"\"\" events = pygame.event.get() for event in events: if event.type ==",
"function\"\"\" events = pygame.event.get() for event in events: if event.type == pygame.QUIT or",
"if not self.text_input.get_text(): # only if there is no text in input field",
"commented out because this is # handled in update method: # self.text_input.update(events) if",
"# creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit =",
"background frame for input field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height)",
"place_buttons(self.buttons, self.container_buttons) # set initial status self.word = self._pick_word() self.previous_try = None #",
"= create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana word img self.str_kana_img, self.str_kana_rect",
"because this is # handled in update method: # self.text_input.update(events) if event.key ==",
"input box and RETURN kez are handled in update function\"\"\" events = pygame.event.get()",
"event.key == self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse()",
"kb events related to input box and RETURN kez are handled in update",
"self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether input text is correct for",
"if self.get_previous_try() not in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument for previous try.\")",
"and place input tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) #",
"self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit]",
"= self.input_frame.center # init attributes for text rects and images self.str_english_img, self.str_english_rect =",
"HELPERS def _pick_word(self): \"\"\" picks a random Word instance from the app's vocab\"\"\"",
"= pygame.mouse.get_pos() for button in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True)",
"tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help",
"pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) #",
"self.app.screen, (5 / 20, 6 / 20, 5 / 20, 4 / 20),",
"= self.container_romaji.center # creates rect for input box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width,",
"pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of text input box if self.get_previous_try(): if",
"_confirm_word(self): \"\"\" checks whether input text is correct for current word \"\"\" current_input",
"- updates and draws screen accordingly \"\"\" self.app = app # create and",
"rect for input box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center",
"text rects and images self.str_english_img, self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect = None,",
"self.container_buttons) # set initial status self.word = self._pick_word() self.previous_try = None # determines",
"self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt,",
"box and RETURN kez are handled in update function\"\"\" events = pygame.event.get() for",
"self._confirm_word() # updates previous try, to return input field to default color if",
"not activate while app is quitting if event.type == pygame.KEYUP: # if event.key",
"\"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen,",
"H2R at every tick, based on user events \"\"\" # creates english word",
"# draw bg of text input box if self.get_previous_try(): if self.get_previous_try() == \"right\":",
"self.container_romaji.center # creates rect for input box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height)",
"self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try() not in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong",
"input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons pos_mouse = pygame.mouse.get_pos() for button",
"if text # was erased if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws",
"self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial status self.word = self._pick_word() self.previous_try =",
"of H2R \"\"\" # draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen,",
"repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame for input field self.input_frame = pygame.Rect(0,",
"img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input",
"(5 / 20, 6 / 20, 5 / 20, 4 / 20), layout=\"V\")",
"not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws each element of H2R \"\"\" #",
"and images self.str_english_img, self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect = None, None #",
"romaji_frame_color, self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text():",
"or (event.type == pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game() return [] # this",
"self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial status self.word =",
"english word img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates",
"no text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input box self.app.screen.blit(self.text_input.get_surface(),",
"= TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) #",
"def update_screen(self, events): \"\"\" implements changes that are needed by H2R at every",
"self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of text",
"if self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger",
"if event.key == self.app.settings.key_confirm: # commented out because this is # handled in",
"self._help() if event.type == pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse() return events #",
"self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input box if",
"user events \"\"\" # creates english word img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english,",
"# init attributes for text rects and images self.str_english_img, self.str_english_rect = None, None",
"hiragana word is displayed, and the user needs to enter the correct romaji",
"= None, None # create and place input tip self.input_tip_img, self.input_tip_rect = create_centered_text(",
"self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if",
"a word - updates and draws screen accordingly \"\"\" self.app = app #",
"import TextInput from helper.pygame_helpers import create_centered_text, create_containers, place_buttons from helper.button import Button import",
"word img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text",
"pos_mouse = pygame.mouse.get_pos() for button in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen,",
"input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw",
"# create and place input tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color,",
"if event.key == self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP: for button in self.buttons:",
"self.set_previous_try(None) def draw_screen(self): \"\"\" draws each element of H2R \"\"\" # draw backgrounds",
"self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons)",
"every tick, based on user events \"\"\" # creates english word img self.str_english_img,",
"this is so the text input does not activate while app is quitting",
"not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT HANDLING def check_events(self): \"\"\"Checks for",
"self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check,",
"create and place input tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji)",
"is no text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input box",
"creates english word img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) #",
"not self.text_input.get_text(): # only if there is no text in input field self.app.screen.blit(self.input_tip_img,",
"self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input box if self.text_input.update(events): self._confirm_word() #",
"correct romaji transliteration\"\"\" def __init__(self, app): \"\"\" initialises the Hiragana to Romaji exercise",
"responds to mouse and kb events NOTE: kb events related to input box",
"self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): #",
"self.container_romaji) # creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit",
"which a hiragana word is displayed, and the user needs to enter the",
"text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect)",
"box if self.text_input.update(events): self._confirm_word() # updates previous try, to return input field to",
"events: if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == self.app.settings.key_quit):",
"self.buttons: button.on_mouse() return events # getters/setters def get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try):",
"<gh_stars>0 import random import pygame from helper.textinput import TextInput from helper.pygame_helpers import create_centered_text,",
"self.container_kana, \\ self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen, (5 / 20, 6 /",
"20, 5 / 20, 4 / 20), layout=\"V\") # creates text input field",
"update method: # self.text_input.update(events) if event.key == self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP:",
"_h2r_button(self, txt, function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt, function=function, color_base=self.app.settings.h2r_button_color, color_alt=self.app.settings.h2r_button_color_alt, font=self.app.settings.h2r_button_font, font_color=self.app.settings.h2r_button_font_color,",
"if self.text_input.update(events): self._confirm_word() # updates previous try, to return input field to default",
"events # getters/setters def get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try() not",
"function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt, function=function, color_base=self.app.settings.h2r_button_color, color_alt=self.app.settings.h2r_button_color_alt, font=self.app.settings.h2r_button_font, font_color=self.app.settings.h2r_button_font_color, font_color_alt=self.app.settings.h2r_button_font_color_alt )",
"self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of text input box if self.get_previous_try(): if self.get_previous_try()",
"None self.str_kana_img, self.str_kana_rect = None, None # create and place input tip self.input_tip_img,",
"self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word)",
"needed by H2R at every tick, based on user events \"\"\" # creates",
"the text input does not activate while app is quitting if event.type ==",
"if current_input == self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else:",
"None # create and place input tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip,",
"self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether input text is correct for current word",
"text class H2R(object): \"\"\" A mode in which a hiragana word is displayed,",
"else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw",
"from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word))",
"for button in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT",
"= create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help)",
"mouse and kb events NOTE: kb events related to input box and RETURN",
"current_input = self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word()",
"tick, based on user events \"\"\" # creates english word img self.str_english_img, self.str_english_rect",
"updates and draws screen accordingly \"\"\" self.app = app # create and place",
"UI elements self.container_english, \\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen, (5",
"import pygame from helper.textinput import TextInput from helper.pygame_helpers import create_centered_text, create_containers, place_buttons from",
"self.container_buttons) # draw bg of text input box if self.get_previous_try(): if self.get_previous_try() ==",
"as feedback def update_screen(self, events): \"\"\" implements changes that are needed by H2R",
"in events: if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key ==",
"return random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\"",
"a random Word instance from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word",
"texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): # only if there is",
"if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game()",
"= app # create and place container rects for different UI elements self.container_english,",
"self.get_previous_try() not in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument for previous try.\") self.previous_try",
"self.text_input.update(events) if event.key == self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP: for button in",
"rects for the 3 main screen areas - selects a word - updates",
"pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game() return [] #",
"== pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse() return events # getters/setters def get_previous_try(self):",
"TypeError(\"Wrong argument for previous try.\") self.previous_try = previous_try # HELPERS def _pick_word(self): \"\"\"",
"set_previous_try(self, previous_try): if self.get_previous_try() not in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument for",
"of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen,",
"for the 3 main screen areas - selects a word - updates and",
"app): \"\"\" initialises the Hiragana to Romaji exercise - creates container rects for",
"def set_previous_try(self, previous_try): if self.get_previous_try() not in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument",
"Word instance from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji",
"cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame for input field self.input_frame",
"and kb events NOTE: kb events related to input box and RETURN kez",
"romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all",
"\"\"\" current_input = self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None)",
"update_screen(self, events): \"\"\" implements changes that are needed by H2R at every tick,",
"self.app = app # create and place container rects for different UI elements",
"text input box if self.text_input.update(events): self._confirm_word() # updates previous try, to return input",
"= self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect)",
"the correct romaji transliteration\"\"\" def __init__(self, app): \"\"\" initialises the Hiragana to Romaji",
"init attributes for text rects and images self.str_english_img, self.str_english_rect = None, None self.str_kana_img,",
"# creates kana word img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana)",
"pygame.mouse.get_pos() for button in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) #",
"\"\"\" checks whether input text is correct for current word \"\"\" current_input =",
"H2R \"\"\" # draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan,",
"pygame from helper.textinput import TextInput from helper.pygame_helpers import create_centered_text, create_containers, place_buttons from helper.button",
"if event.type == pygame.KEYUP: # if event.key == self.app.settings.key_confirm: # commented out because",
"random import pygame from helper.textinput import TextInput from helper.pygame_helpers import create_centered_text, create_containers, place_buttons",
"# set initial status self.word = self._pick_word() self.previous_try = None # determines background",
"in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT HANDLING def",
"field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center #",
"self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else:",
"# draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): # only",
"color if text # was erased if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\"",
"exercise - creates container rects for the 3 main screen areas - selects",
"backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji)",
"= self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else:",
"to default color if text # was erased if not self.text_input.get_text(): self.set_previous_try(None) def",
"# was erased if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws each element",
"RETURN kez are handled in update function\"\"\" events = pygame.event.get() for event in",
"try.\") self.previous_try = previous_try # HELPERS def _pick_word(self): \"\"\" picks a random Word",
"feedback def update_screen(self, events): \"\"\" implements changes that are needed by H2R at",
"\"\"\" picks a random Word instance from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def",
"else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt,",
"None, None # create and place input tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip,",
"container rects for the 3 main screen areas - selects a word -",
"is quitting if event.type == pygame.KEYUP: # if event.key == self.app.settings.key_confirm: # commented",
"creates container rects for the 3 main screen areas - selects a word",
"to input box and RETURN kez are handled in update function\"\"\" events =",
"self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of text input",
"# creates text input field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color,",
"button.on_mouse() return events # getters/setters def get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try): if",
"previous_try): if self.get_previous_try() not in (None, \"right\", \"wrong\"): raise TypeError(\"Wrong argument for previous",
"different UI elements self.container_english, \\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen,",
"# HELPERS def _pick_word(self): \"\"\" picks a random Word instance from the app's",
"= self._pick_word() self.previous_try = None # determines background of text input field as",
"displayed, and the user needs to enter the correct romaji transliteration\"\"\" def __init__(self,",
"def __init__(self, app): \"\"\" initialises the Hiragana to Romaji exercise - creates container",
"\\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen, (5 / 20, 6",
"# EVENT HANDLING def check_events(self): \"\"\"Checks for and responds to mouse and kb",
"get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try() not in (None, \"right\", \"wrong\"):",
"self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg",
"self.previous_try = previous_try # HELPERS def _pick_word(self): \"\"\" picks a random Word instance",
"try, to return input field to default color if text # was erased",
"self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function):",
"update function\"\"\" events = pygame.event.get() for event in events: if event.type == pygame.QUIT",
"button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT HANDLING def check_events(self): \"\"\"Checks for and responds",
"/ 20, 5 / 20, 4 / 20), layout=\"V\") # creates text input",
"in update method: # self.text_input.update(events) if event.key == self.app.settings.key_help: self._help() if event.type ==",
"selects a word - updates and draws screen accordingly \"\"\" self.app = app",
"self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color =",
"self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self,",
"helper.button import Button import text class H2R(object): \"\"\" A mode in which a",
"pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates rect for",
"app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def",
"# updates text input box if self.text_input.update(events): self._confirm_word() # updates previous try, to",
"input box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init",
"place container rects for different UI elements self.container_english, \\ self.container_kana, \\ self.container_romaji, \\",
"text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons pos_mouse = pygame.mouse.get_pos() for",
"field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all",
"self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input box",
"updates text input box if self.text_input.update(events): self._confirm_word() # updates previous try, to return",
"self.str_kana_rect) if not self.text_input.get_text(): # only if there is no text in input",
"getters/setters def get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try() not in (None,",
"for and responds to mouse and kb events NOTE: kb events related to",
"set initial status self.word = self._pick_word() self.previous_try = None # determines background of",
"/ 20), layout=\"V\") # creates text input field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name,",
"0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init attributes for text rects and",
"field as feedback def update_screen(self, events): \"\"\" implements changes that are needed by",
"return [] # this is so the text input does not activate while",
"self.container_english) # creates kana word img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color,",
"create_containers, place_buttons from helper.button import Button import text class H2R(object): \"\"\" A mode",
"Romaji exercise - creates container rects for the 3 main screen areas -",
"def _pick_word(self): \"\"\" picks a random Word instance from the app's vocab\"\"\" return",
"self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self):",
"creates kana word img self.str_kana_img, self.str_kana_rect = create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) #",
"_pick_word(self): \"\"\" picks a random Word instance from the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana))",
"# commented out because this is # handled in update method: # self.text_input.update(events)",
"__init__(self, app): \"\"\" initialises the Hiragana to Romaji exercise - creates container rects",
"text is correct for current word \"\"\" current_input = self.text_input.get_text().lower().strip() if current_input ==",
"TextInput from helper.pygame_helpers import create_centered_text, create_containers, place_buttons from helper.button import Button import text",
"# handled in update method: # self.text_input.update(events) if event.key == self.app.settings.key_help: self._help() if",
"does not activate while app is quitting if event.type == pygame.KEYUP: # if",
"# this is so the text input does not activate while app is",
"TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates",
"self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons self.butt_help =",
"EVENT HANDLING def check_events(self): \"\"\"Checks for and responds to mouse and kb events",
"self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length )",
"self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but, self.container_buttons) # draw bg of text input box if self.get_previous_try():",
"background of text input field as feedback def update_screen(self, events): \"\"\" implements changes",
"draws each element of H2R \"\"\" # draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen,",
"def _next_word(self): self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function): return Button(((0, 0),",
"events): \"\"\" implements changes that are needed by H2R at every tick, based",
"buttons pos_mouse = pygame.mouse.get_pos() for button in self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else:",
"updates previous try, to return input field to default color if text #",
"self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help,",
"the user needs to enter the correct romaji transliteration\"\"\" def __init__(self, app): \"\"\"",
"accordingly \"\"\" self.app = app # create and place container rects for different",
"(event.type == pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game() return [] # this is",
"input field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400, repeat_keys_interval_ms=35,",
"event in events: if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key",
"button in self.buttons: button.on_mouse() return events # getters/setters def get_previous_try(self): return self.previous_try def",
"create_containers( self.app.screen, (5 / 20, 6 / 20, 5 / 20, 4 /",
"default color if text # was erased if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self):",
"related to input box and RETURN kez are handled in update function\"\"\" events",
"a hiragana word is displayed, and the user needs to enter the correct",
"\\ self.container_buttons = create_containers( self.app.screen, (5 / 20, 6 / 20, 5 /",
"previous try, to return input field to default color if text # was",
"4 / 20), layout=\"V\") # creates text input field self.text_input = TextInput( initial_string=\"\",",
"# updates previous try, to return input field to default color if text",
"are needed by H2R at every tick, based on user events \"\"\" #",
"self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial status self.word",
"self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws each element of H2R \"\"\" # draw",
"repeat_keys_initial_ms=400, repeat_keys_interval_ms=35, max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame for input field self.input_frame =",
"in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) #",
"only if there is no text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw",
"frame for input field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center",
"creates buttons self.butt_help = self._h2r_button(text.h2r_button_help, self._help) self.butt_check = self._h2r_button(text.h2r_button_check, self._confirm_word) self.butt_quit = self._h2r_button(text.h2r_button_quit,",
"previous_try # HELPERS def _pick_word(self): \"\"\" picks a random Word instance from the",
"create_centered_text( self.word.english, self.app.settings.h2r_font_english, self.app.settings.h2r_font_english_color, self.container_english) # creates kana word img self.str_kana_img, self.str_kana_rect =",
"== self.app.settings.key_help: self._help() if event.type == pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse() return",
"layout=\"V\") # creates text input field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True,",
"self.str_english_img, self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect = None, None # create and",
"self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\")",
"pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse() return events # getters/setters def get_previous_try(self): return",
"return self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try() not in (None, \"right\", \"wrong\"): raise",
"self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether input text is correct",
"for input box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center #",
"draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom,",
"self.app.settings.key_confirm: # commented out because this is # handled in update method: #",
"word is displayed, and the user needs to enter the correct romaji transliteration\"\"\"",
"self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img,",
"correct for current word \"\"\" current_input = self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if",
"romaji transliteration\"\"\" def __init__(self, app): \"\"\" initialises the Hiragana to Romaji exercise -",
"self.butt_quit = self._h2r_button(text.h2r_button_quit, self.app.quit_game) self.buttons = [self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set",
"import random import pygame from helper.textinput import TextInput from helper.pygame_helpers import create_centered_text, create_containers,",
"self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect = None, None # create and place",
"element of H2R \"\"\" # draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english)",
"= pygame.event.get() for event in events: if event.type == pygame.QUIT or (event.type ==",
"box self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons pos_mouse = pygame.mouse.get_pos() for button in",
"there is no text in input field self.app.screen.blit(self.input_tip_img, self.input_tip_rect) # draw text input",
"pygame.event.get() for event in events: if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN",
"from helper.pygame_helpers import create_centered_text, create_containers, place_buttons from helper.button import Button import text class",
"self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates rect for input box",
"else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect)",
"and responds to mouse and kb events NOTE: kb events related to input",
"enter the correct romaji transliteration\"\"\" def __init__(self, app): \"\"\" initialises the Hiragana to",
"= self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt, function=function,",
"from helper.textinput import TextInput from helper.pygame_helpers import create_centered_text, create_containers, place_buttons from helper.button import",
"the app's vocab\"\"\" return random.choice(list(self.app.vocab.hiragana)) def _help(self): word = self.word.romaji self.text_input.set_text(word) self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\")",
"self.text_input_rect.center = self.input_frame.center # init attributes for text rects and images self.str_english_img, self.str_english_rect",
"20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates rect for input box self.text_input_rect =",
"attributes for text rects and images self.str_english_img, self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect",
"== self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def",
"self.app.settings.h2r_text_input_height) self.text_input_rect.center = self.input_frame.center # init attributes for text rects and images self.str_english_img,",
"the 3 main screen areas - selects a word - updates and draws",
"# creates rect for input box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center",
"max_string_length=self.app.settings.h2r_text_input_max_string_length ) # creates background frame for input field self.input_frame = pygame.Rect(0, 0,",
"= None, None self.str_kana_img, self.str_kana_rect = None, None # create and place input",
"event.type == pygame.MOUSEBUTTONUP: for button in self.buttons: button.on_mouse() return events # getters/setters def",
"areas - selects a word - updates and draws screen accordingly \"\"\" self.app",
"creates rect for input box self.text_input_rect = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width, self.app.settings.h2r_text_input_height) self.text_input_rect.center =",
"text input field self.text_input = TextInput( initial_string=\"\", font_family=self.app.settings.h2r_font_romaji.name, font_size=int(self.app.settings.h2r_font_romaji.size), antialias=True, text_color=self.app.settings.h2r_font_romaji_color, cursor_color=self.app.settings.h2r_font_romaji_color, repeat_keys_initial_ms=400,",
"self.container_kana) # updates text input box if self.text_input.update(events): self._confirm_word() # updates previous try,",
"input field as feedback def update_screen(self, events): \"\"\" implements changes that are needed",
"containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_rom, self.container_romaji) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_but,",
"def _confirm_word(self): \"\"\" checks whether input text is correct for current word \"\"\"",
"_next_word(self): self.word = self._pick_word() self.text_input.clear_text() def _h2r_button(self, txt, function): return Button(((0, 0), self.app.settings.h2r_button_size),",
"romaji_frame_color = self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input pygame.draw.rect(self.app.screen, romaji_frame_color,",
"self.input_frame.center = self.container_romaji.center # creates rect for input box self.text_input_rect = pygame.Rect(0, 0,",
"events \"\"\" # creates english word img self.str_english_img, self.str_english_rect = create_centered_text( self.word.english, self.app.settings.h2r_font_english,",
"for text rects and images self.str_english_img, self.str_english_rect = None, None self.str_kana_img, self.str_kana_rect =",
"self.str_kana_rect = None, None # create and place input tip self.input_tip_img, self.input_tip_rect =",
"create_centered_text( self.word.hiragana, self.app.settings.h2r_font_kana, self.app.settings.h2r_font_kana_color, self.container_kana) # updates text input box if self.text_input.update(events): self._confirm_word()",
"for previous try.\") self.previous_try = previous_try # HELPERS def _pick_word(self): \"\"\" picks a",
"kb events NOTE: kb events related to input box and RETURN kez are",
"self.buttons: if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT HANDLING def check_events(self):",
"[self.butt_help, self.butt_check, self.butt_quit] place_buttons(self.buttons, self.container_buttons) # set initial status self.word = self._pick_word() self.previous_try",
"so the text input does not activate while app is quitting if event.type",
"for event in events: if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and",
"self.container_romaji, \\ self.container_buttons = create_containers( self.app.screen, (5 / 20, 6 / 20, 5",
"place input tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates",
"alt=True) # EVENT HANDLING def check_events(self): \"\"\"Checks for and responds to mouse and",
"20, 4 / 20), layout=\"V\") # creates text input field self.text_input = TextInput(",
"20, 6 / 20, 5 / 20, 4 / 20), layout=\"V\") # creates",
"0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center = self.container_romaji.center # creates rect for input",
"== \"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color = self.app.settings.col_danger else: romaji_frame_color = self.app.settings.h2r_col_bg_input",
"draw_screen(self): \"\"\" draws each element of H2R \"\"\" # draw backgrounds of containers",
"text input box if self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success else:",
"NOTE: kb events related to input box and RETURN kez are handled in",
"# draw backgrounds of containers self.app.screen.fill(self.app.settings.col_dark) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_en, self.container_english) pygame.draw.rect(self.app.screen, self.app.settings.h2r_col_bg_kan, self.container_kana) pygame.draw.rect(self.app.screen,",
"if not button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT HANDLING def check_events(self): \"\"\"Checks",
"screen accordingly \"\"\" self.app = app # create and place container rects for",
"self.text_input.clear_text() def _h2r_button(self, txt, function): return Button(((0, 0), self.app.settings.h2r_button_size), text=txt, function=function, color_base=self.app.settings.h2r_button_color, color_alt=self.app.settings.h2r_button_color_alt,",
"container rects for different UI elements self.container_english, \\ self.container_kana, \\ self.container_romaji, \\ self.container_buttons",
"transliteration\"\"\" def __init__(self, app): \"\"\" initialises the Hiragana to Romaji exercise - creates",
"by H2R at every tick, based on user events \"\"\" # creates english",
"in self.buttons: button.on_mouse() return events # getters/setters def get_previous_try(self): return self.previous_try def set_previous_try(self,",
"this is # handled in update method: # self.text_input.update(events) if event.key == self.app.settings.key_help:",
"== pygame.KEYUP: # if event.key == self.app.settings.key_confirm: # commented out because this is",
"user needs to enter the correct romaji transliteration\"\"\" def __init__(self, app): \"\"\" initialises",
"input field to default color if text # was erased if not self.text_input.get_text():",
"input tip self.input_tip_img, self.input_tip_rect = create_centered_text( text.h2r_input_tip, self.app.settings.h2r_font_tip, self.app.settings.h2r_font_tip_color, self.container_romaji) # creates buttons",
"events related to input box and RETURN kez are handled in update function\"\"\"",
"initialises the Hiragana to Romaji exercise - creates container rects for the 3",
"3 main screen areas - selects a word - updates and draws screen",
"button.is_inside(pos_mouse): button.draw(self.app.screen) else: button.draw(self.app.screen, alt=True) # EVENT HANDLING def check_events(self): \"\"\"Checks for and",
"\"wrong\"): raise TypeError(\"Wrong argument for previous try.\") self.previous_try = previous_try # HELPERS def",
"box if self.get_previous_try(): if self.get_previous_try() == \"right\": romaji_frame_color = self.app.settings.col_success else: romaji_frame_color =",
"input text is correct for current word \"\"\" current_input = self.text_input.get_text().lower().strip() if current_input",
"pygame.KEYDOWN and event.key == self.app.settings.key_quit): self.app.quit_game() return [] # this is so the",
"activate while app is quitting if event.type == pygame.KEYUP: # if event.key ==",
"self.text_input.update(events): self._confirm_word() # updates previous try, to return input field to default color",
"current_input == self.word.romaji: if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\")",
"creates background frame for input field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20,",
"was erased if not self.text_input.get_text(): self.set_previous_try(None) def draw_screen(self): \"\"\" draws each element of",
"/ 20, 6 / 20, 5 / 20, 4 / 20), layout=\"V\") #",
"pygame.draw.rect(self.app.screen, romaji_frame_color, self.input_frame) # draw all texts self.app.screen.blit(self.str_english_img, self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not",
"and place container rects for different UI elements self.container_english, \\ self.container_kana, \\ self.container_romaji,",
"main screen areas - selects a word - updates and draws screen accordingly",
"helper.textinput import TextInput from helper.pygame_helpers import create_centered_text, create_containers, place_buttons from helper.button import Button",
"for button in self.buttons: button.on_mouse() return events # getters/setters def get_previous_try(self): return self.previous_try",
"self.str_english_rect) self.app.screen.blit(self.str_kana_img, self.str_kana_rect) if not self.text_input.get_text(): # only if there is no text",
"needs to enter the correct romaji transliteration\"\"\" def __init__(self, app): \"\"\" initialises the",
"place_buttons from helper.button import Button import text class H2R(object): \"\"\" A mode in",
"word \"\"\" current_input = self.text_input.get_text().lower().strip() if current_input == self.word.romaji: if self.get_previous_try() == \"right\":",
"checks whether input text is correct for current word \"\"\" current_input = self.text_input.get_text().lower().strip()",
"def get_previous_try(self): return self.previous_try def set_previous_try(self, previous_try): if self.get_previous_try() not in (None, \"right\",",
"# if event.key == self.app.settings.key_confirm: # commented out because this is # handled",
"event.key == self.app.settings.key_confirm: # commented out because this is # handled in update",
"self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word = self._pick_word() self.text_input.clear_text() def",
"self.text_input.set_cursor_position(len(word)) self.set_previous_try(\"right\") def _confirm_word(self): \"\"\" checks whether input text is correct for current",
"6 / 20, 5 / 20, 4 / 20), layout=\"V\") # creates text",
"self.app.screen.blit(self.text_input.get_surface(), self.text_input_rect) # draw all buttons pos_mouse = pygame.mouse.get_pos() for button in self.buttons:",
"handled in update method: # self.text_input.update(events) if event.key == self.app.settings.key_help: self._help() if event.type",
"event.type == pygame.KEYUP: # if event.key == self.app.settings.key_confirm: # commented out because this",
"import text class H2R(object): \"\"\" A mode in which a hiragana word is",
"for input field self.input_frame = pygame.Rect(0, 0, self.app.settings.h2r_text_input_width + 20, self.app.settings.h2r_text_input_height) self.input_frame.center =",
"if self.get_previous_try() == \"right\": self.set_previous_try(None) self._next_word() else: self.set_previous_try(\"right\") else: self.set_previous_try(\"wrong\") def _next_word(self): self.word"
] |
[
"face-pair to be strictly coincide at initial state \"\"\" if not isinstance(obj, ElementsBody):",
"outer vertex, and 12 edges, and 6 faces, with three steps: 1. make",
"\\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of ylines",
"\\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has been written. \" )) elif input( \"\\033[32;1m",
"the Nset with open(path + '{}_nset.txt'.format(job), 'w') as file: for node in obj.getFaceNode():",
"{}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {},",
"obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes for periodic",
"\"\"\" use graph-method to get the PBC info, write the PBC for the",
"to new file if \"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'): clone = False",
"= True def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes for periodic boundary condition",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm))",
"coincide file.write('************************** make all outer edges to coincide \\n') edgeId = [ [[0,",
"dm)) # 3. make all corresponding face-pairs to coincide file.write('************************** make all corresponding",
"v1------v5 ---> / x z \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not",
"get the inp file and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp",
"when there are many many nodes on a surface (with time complexity of",
"faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: for dm in [1, 2, 3]:",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm))",
"not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode()",
"for edge in edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] +",
"are many many nodes on a surface (with time complexity of O(V^2)). \"\"\"",
"the line from old file to new file if \"*Node\\n\" in line: if",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{},",
"ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for",
"{}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make all outer edges to coincide",
"simply by coordinates of all nodes. This method can only be applied to",
"range(len(edge['inside'])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"## 1.2 make vertexes of ylines to form parallel hexahedron file.write('************************** make vertexes",
"node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes =",
"parallogram \\n') for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1",
"face-pairs to coincide \\n') edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]:",
"the object with cuboid shape. Two methods match nodes on opposites of the",
"ylines to form parallel hexahedron file.write('************************** make vertexes of 4 ylines to coincide",
"node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node],",
"PBC 3. make the inside nodes of face-pair to coincide \"\"\" if not",
"line: writeEquations(newFile, obj, instance) if clone == False and '*' in line: clone",
"if __name__ == \"__main__\": testState = False # get the inp file and",
"\"1: graph-method (recomended); \\n\" \"2: xMin, xMax, yMin, yMax, zMin, zMax; \\n(insert 1",
"to map facet-nodes to element-number, where the surface-facet is shared by only one",
"-1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm)) # 3. make",
"| | | | | v2----|-v6 y ^ |/ |/ | v1------v5 --->",
"for node in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]]",
"obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes",
"raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False",
"3. make all corresponding face-pairs to coincide for twoFacets in obj.faceMatch: faceMatch =",
"{}, 1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody): raise",
"[[1, 0], [5, 4], [6, 7], [2, 3]], # yEdges [[2, 1], [6,",
"{}, 1 \\n'.format(instance, obj.megaElement[5], dm)) # 2. make all outer edges to coincide",
"# find the instance name instance = 'Part-1' with open(inpFile, 'r') as file:",
"print('instance =', instance) break writeInp = input( 'ok to write the .inp file",
"and '*' in line: clone = True if clone: newFile.write(line) # write the",
"method do you want to use? \\n\" \"1: graph-method (recomended); \\n\" \"2: xMin,",
"arbitrary deformed shape): use dictionary-data-structure to map facet-nodes to element-number, where the surface-facet",
"1], [6, 5], [7, 4], [3, 0]] # zEdges ] for edges in",
"for iface, face in enumerate(obj.faceMatch): for node in face: for dm in [1,",
"coincide edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge in",
"dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm))",
"obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1,",
"yMax, zMin, zMax; \\n(insert 1 or 2): \" )) if key == \"1\":",
"obj.zlines]: for edge in edges: edgeNodes |= ({edge['beg']} | {edge['end']} | set(edge['inside'])) for",
"edgeId = [ [[0, 4], [3, 7], [2, 6], [1, 5]], # xEdges",
"coincide file.write('************************** make all outer edges to coincide \\n') xyzEdges = [obj.xlines, obj.ylines,",
"obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC =",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2],",
"\\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method to get the",
"Matching nodes during traversing of surface-node-graphs of opposite faces. Given a matched node-pair,",
"the node-relation, adjust the nodal coordiantes for periodic boundary condition (PBC) make the",
"the PBC for the 8 outer vertex, and 12 edges, and 6 faces,",
"== \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key",
"obj) elif '*End Assembly' in line: writeEquations(newFile, obj, instance) if clone == False",
"only be applied to the object with cuboid shape. Two methods match nodes",
"V and E are number of nodes and edges respectively): Matching nodes during",
"obj.nodes[obj.ylines[0]['beg']] # 2. make all outer edges to coincide xyzEdges = [obj.xlines, obj.ylines,",
"with open(path + '{}_nset.txt'.format(job), 'w') as file: for node in obj.getFaceNode(): file.write('*Nset, nset=N{}",
"+ \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of ylines to form",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{},",
"obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make all outer edges to coincide xyzEdges =",
"False for node in obj.nodes: if type(obj.nodes[node]) == type([]): makenp = True break",
"edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for edge in edges[1:]: edge1",
"(obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for dm in [1, 2, 3]: file.write('*Equation\\n4",
"-1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make",
"number of nodes and edges respectively): Matching nodes during traversing of surface-node-graphs of",
"file name (include the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile",
"[1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {},",
"in obj.nodes: if type(obj.nodes[node]) == type([]): makenp = True break if makenp: for",
"instance): \"\"\" use graph-method to get the PBC info, write the PBC for",
"')) if adjustCoor == 'y': adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC() # find",
"obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of ylines to",
"by coordinates of all nodes. This method can only be applied to the",
")) elif input( \"\\033[32;1m write nset- and equations- files for PBC? (y/n): \\033[0m\"",
"coincide \\n') for i, j in [[7, 6], [3, 2], [0, 1]]: for",
"coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in ['y', 'n']:",
"dm)) ## 1.2 make vertexes of ylines to form parallel hexahedron file.write('************************** make",
"to satisfy PBC 3. make the inside nodes of face-pair to coincide \"\"\"",
"obj.nodes[edge0[0]] # 3. make all corresponding face-pairs to coincide for twoFacets in obj.faceMatch:",
"Could be very slow when there are many many nodes on a surface",
"vertexes of ylines to form parallel hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']] =",
"write_PBC_Nset(newFile, obj) elif '*End Assembly' in line: writeEquations(newFile, obj, instance) if clone ==",
"edgeId: # edges = xEdges or yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]])",
"file if \"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new",
"'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {}",
"= obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC",
"hexahedron file.write('************************** make vertexes of 4 ylines to coincide \\n') for i, j",
"\\033[0m\".format( \"file\", newFileName, \"has been written. \" )) elif input( \"\\033[32;1m write nset-",
"^ |/ |/ | v1------v5 ---> / x z \"\"\" if not isinstance(obj,",
"= line.split(',') instance = instance[1].split('=') instance = instance[-1] print('instance =', instance) break writeInp",
"nodes: file.write(' {}, {}, {}, {} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] )) def",
"\\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make all corresponding face-pairs",
"8 outer vertex, and 12 edges, and 6 faces, with three steps: 1.",
"obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make all corresponding face-pairs to",
"the inside nodes of face-pair to coincide \"\"\" if not isinstance(obj, ElementsBody): raise",
"detect the surface simply by coordinates of all nodes. This method can only",
"in obj.ylines[1:]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1",
"obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1],",
"the surface simply by coordinates of all nodes. This method can only be",
"= False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m",
"Nset with open(path + '{}_nset.txt'.format(job), 'w') as file: for node in obj.getFaceNode(): file.write('*Nset,",
"for the 8 outer vertex, and 12 edges, and 6 faces, with three",
"\"y\" or \"n\": ')) if adjustCoor == 'y': adjustCoordinate(obj) if testState: del obj.faceMatch",
"\\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"on a surface (with time complexity of O(V^2)). \"\"\" import torch as tch",
"facet-nodes to element-number, where the surface-facet is shared by only one element. Construct",
"'w') as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\",",
"obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node],",
"of xMin, xMax, yMin, yMax, zMin, zMax: detect the surface simply by coordinates",
"inp file and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name",
"\\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"open(newFileName, 'w') as newFile, open(inpFile, 'r') as oldFile: clone = True for line",
"4], [3, 0]] # zEdges ] for edges in edgeId: # edges =",
"edge0[0], dm)) # 3. make all corresponding face-pairs to coincide file.write('************************** make all",
"outer vertexes to form a parallel hexahedron (平行六面体)) 2. make 12 edges to",
"\\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__ ==",
"dm)) # 2. make all outer edges to coincide file.write('************************** make all outer",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm))",
"\".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want to",
"obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make all corresponding face-pairs to coincide edgeNodes =",
"file.write('************************** make all corresponding face-pairs to coincide \\n') for twoFacets in obj.faceMatch: faceMatch",
"zEdges ] for edges in edgeId: # edges = xEdges or yEdges or",
"of 4 ylines to coincide \\n') for yline in obj.ylines[1:]: for dm in",
"for i, j in [[7, 6], [3, 2], [0, 1]]: for dm in",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) #",
"instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_equation.txt'.format(job), \"has been",
"twoFacets[4], dm)) def write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj,",
"and 6 faces, with three steps: 1. make the 8 outer vertexes to",
"for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0,",
"to neighbors) to match their neighbors. 2. nearest-coordinates method: Could be very slow",
"shape. Two methods match nodes on opposites of the surface: 1. BFS method",
"1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1",
"[2, 6], [1, 5]], # xEdges [[1, 0], [5, 4], [6, 7], [2,",
"in faceMatch: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1",
"to be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ##",
"outlines. Using outlines as boundaries, partition the graph into different faces (left-, right-,",
"outlines as boundaries, partition the graph into different faces (left-, right-, down-, up-,",
"is shown as follows, v3------v7 /| /| v0------v4| | | | | |",
"in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1",
"= [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for edge in edges[1:]: for",
"coordiantes for periodic boundary condition (PBC) make the nodes at face-pair to be",
"in [\"y\", \"\"]: # write the Nset with open(path + '{}_nset.txt'.format(job), 'w') as",
"strictly coincide at initial state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not",
"{}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2.",
"get the PBC info, write the PBC for the 8 outer vertex, and",
"to coincide \\n') for yline in obj.ylines[1:]: for dm in [1, 2, 3]:",
"face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\"",
"vertex, and 12 edges, and 6 faces, with three steps: 1. make the",
"job + \"_PBC.inp\" with open(newFileName, 'w') as newFile, open(inpFile, 'r') as oldFile: clone",
"\\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make vertexes",
"for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: for dm",
"outer edges to coincide \\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in",
"you want to adjust the coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while",
"\\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has been written. \" )) #",
"not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for node",
"path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path =",
"2. make 12 edges to satisfy PBC 3. make the inside nodes of",
"edges in edgeId: # edges = xEdges or yEdges or zEdges edge0 =",
"different faces (left-, right-, down-, up-, back-, front- surfaces) by union-find algorithm. 2.",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm)) #",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm))",
"zMin, zMax: detect the surface simply by coordinates of all nodes. This method",
"obj.ylines[1:]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1",
"[3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]]",
"inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key =",
"break if makenp: for node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make",
"{}, 1 \\n'.format(instance, edges[0]['beg'], dm)) # 3. make all corresponding face-pairs to coincide",
"not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make",
"with three steps: 1. make the 8 outer vertexes to form a parallel",
"coincide \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not",
"adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you want to adjust the coordinates",
"use similar vectors (pointed from current node to neighbors) to match their neighbors.",
"[3, 7], [2, 6], [1, 5]], # xEdges [[1, 0], [5, 4], [6,",
"file with PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not",
"PBC info, write the PBC for the 8 outer vertex, and 12 edges,",
"{edge['end']} | set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in face: for",
"of megaElement (composed of vertex of outer surface) is shown as follows, v3------v7",
"form parallel hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\",
"\\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm)) # 3. make all",
"1. BFS method to match the nodes (time complexity of O(V + E),",
"1 \\n'.format(instance, edge0[0], dm)) # 3. make all corresponding face-pairs to coincide file.write('**************************",
"= ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want to use? \\n\"",
"{} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_equation.txt'.format(job), \"has been written. \"",
"as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path",
"open(path + '{}_nset.txt'.format(job), 'w') as file: for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node))",
"use dictionary-data-structure to map facet-nodes to element-number, where the surface-facet is shared by",
"')) while adjustCoor not in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or",
"PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in ['y', 'n']: adjustCoor =",
"= input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": ')) if adjustCoor == 'y': adjustCoordinate(obj) if",
"of surface, and the node-linking graph of the outlines. Using outlines as boundaries,",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm))",
"a matched node-pair, use similar vectors (pointed from current node to neighbors) to",
"\\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make all outer edges",
"only one element. Construct the node-linking graph of surface, and the node-linking graph",
"+ \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want",
"method to get the node-relation, adjust the nodal coordiantes for periodic boundary condition",
"coincide for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]]",
"testState: del obj.faceMatch getFaceForPBC() # find the instance name instance = 'Part-1' with",
"yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'],",
"open(inpFile, 'r') as file: for line in file: if '*Instance' in line and",
"obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make all corresponding face-pairs to coincide for twoFacets",
"obj.ylines, obj.zlines]: for edge in edges: edgeNodes |= ({edge['beg']} | {edge['end']} | set(edge['inside']))",
"import * def write_PBC_equation(file, obj, instance): \"\"\" write the PBC for the 8",
"= inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do",
"in line and \"**\" in line: write_PBC_Nset(newFile, obj) elif '*End Assembly' in line:",
"=', instance) break writeInp = input( 'ok to write the .inp file with",
"if clone: newFile.write(line) # write the line from old file to new file",
"input(\"do you want to adjust the coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): '))",
"{}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {},",
"clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {}",
"1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1",
"\"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert",
"obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1,",
"initial state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph()",
"dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm))",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ##",
") in [\"y\", \"\"]: # write the Nset with open(path + '{}_nset.txt'.format(job), 'w')",
"many many nodes on a surface (with time complexity of O(V^2)). \"\"\" import",
"\\n'.format(instance, edge0[0], dm)) # 3. make all corresponding face-pairs to coincide file.write('************************** make",
"\"n\": ')) if adjustCoor == 'y': adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC() #",
"[6, 7], [2, 3]], # yEdges [[2, 1], [6, 5], [7, 4], [3,",
"as follows, v3------v7 /| /| v0------v4| | | | | | v2----|-v6 y",
"\"which method do you want to use? \\n\" \"1: graph-method (recomended); \\n\" \"2:",
"ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face to be parallogram file.write('************************** make",
"(composed of vertex of outer surface) is shown as follows, v3------v7 /| /|",
"to adjust the coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not",
"# write the Nset with open(path + '{}_nset.txt'.format(job), 'w') as file: for node",
"file and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name (include",
"input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want to use? \\n\" \"1: graph-method (recomended); \\n\"",
"nodal coordiantes for periodic boundary condition (PBC) make the nodes at face-pair to",
"the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name (include the path):",
"for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in ['y', 'n']: adjustCoor",
"input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\": ' )) if writeInp == 'y': newFileName",
"3. make the inside nodes of face-pair to coincide \"\"\" if not isinstance(obj,",
"+ '{}_nset.txt'.format(job), \"has been written. \" )) # write the equation for PBC",
"file.write(' {}, {}, {}, {} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj):",
"def write_PBC_equation(file, obj, instance): \"\"\" write the PBC for the 8 outer vertex,",
"dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm))",
"face: for dm in [1, 2, 3]: if node not in edgeNodes: file.write('*Equation\\n4",
"4], [3, 7], [2, 6], [1, 5]], # xEdges [[1, 0], [5, 4],",
"for node in range(len(edge['inside'])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{},",
"\\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"\\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job),",
"all outer edges to coincide file.write('************************** make all outer edges to coincide \\n')",
"-1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1",
"obj.megaElement[1], dm)) ## 1.2 make vertexes of ylines to form parallel hexahedron file.write('**************************",
"def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes for periodic boundary condition (PBC) make",
"graph method to get the node-relation, adjust the nodal coordiantes for periodic boundary",
"{edge['end']} | set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in face: if",
"= \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make all corresponding",
")) if key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate =",
"node-linking graph of the outlines. Using outlines as boundaries, partition the graph into",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method",
"getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do",
"[[7, 6], [3, 2], [0, 1]]: for dm in [1, 2, 3]: file.write('*Equation\\n4",
"(obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]],",
"True if __name__ == \"__main__\": testState = False # get the inp file",
"y0face to be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1])",
"2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1",
"not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for node in obj.nodes: if type(obj.nodes[node])",
"edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'],",
"'faceNode'): obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file,",
"\\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal",
"xMin, xMax, yMin, yMax, zMin, zMax; \\n(insert 1 or 2): \" )) if",
"adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC() # find the instance name instance =",
"6 faces, with three steps: 1. make the 8 outer vertexes to form",
"= True if __name__ == \"__main__\": testState = False # get the inp",
"obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for node in obj.nodes: if type(obj.nodes[node]) == type([]):",
"import torch as tch import numpy as np from elementsBody import * def",
"{}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make vertexes of ylines to form",
"2. nearest-coordinates method: Could be very slow when there are many many nodes",
"\\n(insert 1 or 2): \" )) if key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph",
"obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj):",
"'Part-1' with open(inpFile, 'r') as file: for line in file: if '*Instance' in",
"if key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph",
"be very slow when there are many many nodes on a surface (with",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0],",
"the surface-nodes: 1. graph-method: (recommended, can deal with arbitrary deformed shape): use dictionary-data-structure",
"for dm in [1, 2, 3]: if node not in edgeNodes: file.write('*Equation\\n4 \\n')",
"1.2 make vertexes of ylines to form parallel hexahedron file.write('************************** make vertexes of",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm))",
"\\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj): if",
"obj.nodesAdjusted = True if __name__ == \"__main__\": testState = False # get the",
"from elementsBody import * def write_PBC_equation(file, obj, instance): \"\"\" write the PBC for",
"make all corresponding face-pairs to coincide \\n') edgeNodes = set() for edges in",
"if makenp: for node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm))",
"make all outer edges to coincide \\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for",
"isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the y0face to",
"all outer edges to coincide edgeId = [ [[0, 4], [3, 7], [2,",
"= \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make vertexes of ylines to",
"\\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make all outer edges to coincide edgeId",
"face-pairs to coincide for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in",
"if not hasattr(obj, 'faceNode'): obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{},",
"obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5],",
"node in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted",
"state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph()",
"obj.outlines: for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])):",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make all outer edges to",
"file to new file if \"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'): clone =",
"1. graph-method: (recommended, can deal with arbitrary deformed shape): use dictionary-data-structure to map",
"for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node,",
"for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes",
"can only be applied to the object with cuboid shape. Two methods match",
"obj.zlines] for edges in xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])):",
"been written. \" )) # write the equation for PBC with open(path +",
"to be strictly coincide at initial state \"\"\" if not isinstance(obj, ElementsBody): raise",
"obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if",
"map facet-nodes to element-number, where the surface-facet is shared by only one element.",
"'please insert \"y\" or \"n\": ' )) if writeInp == 'y': newFileName =",
"match their neighbors. 2. nearest-coordinates method: Could be very slow when there are",
"newFileName, \"has been written. \" )) elif input( \"\\033[32;1m write nset- and equations-",
"and E are number of nodes and edges respectively): Matching nodes during traversing",
"nodes at face-pair to be strictly coincide at initial state \"\"\" if not",
"parallogram file.write('************************** make the y0face to be parallogram \\n') for dm in [1,",
"- obj.nodes[obj.megaElement[5]] # 2. make all outer edges to coincide edgeId = [",
"edges to coincide file.write('************************** make all outer edges to coincide \\n') edgeId =",
"make all outer edges to coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges",
"dictionary-data-structure to map facet-nodes to element-number, where the surface-facet is shared by only",
"faceMatch: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"def write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if",
"\\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of ylines",
"isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for node in",
"- obj.nodes[edges[0]['beg']] # 3. make all corresponding face-pairs to coincide edgeNodes = set()",
"ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the",
"= False # get the inp file and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please",
"elif '*End Assembly' in line: writeEquations(newFile, obj, instance) if clone == False and",
"match nodes on opposites of the surface: 1. BFS method to match the",
"= obj.nodes for node in nodes: file.write(' {}, {}, {}, {} \\n'.format( node,",
"{}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {},",
"or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for edge in",
"[0, 1]]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1",
"obj.nodes: if type(obj.nodes[node]) == type([]): makenp = True break if makenp: for node",
"\\n'.format(instance, obj.megaElement[5], dm)) # 2. make all outer edges to coincide file.write('************************** make",
"the y0face to be parallogram file.write('************************** make the y0face to be parallogram \\n')",
"{}, {}, {} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use",
"in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": ')) if adjustCoor",
"obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: for dm in [1, 2,",
"\\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path +",
"dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm))",
"type([]): makenp = True break if makenp: for node in obj.nodes: obj.nodes[node] =",
"in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format(",
"__name__ == \"__main__\": testState = False # get the inp file and the",
"faces, with three steps: 1. make the 8 outer vertexes to form a",
"for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'],",
"if hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile, obj)",
"\\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make all corresponding face-pairs",
"\"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ##",
"file.write('************************** make all corresponding face-pairs to coincide \\n') edgeNodes = set() for edges",
"[[7, 6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]]",
"can deal with arbitrary deformed shape): use dictionary-data-structure to map facet-nodes to element-number,",
"outer surface) is shown as follows, v3------v7 /| /| v0------v4| | | |",
"== type([]): makenp = True break if makenp: for node in obj.nodes: obj.nodes[node]",
"in [[7, 6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm))",
"to form parallel hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] +",
"corresponding face-pairs to coincide for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{},",
"elif key == \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC",
"- obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__ == \"__main__\": testState = False #",
"{}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make vertexes of ylines to form",
"[[2, 1], [6, 5], [7, 4], [3, 0]] # zEdges ] for edges",
"in oldFile: if \"Section:\" in line and \"**\" in line: write_PBC_Nset(newFile, obj) elif",
"for PBC? (y/n): \\033[0m\" ) in [\"y\", \"\"]: # write the Nset with",
"up-, back-, front- surfaces) by union-find algorithm. 2. method of xMin, xMax, yMin,",
"Assembly' in line: writeEquations(newFile, obj, instance) if clone == False and '*' in",
"with PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not in",
"to form parallel hexahedron for i, j in [[7, 6], [3, 2], [0,",
"nodes (time complexity of O(V + E), V and E are number of",
"time complexity of O(V^2)). \"\"\" import torch as tch import numpy as np",
"use? \\n\" \"1: graph-method (recomended); \\n\" \"2: xMin, xMax, yMin, yMax, zMin, zMax;",
"= inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0]",
"= adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate",
"obj.nodes[obj.megaElement[5]] # 2. make all outer edges to coincide edgeId = [ [[0,",
"{}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {},",
"= True if clone: newFile.write(line) # write the line from old file to",
"instance name instance = 'Part-1' with open(inpFile, 'r') as file: for line in",
"clone = True for line in oldFile: if \"Section:\" in line and \"**\"",
"open(path + '{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m",
"the instance name instance = 'Part-1' with open(inpFile, 'r') as file: for line",
"(pointed from current node to neighbors) to match their neighbors. 2. nearest-coordinates method:",
"ylines to coincide \\n') for yline in obj.ylines[1:]: for dm in [1, 2,",
"for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has",
"edges[1:]: for node in range(len(edge['inside'])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n')",
"= (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\",
"input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name (include the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0]",
")) if writeInp == 'y': newFileName = path + job + \"_PBC.inp\" with",
"obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make all",
"= write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you want to adjust",
"for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i],",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm))",
"obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.megaElement[6]] =",
"writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\": ' )) if writeInp ==",
"enumerate(obj.faceMatch): for node in face: if node not in edgeNodes: obj.nodes[node] = \\",
"make 12 edges to satisfy PBC 3. make the inside nodes of face-pair",
"== 'y': adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC() # find the instance name",
"obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make all",
"to use? \\n\" \"1: graph-method (recomended); \\n\" \"2: xMin, xMax, yMin, yMax, zMin,",
"corresponding face-pairs to coincide edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]:",
"{}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2",
"to coincide \\n') edgeId = [ [[0, 4], [3, 7], [2, 6], [1,",
"yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for edge",
"coincide \\n') for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch:",
"inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which",
"writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC = obj.getFaceForPBC",
"\\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has been written. \" )) # write the",
"if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for node in obj.nodes: if",
"v2----|-v6 y ^ |/ |/ | v1------v5 ---> / x z \"\"\" if",
"in range(len(obj.outlines[edge0])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1",
"as file: for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {}",
"[1, 2, 3]: if node not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1",
"insert \"y\" or \"n\": ')) if adjustCoor == 'y': adjustCoordinate(obj) if testState: del",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm))",
"if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'):",
"| v1------v5 ---> / x z \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error,",
"isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face to be parallogram file.write('**************************",
"\\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make all corresponding face-pairs to coincide for",
"-1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm)) # 2. make",
"[1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {},",
"\\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make all corresponding face-pairs to coincide edgeNodes",
"not in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted",
"1. make the 8 outer vertexes to form a parallel hexahedron (平行六面体)) 2.",
"= input(\"do you want to adjust the coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n):",
"hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for node in obj.nodes: if type(obj.nodes[node]) ==",
"match the nodes (time complexity of O(V + E), V and E are",
"the outlines. Using outlines as boundaries, partition the graph into different faces (left-,",
"{} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method",
"make the nodes at face-pair to be strictly coincide at initial state \"\"\"",
"tch import numpy as np from elementsBody import * def write_PBC_equation(file, obj, instance):",
"-1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1",
"obj.nodes for node in nodes: file.write(' {}, {}, {}, {} \\n'.format( node, nodes[node][0],",
"numpy as np from elementsBody import * def write_PBC_equation(file, obj, instance): \"\"\" write",
"- obj.nodes[obj.ylines[0]['beg']] # 2. make all outer edges to coincide xyzEdges = [obj.xlines,",
"coincide file.write('************************** make all corresponding face-pairs to coincide \\n') edgeNodes = set() for",
"\\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make vertexes of ylines to form parallel hexahedron",
"np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]]",
"to be parallogram file.write('************************** make the y0face to be parallogram \\n') for dm",
"1 \\n'.format(instance, edges[0]['beg'], dm)) # 3. make all corresponding face-pairs to coincide file.write('**************************",
"not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for node in obj.nodes: if",
"obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method to get the PBC",
"make all corresponding face-pairs to coincide file.write('************************** make all corresponding face-pairs to coincide",
"{} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_equation.txt'.format(job), \"has been written. \" ))",
"get the node-relation, adjust the nodal coordiantes for periodic boundary condition (PBC) make",
"(obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of ylines to form parallel hexahedron",
"\\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make vertexes",
"1 or 2): \" )) if key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations",
"\\n\" \"2: xMin, xMax, yMin, yMax, zMin, zMax; \\n(insert 1 or 2): \"",
"if edge0 in obj.outlines: for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for",
"\\n') for i, j in [[7, 6], [3, 2], [0, 1]]: for dm",
")) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to get the node-relation, adjust the",
"in xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\",
"adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation",
"{} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has been written. \" )) elif input(",
"obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make all outer edges to",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{},",
"make vertexes of 4 ylines to coincide \\n') for i, j in [[7,",
"key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif",
"in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{},",
"x z \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph()",
"follows, v3------v7 /| /| v0------v4| | | | | | v2----|-v6 y ^",
"vertexes of 4 ylines to coincide \\n') for i, j in [[7, 6],",
".inp file with PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp",
"opposite faces. Given a matched node-pair, use similar vectors (pointed from current node",
"name (include the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else",
"dm in [1, 2, 3]: if node not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{},",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj): if not isinstance(obj,",
"form parallel hexahedron file.write('************************** make vertexes of 4 ylines to coincide \\n') for",
"{} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has been written. \" )) # write",
"all nodes. This method can only be applied to the object with cuboid",
"' )) if writeInp == 'y': newFileName = path + job + \"_PBC.inp\"",
"obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face to be parallogram file.write('************************** make the",
"{}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {},",
"(left-, right-, down-, up-, back-, front- surfaces) by union-find algorithm. 2. method of",
"and \"**\" in line: write_PBC_Nset(newFile, obj) elif '*End Assembly' in line: writeEquations(newFile, obj,",
"surface) is shown as follows, v3------v7 /| /| v0------v4| | | | |",
"obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm)) # 3. make all corresponding",
"(y/n): \\033[0m\" ) in [\"y\", \"\"]: # write the Nset with open(path +",
"obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes = obj.nodes for",
"= path + job + \"_PBC.inp\" with open(newFileName, 'w') as newFile, open(inpFile, 'r')",
"{}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file,",
"\"2\": getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor =",
"\"n\": ' )) if writeInp == 'y': newFileName = path + job +",
"in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted =",
"obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.v_x1y0z0] =",
"a parallel hexahedron (平行六面体)) 2. make 12 edges to satisfy PBC 3. make",
"enumerate(obj.faceMatch): for node in face: for dm in [1, 2, 3]: if node",
"= input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\": ' )) if writeInp == 'y':",
"True if clone: newFile.write(line) # write the line from old file to new",
"\"Section:\" in line and \"**\" in line: write_PBC_Nset(newFile, obj) elif '*End Assembly' in",
"obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_equation.txt'.format(job), \"has",
"newFileName = path + job + \"_PBC.inp\" with open(newFileName, 'w') as newFile, open(inpFile,",
"parallel hexahedron file.write('************************** make vertexes of 4 ylines to coincide \\n') for i,",
"the inp file and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file",
"to the object with cuboid shape. Two methods match nodes on opposites of",
"2. make all outer edges to coincide edgeId = [ [[0, 4], [3,",
"the nodes (time complexity of O(V + E), V and E are number",
"file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has",
"are number of nodes and edges respectively): Matching nodes during traversing of surface-node-graphs",
"in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{},",
"edges to satisfy PBC 3. make the inside nodes of face-pair to coincide",
"to get the node-relation, adjust the nodal coordiantes for periodic boundary condition (PBC)",
"\"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for",
"+ \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__ == \"__main__\": testState",
"deal with arbitrary deformed shape): use dictionary-data-structure to map facet-nodes to element-number, where",
"in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\",
"as tch import numpy as np from elementsBody import * def write_PBC_equation(file, obj,",
"xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): for dm in [1,",
"{} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has been written. \"",
"for edges in xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]]",
"2], [0, 1]]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {},",
"2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1",
"in line: writeEquations(newFile, obj, instance) if clone == False and '*' in line:",
"+ job + \"_PBC.inp\" with open(newFileName, 'w') as newFile, open(inpFile, 'r') as oldFile:",
"if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1",
"'y': newFileName = path + job + \"_PBC.inp\" with open(newFileName, 'w') as newFile,",
"= (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for edge in edges[1:]: edge1 =",
"obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] -",
"make the y0face to be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]]",
"to get the PBC info, write the PBC for the 8 outer vertex,",
"+ \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make all outer edges to coincide",
"/| /| v0------v4| | | | | | v2----|-v6 y ^ |/ |/",
"getFaceForPBC() # find the instance name instance = 'Part-1' with open(inpFile, 'r') as",
"edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] =",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm))",
"np from elementsBody import * def write_PBC_equation(file, obj, instance): \"\"\" write the PBC",
"\"\"\" import torch as tch import numpy as np from elementsBody import *",
"to coincide file.write('************************** make all corresponding face-pairs to coincide \\n') edgeNodes = set()",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j],",
"nodes and edges respectively): Matching nodes during traversing of surface-node-graphs of opposite faces.",
"'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\": ' )) if writeInp",
"[6, 5], [7, 4], [3, 0]] # zEdges ] for edges in edgeId:",
"nodes during traversing of surface-node-graphs of opposite faces. Given a matched node-pair, use",
"/ x z \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\")",
"y0face to be parallogram file.write('************************** make the y0face to be parallogram \\n') for",
"obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes",
"for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node],",
"\\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm))",
"condition (PBC) make the nodes at face-pair to be strictly coincide at initial",
"new nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\",",
"line: instance = line.split(',') instance = instance[1].split('=') instance = instance[-1] print('instance =', instance)",
"nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to get the node-relation, adjust",
"1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1",
"in edges: edgeNodes |= ({edge['beg']} | {edge['end']} | set(edge['inside'])) for iface, face in",
"all outer edges to coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in",
"file.write('************************** make vertexes of 4 ylines to coincide \\n') for i, j in",
"megaElement (composed of vertex of outer surface) is shown as follows, v3------v7 /|",
"surface-node-graphs of opposite faces. Given a matched node-pair, use similar vectors (pointed from",
"coincide file.write('************************** make all corresponding face-pairs to coincide \\n') for twoFacets in obj.faceMatch:",
"if clone == False and '*' in line: clone = True if clone:",
"in [[7, 6], [3, 2], [0, 1]]: for dm in [1, 2, 3]:",
"of vertex of outer surface) is shown as follows, v3------v7 /| /| v0------v4|",
"for edge in edges[1:]: for node in range(len(edge['inside'])): for dm in [1, 2,",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm))",
"PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not in ['y',",
"isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for",
"edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0],",
"+ E), V and E are number of nodes and edges respectively): Matching",
"in line: if hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\"))",
"\\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"[\"y\", \"\"]: # write the Nset with open(path + '{}_nset.txt'.format(job), 'w') as file:",
"method to match the nodes (time complexity of O(V + E), V and",
"coincide edgeId = [ [[0, 4], [3, 7], [2, 6], [1, 5]], #",
"to write the .inp file with PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ')",
"obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make all corresponding face-pairs to",
"obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make vertexes of",
"with open(newFileName, 'w') as newFile, open(inpFile, 'r') as oldFile: clone = True for",
"open(inpFile, 'r') as oldFile: clone = True for line in oldFile: if \"Section:\"",
"make all outer edges to coincide \\n') edgeId = [ [[0, 4], [3,",
"adjustCoor not in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": '))",
"graph-method to get the PBC info, write the PBC for the 8 outer",
"adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you want to adjust the coordinates for PBC?",
"outer edges to coincide \\n') edgeId = [ [[0, 4], [3, 7], [2,",
"to be parallogram \\n') for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{},",
"if \"Section:\" in line and \"**\" in line: write_PBC_Nset(newFile, obj) elif '*End Assembly'",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm))",
"periodic boundary condition (PBC) make the nodes at face-pair to be strictly coincide",
"-1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1",
"make the inside nodes of face-pair to coincide \"\"\" if not isinstance(obj, ElementsBody):",
"input( \"\\033[32;1m write nset- and equations- files for PBC? (y/n): \\033[0m\" ) in",
"the y0face to be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] -",
"# 3. make all corresponding face-pairs to coincide edgeNodes = set() for edges",
"[1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {},",
"all outer edges to coincide \\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges",
"= xEdges or yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in",
"obj.v_x0y0z1, dm)) ## 1.2 make vertexes of ylines to form parallel hexahedron file.write('**************************",
"vertexes of ylines to form parallel hexahedron for i, j in [[7, 6],",
"inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0] obj",
"obj.faceMatch[twoFacets] for node in faceMatch: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n')",
"writeInp not in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\":",
"or 2): \" )) if key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations =",
"in enumerate(obj.faceMatch): for node in face: if node not in edgeNodes: obj.nodes[node] =",
"faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True",
"edges: edgeNodes |= ({edge['beg']} | {edge['end']} | set(edge['inside'])) for iface, face in enumerate(obj.faceMatch):",
"line: write_PBC_Nset(newFile, obj) elif '*End Assembly' in line: writeEquations(newFile, obj, instance) if clone",
"old file to new file if \"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'): clone",
"1.1 make the y0face to be parallogram file.write('************************** make the y0face to be",
"\\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_equation.txt'.format(job), \"has been written.",
"opposites of the surface: 1. BFS method to match the nodes (time complexity",
"method can only be applied to the object with cuboid shape. Two methods",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0],",
"surface simply by coordinates of all nodes. This method can only be applied",
"to match their neighbors. 2. nearest-coordinates method: Could be very slow when there",
"coincide \\n') for yline in obj.ylines[1:]: for dm in [1, 2, 3]: file.write('*Equation\\n4",
"dm)) def write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\")",
"nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName,",
"the surface-facet is shared by only one element. Construct the node-linking graph of",
"obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm)) # 2. make all outer",
"obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\" adjust",
"the inside nodes of face-pair to coincide the node-number of megaElement (composed of",
"= input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want to use? \\n\" \"1: graph-method (recomended);",
"inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not in ['y', 'n']:",
"line and 'name=' in line: instance = line.split(',') instance = instance[1].split('=') instance =",
"by only one element. Construct the node-linking graph of surface, and the node-linking",
"be parallogram file.write('************************** make the y0face to be parallogram \\n') for dm in",
"# 3. make all corresponding face-pairs to coincide for twoFacets in obj.faceMatch: faceMatch",
"# write the line from old file to new file if \"*Node\\n\" in",
"'r') as oldFile: clone = True for line in oldFile: if \"Section:\" in",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm))",
"nodes on opposites of the surface: 1. BFS method to match the nodes",
"on opposites of the surface: 1. BFS method to match the nodes (time",
"node not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{},",
"j in [[7, 6], [3, 2], [0, 1]]: for dm in [1, 2,",
"all corresponding face-pairs to coincide for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for",
"{}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {},",
"want to use? \\n\" \"1: graph-method (recomended); \\n\" \"2: xMin, xMax, yMin, yMax,",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm))",
"for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m",
"O(V + E), V and E are number of nodes and edges respectively):",
"one element. Construct the node-linking graph of surface, and the node-linking graph of",
"respectively): Matching nodes during traversing of surface-node-graphs of opposite faces. Given a matched",
"/| v0------v4| | | | | | v2----|-v6 y ^ |/ |/ |",
"from current node to neighbors) to match their neighbors. 2. nearest-coordinates method: Could",
"and 12 edges, and 6 faces, with three steps: 1. make the 8",
"\\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm)) # 2. make all",
"5]], # xEdges [[1, 0], [5, 4], [6, 7], [2, 3]], # yEdges",
"coincide \\n') edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge",
"be strictly coincide at initial state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error,",
"surface: 1. BFS method to match the nodes (time complexity of O(V +",
"corresponding face-pairs to coincide file.write('************************** make all corresponding face-pairs to coincide \\n') for",
"corresponding face-pairs to coincide \\n') edgeNodes = set() for edges in [obj.xlines, obj.ylines,",
"= instance[-1] print('instance =', instance) break writeInp = input( 'ok to write the",
"\\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"y ^ |/ |/ | v1------v5 ---> / x z \"\"\" if not",
"write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations =",
"= \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make all corresponding",
"dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method to get the PBC info,",
"front- surfaces) by union-find algorithm. 2. method of xMin, xMax, yMin, yMax, zMin,",
"hexahedron for i, j in [[7, 6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] =",
"---> / x z \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj,",
"edges respectively): Matching nodes during traversing of surface-node-graphs of opposite faces. Given a",
"raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make",
"[1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {},",
"dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm))",
"steps: 1. make the 8 outer vertexes to form a parallel hexahedron (平行六面体))",
"write the Nset with open(path + '{}_nset.txt'.format(job), 'w') as file: for node in",
"job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job +",
"by union-find algorithm. 2. method of xMin, xMax, yMin, yMax, zMin, zMax: detect",
"twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: for dm in",
"for iface, face in enumerate(obj.faceMatch): for node in face: if node not in",
"parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make",
"xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']]",
"node-number of megaElement (composed of vertex of outer surface) is shown as follows,",
"obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]])",
"{}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm)) # 3.",
"boundary condition (PBC) make the nodes at face-pair to be strictly coincide at",
"condition (PBC). Two methods to detect and partition the surface-nodes: 1. graph-method: (recommended,",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make vertexes of ylines to",
"3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"coincide \\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for edge",
"+ '{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {}",
"(PBC). Two methods to detect and partition the surface-nodes: 1. graph-method: (recommended, can",
"with open(path + '{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {}",
"into different faces (left-, right-, down-, up-, back-, front- surfaces) by union-find algorithm.",
"\\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please",
"methods match nodes on opposites of the surface: 1. BFS method to match",
"for yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']]",
"name instance = 'Part-1' with open(inpFile, 'r') as file: for line in file:",
"be parallogram \\n') for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {},",
"satisfy PBC 3. make the inside nodes of face-pair to coincide the node-number",
"written. \" )) # write the equation for PBC with open(path + '{}_equation.txt'.format(job),",
"1 \\n'.format(instance, obj.megaElement[5], dm)) # 2. make all outer edges to coincide file.write('**************************",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm)) # 3. make all corresponding face-pairs to",
"form a parallel hexahedron (平行六面体)) 2. make 12 edges to satisfy PBC 3.",
"obj.getEdgeVertexForPBC() makenp = False for node in obj.nodes: if type(obj.nodes[node]) == type([]): makenp",
"i, j in [[7, 6], [3, 2], [0, 1]]: for dm in [1,",
"in file: if '*Instance' in line and 'name=' in line: instance = line.split(',')",
"ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want to use? \\n\" \"1:",
"for node in range(len(obj.outlines[edge0])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{},",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{},",
"instance) break writeInp = input( 'ok to write the .inp file with PBC",
"in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key",
"input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": ')) if adjustCoor == 'y': adjustCoordinate(obj) if testState:",
"obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.v_x1y0z0]",
"\"2: xMin, xMax, yMin, yMax, zMin, zMax; \\n(insert 1 or 2): \" ))",
"edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge in edges:",
"obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] +",
"new file if \"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write",
"\" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please",
"inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you",
"write_PBC_equation(file, obj, instance): \"\"\" write the PBC for the 8 outer vertex, and",
"graph into different faces (left-, right-, down-, up-, back-, front- surfaces) by union-find",
"1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody): raise ValueError(\"error,",
"{}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {},",
"in range(len(edge['inside'])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1",
"surface, and the node-linking graph of the outlines. Using outlines as boundaries, partition",
"object with cuboid shape. Two methods match nodes on opposites of the surface:",
"faces. Given a matched node-pair, use similar vectors (pointed from current node to",
"and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name (include the",
"there are many many nodes on a surface (with time complexity of O(V^2)).",
"in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{},",
"if writeInp == 'y': newFileName = path + job + \"_PBC.inp\" with open(newFileName,",
"ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face to be",
"nodes. This method can only be applied to the object with cuboid shape.",
"'ok to write the .inp file with PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n):",
"- obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes for",
"edges to coincide edgeId = [ [[0, 4], [3, 7], [2, 6], [1,",
"write the line from old file to new file if \"*Node\\n\" in line:",
"union-find algorithm. 2. method of xMin, xMax, yMin, yMax, zMin, zMax: detect the",
"or yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for",
"edges to coincide file.write('************************** make all outer edges to coincide \\n') xyzEdges =",
"0]] # zEdges ] for edges in edgeId: # edges = xEdges or",
"equations- files for PBC? (y/n): \\033[0m\" ) in [\"y\", \"\"]: # write the",
"node in face: if node not in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] +",
"file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path",
"'w') as file: for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m",
")) # write the equation for PBC with open(path + '{}_equation.txt'.format(job), 'w') as",
"This method can only be applied to the object with cuboid shape. Two",
"del obj.faceMatch getFaceForPBC() # find the instance name instance = 'Part-1' with open(inpFile,",
"1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make all outer edges to coincide file.write('**************************",
"obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__ == \"__main__\":",
"y0face to be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]])",
"if type(obj.nodes[node]) == type([]): makenp = True break if makenp: for node in",
"isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset, nset=N{}",
"ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node))",
"\\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm))",
"all corresponding face-pairs to coincide \\n') edgeNodes = set() for edges in [obj.xlines,",
"edges in xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): for dm",
"be applied to the object with cuboid shape. Two methods match nodes on",
"obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you want",
"-1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1",
"find the instance name instance = 'Part-1' with open(inpFile, 'r') as file: for",
"as file: for line in file: if '*Instance' in line and 'name=' in",
"in obj.outlines: for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in",
"set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in face: if node not",
"| {edge['end']} | set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in face:",
"break writeInp = input( 'ok to write the .inp file with PBC inside",
"down-, up-, back-, front- surfaces) by union-find algorithm. 2. method of xMin, xMax,",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm)) #",
"writeInp = input( 'ok to write the .inp file with PBC inside the",
"1.2 make vertexes of ylines to form parallel hexahedron for yline in obj.ylines[1:]:",
"2. make all outer edges to coincide file.write('************************** make all outer edges to",
"dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm))",
"- obj.nodes[edge0[0]] # 3. make all corresponding face-pairs to coincide for twoFacets in",
"in line and 'name=' in line: instance = line.split(',') instance = instance[1].split('=') instance",
"O(V^2)). \"\"\" import torch as tch import numpy as np from elementsBody import",
"the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path",
"recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\"",
"obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make all outer edges to",
"{}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {},",
"\\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make all outer edges to coincide xyzEdges",
"nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes = obj.nodes for node in",
"'*End Assembly' in line: writeEquations(newFile, obj, instance) if clone == False and '*'",
"\\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of ylines to form parallel",
"to element-number, where the surface-facet is shared by only one element. Construct the",
"xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for edge in edges[1:]:",
"info, write the PBC for the 8 outer vertex, and 12 edges, and",
"not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset,",
"node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] #",
"matched node-pair, use similar vectors (pointed from current node to neighbors) to match",
"nodes on a surface (with time complexity of O(V^2)). \"\"\" import torch as",
"\"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile))",
"12 edges to satisfy PBC 3. make the inside nodes of face-pair to",
"## 1.1 make the y0face to be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] +",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{},",
"ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for node in obj.nodes: if type(obj.nodes[node]) ==",
"or \"n\": ' )) if writeInp == 'y': newFileName = path + job",
"== \"__main__\": testState = False # get the inp file and the object",
"= np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.v_x1y0z0] = \\",
"the node-linking graph of surface, and the node-linking graph of the outlines. Using",
"ylines to coincide \\n') for i, j in [[7, 6], [3, 2], [0,",
"to coincide file.write('************************** make all outer edges to coincide \\n') xyzEdges = [obj.xlines,",
"is shared by only one element. Construct the node-linking graph of surface, and",
"1.1 make the y0face to be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\",
"2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1",
"make the y0face to be parallogram file.write('************************** make the y0face to be parallogram",
"= \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of",
"obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of ylines to form parallel hexahedron for yline",
"True break if makenp: for node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1",
"obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make all outer",
"of ylines to form parallel hexahedron for i, j in [[7, 6], [3,",
"line from old file to new file if \"*Node\\n\" in line: if hasattr(obj,",
"\\n') for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"{}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method to",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'],",
"- obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of ylines to form parallel hexahedron for",
"if node not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm))",
"of opposite faces. Given a matched node-pair, use similar vectors (pointed from current",
"obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes for periodic boundary",
"\"has been written. \" )) # write the equation for PBC with open(path",
"-1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj):",
"for yline in obj.ylines[1:]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{},",
"1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make vertexes of ylines to form parallel",
"raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for node in",
"surface (with time complexity of O(V^2)). \"\"\" import torch as tch import numpy",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{},",
"'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": ')) if adjustCoor == 'y':",
"{}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {},",
"surfaces) by union-find algorithm. 2. method of xMin, xMax, yMin, yMax, zMin, zMax:",
"of 4 ylines to coincide \\n') for i, j in [[7, 6], [3,",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm))",
"[1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {},",
"corresponding face-pairs to coincide \\n') for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for",
"applied to the object with cuboid shape. Two methods match nodes on opposites",
"\\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to",
"= False for node in obj.nodes: if type(obj.nodes[node]) == type([]): makenp = True",
"\\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"the 8 outer vertex, and 12 edges, and 6 faces, with three steps:",
"[ [[0, 4], [3, 7], [2, 6], [1, 5]], # xEdges [[1, 0],",
"vertexes of 4 ylines to coincide \\n') for yline in obj.ylines[1:]: for dm",
"4 ylines to coincide \\n') for yline in obj.ylines[1:]: for dm in [1,",
"coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for edge in",
"do you want to use? \\n\" \"1: graph-method (recomended); \\n\" \"2: xMin, xMax,",
"graph of surface, and the node-linking graph of the outlines. Using outlines as",
"to coincide \\n') for i, j in [[7, 6], [3, 2], [0, 1]]:",
"obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of ylines to",
"## 1.2 make vertexes of ylines to form parallel hexahedron for i, j",
"element-number, where the surface-facet is shared by only one element. Construct the node-linking",
"edges[0]['beg'], dm)) # 3. make all corresponding face-pairs to coincide file.write('************************** make all",
"line in file: if '*Instance' in line and 'name=' in line: instance =",
"\" )) # write the equation for PBC with open(path + '{}_equation.txt'.format(job), 'w')",
"zMin, zMax; \\n(insert 1 or 2): \" )) if key == \"1\": getFaceForPBC",
"-1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1",
"writeEquations(newFile, obj, instance) if clone == False and '*' in line: clone =",
"obj.ylines[0]['beg'], dm)) # 2. make all outer edges to coincide file.write('************************** make all",
"shape): use dictionary-data-structure to map facet-nodes to element-number, where the surface-facet is shared",
"faces (left-, right-, down-, up-, back-, front- surfaces) by union-find algorithm. 2. method",
"three steps: 1. make the 8 outer vertexes to form a parallel hexahedron",
"+ \"_PBC.inp\" with open(newFileName, 'w') as newFile, open(inpFile, 'r') as oldFile: clone =",
"[1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {},",
"\\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\"",
"file.write('************************** make vertexes of 4 ylines to coincide \\n') for yline in obj.ylines[1:]:",
"for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]]",
"node-relation, adjust the nodal coordiantes for periodic boundary condition (PBC) make the nodes",
"be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2",
"you want to use? \\n\" \"1: graph-method (recomended); \\n\" \"2: xMin, xMax, yMin,",
"the node-linking graph of the outlines. Using outlines as boundaries, partition the graph",
"in enumerate(obj.faceMatch): for node in face: for dm in [1, 2, 3]: if",
"make vertexes of ylines to form parallel hexahedron for i, j in [[7,",
"obj): if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj,",
"where the surface-facet is shared by only one element. Construct the node-linking graph",
"in [1, 2, 3]: if node not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {},",
"nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to get the node-relation,",
"= obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node]",
"not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False",
"| set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in face: if node",
"very slow when there are many many nodes on a surface (with time",
"xEdges or yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines:",
"parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make",
"writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_equation.txt'.format(job),",
"parallel hexahedron for i, j in [[7, 6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]]",
"\\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has been",
"'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the y0face to be parallogram file.write('************************** make the",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm)) # 2. make all outer edges to",
"set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge in edges: edgeNodes |=",
"back-, front- surfaces) by union-find algorithm. 2. method of xMin, xMax, yMin, yMax,",
"edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]]",
"edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True",
"graph of the outlines. Using outlines as boundaries, partition the graph into different",
"\\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {}",
"the file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not in ['y', 'n']: writeInp",
"make the y0face to be parallogram \\n') for dm in [1, 2, 3]:",
"# 3. make all corresponding face-pairs to coincide file.write('************************** make all corresponding face-pairs",
"\"file\", newFileName, \"has been written. \" )) elif input( \"\\033[32;1m write nset- and",
"12 edges, and 6 faces, with three steps: 1. make the 8 outer",
"\\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm)) # 3. make all",
"7], [2, 3]], # yEdges [[2, 1], [6, 5], [7, 4], [3, 0]]",
"# edges = xEdges or yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if",
"= True break if makenp: for node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ##",
"[5, 4], [6, 7], [2, 3]], # yEdges [[2, 1], [6, 5], [7,",
"set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in face: for dm in",
"Using outlines as boundaries, partition the graph into different faces (left-, right-, down-,",
"the node-number of megaElement (composed of vertex of outer surface) is shown as",
"file.write('************************** make the y0face to be parallogram \\n') for dm in [1, 2,",
"False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {}",
"range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make",
"similar vectors (pointed from current node to neighbors) to match their neighbors. 2.",
"yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] #",
"[3, 0]] # zEdges ] for edges in edgeId: # edges = xEdges",
"line: if hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile,",
"of O(V^2)). \"\"\" import torch as tch import numpy as np from elementsBody",
"# 2. make all outer edges to coincide file.write('************************** make all outer edges",
"not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {},",
"obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of ylines to form parallel hexahedron for i,",
"of all nodes. This method can only be applied to the object with",
"obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def",
"'*Instance' in line and 'name=' in line: instance = line.split(',') instance = instance[1].split('=')",
"* def write_PBC_equation(file, obj, instance): \"\"\" write the PBC for the 8 outer",
"method: Could be very slow when there are many many nodes on a",
"obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has been",
"complexity of O(V^2)). \"\"\" import torch as tch import numpy as np from",
"ylines to form parallel hexahedron for i, j in [[7, 6], [3, 2],",
"node in range(len(obj.outlines[edge0])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {},",
"edgeNodes |= ({edge['beg']} | {edge['end']} | set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for",
"coincide \\n') edgeId = [ [[0, 4], [3, 7], [2, 6], [1, 5]],",
"neighbors. 2. nearest-coordinates method: Could be very slow when there are many many",
"to coincide edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge",
"node in faceMatch: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {},",
"writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you want to",
"write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has been written.",
"+ \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\" adjust the",
"3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"edges in [obj.xlines, obj.ylines, obj.zlines]: for edge in edges: edgeNodes |= ({edge['beg']} |",
"1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1",
"| | | | v2----|-v6 y ^ |/ |/ | v1------v5 ---> /",
"== \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor",
"v3------v7 /| /| v0------v4| | | | | | v2----|-v6 y ^ |/",
"({edge['beg']} | {edge['end']} | set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in",
"## 1.1 make the y0face to be parallogram file.write('************************** make the y0face to",
"periodic boundary condition (PBC). Two methods to detect and partition the surface-nodes: 1.",
"adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": ')) if adjustCoor == 'y': adjustCoordinate(obj)",
"\"\"\" adjust the nodal coordiantes for periodic boundary condition (PBC) make the nodes",
"print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has been written.",
"use graph method to get the node-relation, adjust the nodal coordiantes for periodic",
"face in enumerate(obj.faceMatch): for node in face: for dm in [1, 2, 3]:",
"2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1",
"in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]]",
"state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not",
"6], [1, 5]], # xEdges [[1, 0], [5, 4], [6, 7], [2, 3]],",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{},",
"to coincide edgeId = [ [[0, 4], [3, 7], [2, 6], [1, 5]],",
"vertexes to form a parallel hexahedron (平行六面体)) 2. make 12 edges to satisfy",
"isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the",
"coincide at initial state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj,",
"adjustCoor == 'y': adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC() # find the instance",
"vertex of outer surface) is shown as follows, v3------v7 /| /| v0------v4| |",
"obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make vertexes of",
"\"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj,",
"['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": ')) if adjustCoor ==",
"face-pairs to coincide \\n') for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node",
"of face-pair to coincide \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj,",
"insert the .inp file name (include the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if",
"{}, 1 \\n'.format(instance, edge0[0], dm)) # 3. make all corresponding face-pairs to coincide",
"node in nodes: file.write(' {}, {}, {}, {} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2]",
"2. make all outer edges to coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for",
"of ylines to form parallel hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\",
"obj.getEdgeVertexForPBC() ## 1.1 make the y0face to be parallogram file.write('************************** make the y0face",
"in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\": ' ))",
"+ '{}_nset.txt'.format(job), 'w') as file: for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{},",
"to coincide file.write('************************** make all corresponding face-pairs to coincide \\n') for twoFacets in",
"their neighbors. 2. nearest-coordinates method: Could be very slow when there are many",
"in edges[1:]: for node in range(len(edge['inside'])): for dm in [1, 2, 3]: file.write('*Equation\\n4",
"zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0 in obj.outlines: for edge in edges[1:]:",
"3. make all corresponding face-pairs to coincide edgeNodes = set() for edges in",
"2): \" )) if key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph",
"{}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {},",
"inside nodes of face-pair to coincide the node-number of megaElement (composed of vertex",
"if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0] obj =",
"+ \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make all outer edges to coincide",
"ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1",
"-1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make",
"8 outer vertexes to form a parallel hexahedron (平行六面体)) 2. make 12 edges",
"to coincide the node-number of megaElement (composed of vertex of outer surface) is",
"obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1],",
"object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name (include the path): \"))",
"vectors (pointed from current node to neighbors) to match their neighbors. 2. nearest-coordinates",
"current node to neighbors) to match their neighbors. 2. nearest-coordinates method: Could be",
"'{}_nset.txt'.format(job), \"has been written. \" )) # write the equation for PBC with",
"make all outer edges to coincide edgeId = [ [[0, 4], [3, 7],",
"for node in faceMatch: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{},",
"obj.faceMatch getFaceForPBC() # find the instance name instance = 'Part-1' with open(inpFile, 'r')",
"Given a matched node-pair, use similar vectors (pointed from current node to neighbors)",
"line: clone = True if clone: newFile.write(line) # write the line from old",
"obj.nodes[edges[0]['beg']] # 3. make all corresponding face-pairs to coincide edgeNodes = set() for",
"slow when there are many many nodes on a surface (with time complexity",
"'y': adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC() # find the instance name instance",
"been written. \" )) elif input( \"\\033[32;1m write nset- and equations- files for",
"-1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj,",
"# write the equation for PBC with open(path + '{}_equation.txt'.format(job), 'w') as file:",
"j in [[7, 6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] +",
"not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the y0face to be parallogram file.write('**************************",
"of ylines to form parallel hexahedron file.write('************************** make vertexes of 4 ylines to",
"3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"\"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp",
"of the outlines. Using outlines as boundaries, partition the graph into different faces",
"and equations- files for PBC? (y/n): \\033[0m\" ) in [\"y\", \"\"]: # write",
"# zEdges ] for edges in edgeId: # edges = xEdges or yEdges",
"3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm)) def",
"+ \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of ylines to form",
"2, 3]: if node not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode() for node",
"in edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]]",
"## 1.2 make vertexes of ylines to form parallel hexahedron for yline in",
"written. \" )) elif input( \"\\033[32;1m write nset- and equations- files for PBC?",
"faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\",
"'{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format(",
"form parallel hexahedron for i, j in [[7, 6], [3, 2], [0, 1]]:",
"adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to get the node-relation, adjust the nodal coordiantes",
"writeInp == 'y': newFileName = path + job + \"_PBC.inp\" with open(newFileName, 'w')",
"adjust the nodal coordiantes for periodic boundary condition (PBC) make the nodes at",
"hasattr(obj, 'faceNode'): obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def",
"node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face to be",
"-1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1",
"\\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody): raise ValueError(\"error, not",
"'r') as file: for line in file: if '*Instance' in line and 'name='",
"the coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in ['y',",
"obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__ == \"__main__\": testState = False",
"to detect and partition the surface-nodes: 1. graph-method: (recommended, can deal with arbitrary",
"obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make all",
"equation for PBC with open(path + '{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj, instance)",
"insert \"y\" or \"n\": ' )) if writeInp == 'y': newFileName = path",
"Two methods to detect and partition the surface-nodes: 1. graph-method: (recommended, can deal",
"'{}_nset.txt'.format(job), 'w') as file: for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node))",
"\\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes = obj.nodes for node in nodes:",
"## 1.1 make the y0face to be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] +",
"inside nodes of face-pair to coincide \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error,",
"and the node-linking graph of the outlines. Using outlines as boundaries, partition the",
"obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.megaElement[6]]",
"type(obj.nodes[node]) == type([]): makenp = True break if makenp: for node in obj.nodes:",
"edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node],",
"= [ [[0, 4], [3, 7], [2, 6], [1, 5]], # xEdges [[1,",
"face-pairs to coincide edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for",
"as boundaries, partition the graph into different faces (left-, right-, down-, up-, back-,",
"\"\"\" generate periodic boundary condition (PBC). Two methods to detect and partition the",
"twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4],",
"instance = 'Part-1' with open(inpFile, 'r') as file: for line in file: if",
"oldFile: clone = True for line in oldFile: if \"Section:\" in line and",
"for periodic boundary condition (PBC) make the nodes at face-pair to be strictly",
"obj, instance): \"\"\" use graph-method to get the PBC info, write the PBC",
"edge0 in obj.outlines: for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node",
"newFile.write(line) # write the line from old file to new file if \"*Node\\n\"",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody):",
"to coincide \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if",
"for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node],",
"1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1",
"1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make vertexes of ylines to form parallel",
"edges to coincide \\n') edgeId = [ [[0, 4], [3, 7], [2, 6],",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm))",
"write_nodes(file, obj): nodes = obj.nodes for node in nodes: file.write(' {}, {}, {},",
"method of xMin, xMax, yMin, yMax, zMin, zMax: detect the surface simply by",
"node in range(len(edge['inside'])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {},",
"nodes of face-pair to coincide \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not",
"faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file, obj): if not",
"all corresponding face-pairs to coincide edgeNodes = set() for edges in [obj.xlines, obj.ylines,",
"oldFile: if \"Section:\" in line and \"**\" in line: write_PBC_Nset(newFile, obj) elif '*End",
"edge in edges: edgeNodes |= ({edge['beg']} | {edge['end']} | set(edge['inside'])) for iface, face",
"instance = instance[-1] print('instance =', instance) break writeInp = input( 'ok to write",
"partition the surface-nodes: 1. graph-method: (recommended, can deal with arbitrary deformed shape): use",
"in line: clone = True if clone: newFile.write(line) # write the line from",
"make the 8 outer vertexes to form a parallel hexahedron (平行六面体)) 2. make",
"of O(V + E), V and E are number of nodes and edges",
"line and \"**\" in line: write_PBC_Nset(newFile, obj) elif '*End Assembly' in line: writeEquations(newFile,",
"(include the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0]",
"PBC with open(path + '{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m {}",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0,",
"\\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make all",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ##",
"def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method to get the PBC info, write",
"1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make",
"not hasattr(obj, 'faceNode'): obj.getFaceNode() for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node))",
"|/ |/ | v1------v5 ---> / x z \"\"\" if not isinstance(obj, ElementsBody):",
"# yEdges [[2, 1], [6, 5], [7, 4], [3, 0]] # zEdges ]",
"for edges in edgeId: # edges = xEdges or yEdges or zEdges edge0",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2 make vertexes of ylines",
"the graph into different faces (left-, right-, down-, up-, back-, front- surfaces) by",
"-1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1",
"use graph-method to get the PBC info, write the PBC for the 8",
"{}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {},",
"at initial state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\")",
"to be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ##",
"hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the y0face to be parallogram file.write('************************** make",
"adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes for periodic boundary condition (PBC) make the",
"face-pair to coincide the node-number of megaElement (composed of vertex of outer surface)",
"\\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make vertexes of ylines to form parallel hexahedron",
"graph-method (recomended); \\n\" \"2: xMin, xMax, yMin, yMax, zMin, zMax; \\n(insert 1 or",
"ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp =",
"while adjustCoor not in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\":",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{},",
"\\n\" \"1: graph-method (recomended); \\n\" \"2: xMin, xMax, yMin, yMax, zMin, zMax; \\n(insert",
"of nodes and edges respectively): Matching nodes during traversing of surface-node-graphs of opposite",
"in nodes: file.write(' {}, {}, {}, {} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] ))",
"3. make the inside nodes of face-pair to coincide the node-number of megaElement",
"obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face to be parallogram file.write('************************** make the y0face",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{},",
"True def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes for periodic boundary condition (PBC)",
"of surface-node-graphs of opposite faces. Given a matched node-pair, use similar vectors (pointed",
"make the y0face to be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1]",
"edges = xEdges or yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]], obj.megaElement[edges[0][1]]) if edge0",
"{}, -1 \\n'.format(instance, edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm)) # 3.",
"outer edges to coincide edgeId = [ [[0, 4], [3, 7], [2, 6],",
"obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make",
"to satisfy PBC 3. make the inside nodes of face-pair to coincide the",
"= (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for dm in [1, 2, 3]:",
"elif input( \"\\033[32;1m write nset- and equations- files for PBC? (y/n): \\033[0m\" )",
"file: for node in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {}",
"for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]]",
"[7, 4], [3, 0]] # zEdges ] for edges in edgeId: # edges",
"boundaries, partition the graph into different faces (left-, right-, down-, up-, back-, front-",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make all outer edges",
"make all corresponding face-pairs to coincide edgeNodes = set() for edges in [obj.xlines,",
"| set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node in face: for dm",
"\"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key ==",
"adjustCoor = input(\"do you want to adjust the coordinates for PBC? \" \"(not",
"import numpy as np from elementsBody import * def write_PBC_equation(file, obj, instance): \"\"\"",
"v0------v4| | | | | | v2----|-v6 y ^ |/ |/ | v1------v5",
"node, nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to get",
"E), V and E are number of nodes and edges respectively): Matching nodes",
"the y0face to be parallogram obj.nodes[obj.megaElement[6]] = \\ obj.nodes[obj.megaElement[2]] + \\ (obj.nodes[obj.megaElement[5]] -",
"\\033[0m\" ) in [\"y\", \"\"]: # write the Nset with open(path + '{}_nset.txt'.format(job),",
"boundary condition (PBC). Two methods to detect and partition the surface-nodes: 1. graph-method:",
"to coincide \\n') for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in",
"all corresponding face-pairs to coincide \\n') for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets]",
"7], [2, 6], [1, 5]], # xEdges [[1, 0], [5, 4], [6, 7],",
"\\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__ == \"__main__\": testState =",
"{}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {},",
"{}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {},",
"(recomended); \\n\" \"2: xMin, xMax, yMin, yMax, zMin, zMax; \\n(insert 1 or 2):",
"write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you want to adjust the",
"in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{},",
"for node in face: for dm in [1, 2, 3]: if node not",
"\\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"for edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for",
"testState = False # get the inp file and the object inpFile =",
"isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for node in obj.nodes: if type(obj.nodes[node])",
"ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for node",
"# 2. make all outer edges to coincide edgeId = [ [[0, 4],",
"face: if node not in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]]",
"+ \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3. make all corresponding face-pairs to coincide",
"in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram",
"obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5],",
"# get the inp file and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the",
"'*' in line: clone = True if clone: newFile.write(line) # write the line",
"\\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"edges to coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for",
"generate periodic boundary condition (PBC). Two methods to detect and partition the surface-nodes:",
"False and '*' in line: clone = True if clone: newFile.write(line) # write",
"instance): \"\"\" write the PBC for the 8 outer vertex, and 12 edges,",
"with cuboid shape. Two methods match nodes on opposites of the surface: 1.",
"edge in edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\",
"obj.ylines, obj.zlines] for edges in xyzEdges: for edge in edges[1:]: for node in",
"for edge in edges: edgeNodes |= ({edge['beg']} | {edge['end']} | set(edge['inside'])) for iface,",
"from old file to new file if \"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'):",
"as newFile, open(inpFile, 'r') as oldFile: clone = True for line in oldFile:",
"adjust the coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor not in",
"np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0]",
"= np.array(obj.nodes[node]) ## 1.1 make the y0face to be parallogram obj.nodes[obj.megaElement[6]] = \\",
"to coincide for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch:",
"6], [3, 2], [0, 1]]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n')",
"obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n')",
"inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name (include the path): \")) job",
"xMax, yMin, yMax, zMin, zMax; \\n(insert 1 or 2): \" )) if key",
"of face-pair to coincide the node-number of megaElement (composed of vertex of outer",
"print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has been written. \" ))",
"(obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]]",
"| | | v2----|-v6 y ^ |/ |/ | v1------v5 ---> / x",
"in face: if node not in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\",
"xMax, yMin, yMax, zMin, zMax: detect the surface simply by coordinates of all",
"4], [6, 7], [2, 3]], # yEdges [[2, 1], [6, 5], [7, 4],",
"instance[-1] print('instance =', instance) break writeInp = input( 'ok to write the .inp",
"3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"PBC? (y/n): \\033[0m\" ) in [\"y\", \"\"]: # write the Nset with open(path",
"in line: instance = line.split(',') instance = instance[1].split('=') instance = instance[-1] print('instance =',",
"make all corresponding face-pairs to coincide for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets]",
"if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the y0face to be parallogram",
"= 'Part-1' with open(inpFile, 'r') as file: for line in file: if '*Instance'",
"\" )) if key == \"1\": getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate",
"all outer edges to coincide \\n') edgeId = [ [[0, 4], [3, 7],",
"print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format(",
"\\n') for yline in obj.ylines[1:]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n')",
"2. method of xMin, xMax, yMin, yMax, zMin, zMax: detect the surface simply",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def",
"parallel hexahedron (平行六面体)) 2. make 12 edges to satisfy PBC 3. make the",
"E are number of nodes and edges respectively): Matching nodes during traversing of",
"not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face to be parallogram",
"if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'):",
"make vertexes of 4 ylines to coincide \\n') for yline in obj.ylines[1:]: for",
"traversing of surface-node-graphs of opposite faces. Given a matched node-pair, use similar vectors",
"shown as follows, v3------v7 /| /| v0------v4| | | | | | v2----|-v6",
"makenp = True break if makenp: for node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node])",
"|/ | v1------v5 ---> / x z \"\"\" if not isinstance(obj, ElementsBody): raise",
"file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes = obj.nodes for node in nodes: file.write('",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'],",
"write the PBC for the 8 outer vertex, and 12 edges, and 6",
"1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1",
"face-pairs to coincide file.write('************************** make all corresponding face-pairs to coincide \\n') for twoFacets",
"if '*Instance' in line and 'name=' in line: instance = line.split(',') instance =",
"to form parallel hexahedron file.write('************************** make vertexes of 4 ylines to coincide \\n')",
"\\n'.format(node)) def write_nodes(file, obj): nodes = obj.nodes for node in nodes: file.write(' {},",
"coordinates of all nodes. This method can only be applied to the object",
"isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode() for",
"5], [7, 4], [3, 0]] # zEdges ] for edges in edgeId: #",
"yline in obj.ylines[1:]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {},",
"-1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make",
"the equation for PBC with open(path + '{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj,",
"during traversing of surface-node-graphs of opposite faces. Given a matched node-pair, use similar",
"not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC()",
"isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp",
"\\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"make the inside nodes of face-pair to coincide the node-number of megaElement (composed",
"in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{},",
"raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode() for node in",
"element. Construct the node-linking graph of surface, and the node-linking graph of the",
"= set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge in edges: edgeNodes",
"face in enumerate(obj.faceMatch): for node in face: if node not in edgeNodes: obj.nodes[node]",
"nodes = obj.nodes for node in nodes: file.write(' {}, {}, {}, {} \\n'.format(",
"nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", path +",
"zMax: detect the surface simply by coordinates of all nodes. This method can",
"to coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for edge",
"shared by only one element. Construct the node-linking graph of surface, and the",
"make vertexes of ylines to form parallel hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']]",
"[1, 5]], # xEdges [[1, 0], [5, 4], [6, 7], [2, 3]], #",
"\"file\", path + '{}_nset.txt'.format(job), \"has been written. \" )) # write the equation",
"[obj.xlines, obj.ylines, obj.zlines]: for edge in edges: edgeNodes |= ({edge['beg']} | {edge['end']} |",
"of the surface: 1. BFS method to match the nodes (time complexity of",
"= \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__",
"right-, down-, up-, back-, front- surfaces) by union-find algorithm. 2. method of xMin,",
"\"**\" in line: write_PBC_Nset(newFile, obj) elif '*End Assembly' in line: writeEquations(newFile, obj, instance)",
"graph-method: (recommended, can deal with arbitrary deformed shape): use dictionary-data-structure to map facet-nodes",
"# xEdges [[1, 0], [5, 4], [6, 7], [2, 3]], # yEdges [[2,",
"= instance[1].split('=') instance = instance[-1] print('instance =', instance) break writeInp = input( 'ok",
"instance) if clone == False and '*' in line: clone = True if",
"for node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face to",
"hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes for obj\")) write_nodes(newFile, obj) print(\"\\033[40;36;1m",
"{}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm)) # 2.",
"face-pairs to coincide file.write('************************** make all corresponding face-pairs to coincide \\n') edgeNodes =",
"to coincide \\n') edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for",
"2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{},",
"\\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance):",
"node not in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] - obj.nodes[obj.baseNodes[iface][1]]",
"nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to get the",
"write nset- and equations- files for PBC? (y/n): \\033[0m\" ) in [\"y\", \"\"]:",
"{}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, twoFacets[4], dm)) def write_PBC_Nset(file,",
") while writeInp not in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\"",
"newFile, open(inpFile, 'r') as oldFile: clone = True for line in oldFile: if",
"== False and '*' in line: clone = True if clone: newFile.write(line) #",
"to match the nodes (time complexity of O(V + E), V and E",
"\\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for edge in",
"6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] -",
"edges, and 6 faces, with three steps: 1. make the 8 outer vertexes",
"== 'y': newFileName = path + job + \"_PBC.inp\" with open(newFileName, 'w') as",
"\" )) elif input( \"\\033[32;1m write nset- and equations- files for PBC? (y/n):",
"[0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2.",
"getFaceForPBC = obj.getFaceForPBC_byGraph writeEquations = write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key == \"2\":",
"3]: if node not in edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node,",
"with open(inpFile, 'r') as file: for line in file: if '*Instance' in line",
"file.write('************************** make all outer edges to coincide \\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines]",
"range(len(obj.outlines[edge0])): for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"iface, face in enumerate(obj.faceMatch): for node in face: for dm in [1, 2,",
"file: if '*Instance' in line and 'name=' in line: instance = line.split(',') instance",
"vertexes of ylines to form parallel hexahedron file.write('************************** make vertexes of 4 ylines",
"clone == False and '*' in line: clone = True if clone: newFile.write(line)",
"\\n'.format(instance, obj.ylines[0]['beg'], dm)) # 2. make all outer edges to coincide file.write('************************** make",
"'w') as newFile, open(inpFile, 'r') as oldFile: clone = True for line in",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{},",
"obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\",",
"if testState: del obj.faceMatch getFaceForPBC() # find the instance name instance = 'Part-1'",
"the PBC info, write the PBC for the 8 outer vertex, and 12",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[1], dm)) ## 1.2 make vertexes of ylines",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm))",
"') ) while writeInp not in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert",
"for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge in edges: edgeNodes |= ({edge['beg']}",
"as np from elementsBody import * def write_PBC_equation(file, obj, instance): \"\"\" write the",
"write_PBC_Nset(file, obj): if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not",
"yMin, yMax, zMin, zMax: detect the surface simply by coordinates of all nodes.",
"file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0],",
"False # get the inp file and the object inpFile = input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert",
"ylines to form parallel hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']]",
"surface-nodes: 1. graph-method: (recommended, can deal with arbitrary deformed shape): use dictionary-data-structure to",
"outer edges to coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges:",
"node to neighbors) to match their neighbors. 2. nearest-coordinates method: Could be very",
"zMax; \\n(insert 1 or 2): \" )) if key == \"1\": getFaceForPBC =",
"yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.ylines[0]['beg'],",
"obj, instance) if clone == False and '*' in line: clone = True",
"'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for node in obj.nodes: if type(obj.nodes[node]) == type([]):",
"and edges respectively): Matching nodes during traversing of surface-node-graphs of opposite faces. Given",
"= \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make all outer",
"1.1 make the y0face to be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\",
"initial state \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if",
"(recommended, can deal with arbitrary deformed shape): use dictionary-data-structure to map facet-nodes to",
"z \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph()",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use",
"\\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm))",
"\"has been written. \" )) elif input( \"\\033[32;1m write nset- and equations- files",
"node in face: for dm in [1, 2, 3]: if node not in",
"(平行六面体)) 2. make 12 edges to satisfy PBC 3. make the inside nodes",
"instance = line.split(',') instance = instance[1].split('=') instance = instance[-1] print('instance =', instance) break",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{},",
"line.split(',') instance = instance[1].split('=') instance = instance[-1] print('instance =', instance) break writeInp =",
"\"\"\" write the PBC for the 8 outer vertex, and 12 edges, and",
"[[0, 4], [3, 7], [2, 6], [1, 5]], # xEdges [[1, 0], [5,",
"in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3.",
"\"y\" or \"n\": ' )) if writeInp == 'y': newFileName = path +",
"makenp = False for node in obj.nodes: if type(obj.nodes[node]) == type([]): makenp =",
"{} \\033[0m\".format( \"file\", newFileName, \"has been written. \" )) elif input( \"\\033[32;1m write",
"path = inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method",
"{}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge['beg'], dm)) file.write('{}.N{}, {},",
"Two methods match nodes on opposites of the surface: 1. BFS method to",
"edges to coincide \\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges:",
"PBC for the 8 outer vertex, and 12 edges, and 6 faces, with",
"for PBC with open(path + '{}_equation.txt'.format(job), 'w') as file: writeEquations(file, obj, instance) print(\"\\033[40;36;1m",
"clone = True if clone: newFile.write(line) # write the line from old file",
"to coincide file.write('************************** make all outer edges to coincide \\n') edgeId = [",
"\\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"3]], # yEdges [[2, 1], [6, 5], [7, 4], [3, 0]] # zEdges",
"\\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"= \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj):",
"in line: write_PBC_Nset(newFile, obj) elif '*End Assembly' in line: writeEquations(newFile, obj, instance) if",
"True for line in oldFile: if \"Section:\" in line and \"**\" in line:",
"the surface: 1. BFS method to match the nodes (time complexity of O(V",
"hexahedron file.write('************************** make vertexes of 4 ylines to coincide \\n') for yline in",
"for line in oldFile: if \"Section:\" in line and \"**\" in line: write_PBC_Nset(newFile,",
"2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] #",
"input( 'ok to write the .inp file with PBC inside the file ?",
"not in ['y', 'n']: adjustCoor = input('\\033[33m{}\\033[0m'.format('please insert \"y\" or \"n\": ')) if",
"key == \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC()",
"be parallogram obj.nodes[obj.v_x1y0z0] = \\ obj.nodes[obj.v_x0y0z0] + \\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2",
"the 8 outer vertexes to form a parallel hexahedron (平行六面体)) 2. make 12",
"clone: newFile.write(line) # write the line from old file to new file if",
"complexity of O(V + E), V and E are number of nodes and",
"cuboid shape. Two methods match nodes on opposites of the surface: 1. BFS",
"yEdges [[2, 1], [6, 5], [7, 4], [3, 0]] # zEdges ] for",
"nodes of face-pair to coincide the node-number of megaElement (composed of vertex of",
"algorithm. 2. method of xMin, xMax, yMin, yMax, zMin, zMax: detect the surface",
"i, j in [[7, 6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\ obj.nodes[obj.megaElement[j]]",
"in xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): for dm in",
"node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] #",
"1]]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance,",
"-1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm)) # 3. make",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm)) # 3. make all corresponding face-pairs",
"if adjustCoor == 'y': adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC() # find the",
"ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the y0face to be",
"{} {} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has been written. \" )) elif",
"many nodes on a surface (with time complexity of O(V^2)). \"\"\" import torch",
"outer edges to coincide file.write('************************** make all outer edges to coincide \\n') xyzEdges",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm))",
"the nodal coordiantes for periodic boundary condition (PBC) make the nodes at face-pair",
"in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: for dm in [1,",
"in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{},",
"= input( 'ok to write the .inp file with PBC inside the file",
"{}, {}, {}, {} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\"",
"\\n') edgeId = [ [[0, 4], [3, 7], [2, 6], [1, 5]], #",
"if node not in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]] + \\ obj.nodes[face[node]] -",
"[2, 3]], # yEdges [[2, 1], [6, 5], [7, 4], [3, 0]] #",
"\")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in inpFile else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job",
"ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() makenp = False for node in obj.nodes:",
"the .inp file with PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while",
"in faceMatch: obj.nodes[faceMatch[node]] = \\ obj.nodes[twoFacets[4]] + \\ obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted =",
"\"\"\" use graph method to get the node-relation, adjust the nodal coordiantes for",
"obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make all",
"adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate =",
"make vertexes of ylines to form parallel hexahedron file.write('************************** make vertexes of 4",
"obj, instance): \"\"\" write the PBC for the 8 outer vertex, and 12",
"xMin, xMax, yMin, yMax, zMin, zMax: detect the surface simply by coordinates of",
"obj.getEdgeForPBC_byGraph() makenp = False for node in obj.nodes: if type(obj.nodes[node]) == type([]): makenp",
"the .inp file name (include the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\"",
"the y0face to be parallogram \\n') for dm in [1, 2, 3]: file.write('*Equation\\n4",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.outlines[edge0][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm)) #",
"\"_PBC.inp\" with open(newFileName, 'w') as newFile, open(inpFile, 'r') as oldFile: clone = True",
"in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for dm in",
"path + '{}_nset.txt'.format(job), \"has been written. \" )) # write the equation for",
"ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'faceNode'): obj.getFaceNode() for node in obj.getFaceNode():",
"while writeInp not in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or",
"obj.megaElement[5], dm)) # 2. make all outer edges to coincide file.write('************************** make all",
"{} \\033[35;1m {} \\033[0m\".format( \"file\", path + '{}_nset.txt'.format(job), \"has been written. \" ))",
"satisfy PBC 3. make the inside nodes of face-pair to coincide \"\"\" if",
"in obj.getFaceNode(): file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes = obj.nodes",
"nset- and equations- files for PBC? (y/n): \\033[0m\" ) in [\"y\", \"\"]: #",
"y0face to be parallogram \\n') for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n')",
"obj): nodes = obj.nodes for node in nodes: file.write(' {}, {}, {}, {}",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm)) # 3. make all corresponding face-pairs",
"instance = instance[1].split('=') instance = instance[-1] print('instance =', instance) break writeInp = input(",
"hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] -",
"| | v2----|-v6 y ^ |/ |/ | v1------v5 ---> / x z",
"{}, {} \\n'.format( node, nodes[node][0], nodes[node][1], nodes[node][2] )) def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph",
"file.write('************************** make all outer edges to coincide \\n') edgeId = [ [[0, 4],",
"obj) print(\"\\033[40;36;1m {} {} \\033[35;1m {} \\033[0m\".format( \"file\", newFileName, \"has been written. \"",
"make all corresponding face-pairs to coincide \\n') for twoFacets in obj.faceMatch: faceMatch =",
"Construct the node-linking graph of surface, and the node-linking graph of the outlines.",
"(with time complexity of O(V^2)). \"\"\" import torch as tch import numpy as",
"path + job + \"_PBC.inp\" with open(newFileName, 'w') as newFile, open(inpFile, 'r') as",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{},",
"yMin, yMax, zMin, zMax; \\n(insert 1 or 2): \" )) if key ==",
"2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, yline['end'], dm)) file.write('{}.N{}, {}, -1",
"def adjustCoordinatesForPBC_byGraph(obj): \"\"\" use graph method to get the node-relation, adjust the nodal",
"\\ obj.nodes[obj.megaElement[j]] + \\ obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make all outer edges",
"file ? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not in ['y', 'n']: writeInp =",
"nearest-coordinates method: Could be very slow when there are many many nodes on",
"1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, edge1[0], dm)) file.write('{}.N{}, {}, -1",
"2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{}, {}, -1",
"deformed shape): use dictionary-data-structure to map facet-nodes to element-number, where the surface-facet is",
"file: for line in file: if '*Instance' in line and 'name=' in line:",
"and partition the surface-nodes: 1. graph-method: (recommended, can deal with arbitrary deformed shape):",
"of outer surface) is shown as follows, v3------v7 /| /| v0------v4| | |",
"def write_nodes(file, obj): nodes = obj.nodes for node in nodes: file.write(' {}, {},",
"dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[5], dm)) # 2. make all outer edges",
"if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp =",
"[3, 2], [0, 1]]: for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{},",
"\"\"]: # write the Nset with open(path + '{}_nset.txt'.format(job), 'w') as file: for",
"yMax, zMin, zMax: detect the surface simply by coordinates of all nodes. This",
"detect and partition the surface-nodes: 1. graph-method: (recommended, can deal with arbitrary deformed",
"hexahedron (平行六面体)) 2. make 12 edges to satisfy PBC 3. make the inside",
"ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() makenp = False for node in obj.nodes:",
"node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node],",
"for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']]",
"obj.nodes[obj.megaElement[4]] - obj.nodes[obj.megaElement[5]] # 2. make all outer edges to coincide edgeId =",
"3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"getFaceForPBC() adjustCoor = input(\"do you want to adjust the coordinates for PBC? \"",
"node-pair, use similar vectors (pointed from current node to neighbors) to match their",
"face-pair to coincide \"\"\" if not isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\")",
"1.2 make vertexes of ylines to form parallel hexahedron for i, j in",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.baseNodes[iface][1], dm))",
"not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ## 1.1 make the y0face",
"or \"n\": ')) if adjustCoor == 'y': adjustCoordinate(obj) if testState: del obj.faceMatch getFaceForPBC()",
"in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2.",
"edges[0]['inside'][node], dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, edges[0]['beg'], dm)) # 3. make all corresponding",
"= adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you want to adjust the coordinates for",
"torch as tch import numpy as np from elementsBody import * def write_PBC_equation(file,",
"for line in file: if '*Instance' in line and 'name=' in line: instance",
"- obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of ylines to form parallel hexahedron for",
"key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want to use? \\n\" \"1: graph-method",
"outer edges to coincide file.write('************************** make all outer edges to coincide \\n') edgeId",
"want to adjust the coordinates for PBC? \" \"(not recommended)\\n\\033[33m{}\\033[0m\".format('(y/n): ')) while adjustCoor",
"neighbors) to match their neighbors. 2. nearest-coordinates method: Could be very slow when",
"edge in edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for dm",
"obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format( \"which method do you want to use?",
"parallel hexahedron file.write('************************** make vertexes of 4 ylines to coincide \\n') for yline",
"= \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']] - obj.nodes[obj.ylines[0]['beg']] # 2. make all outer",
"= write_PBC_equation_byGraph adjustCoordinate = adjustCoordinatesForPBC_byGraph elif key == \"2\": getFaceForPBC = obj.getFaceForPBC writeEquations",
"edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for dm in [1, 2,",
"twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]] = \\",
"edgeNodes: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, node, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"if \"*Node\\n\" in line: if hasattr(obj, 'nodesAdjusted'): clone = False print(\"\\033[35;1m{}\\033[0m\".format(\"write new nodes",
"] for edges in edgeId: # edges = xEdges or yEdges or zEdges",
"in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, edge['inside'][node], dm)) file.write('{}.N{},",
"\\n'.format(instance, edges[0]['beg'], dm)) # 3. make all corresponding face-pairs to coincide file.write('************************** make",
"-1 \\n'.format(instance, obj.megaElement[2], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[5], dm)) file.write('{}.N{}, {}, 1",
"raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face to",
"line in oldFile: if \"Section:\" in line and \"**\" in line: write_PBC_Nset(newFile, obj)",
"edges in xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] =",
"to form a parallel hexahedron (平行六面体)) 2. make 12 edges to satisfy PBC",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, twoFacets[0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, faceMatch[node], dm)) file.write('{}.N{},",
"# 2. make all outer edges to coincide xyzEdges = [obj.xlines, obj.ylines, obj.zlines]",
"\"__main__\": testState = False # get the inp file and the object inpFile",
"+ \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make all corresponding face-pairs to coincide",
"(obj.nodes[obj.megaElement[5]] - obj.nodes[obj.megaElement[1]]) ## 1.2 make vertexes of ylines to form parallel hexahedron",
"{}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm)) file.write('{}.N{}, {},",
"BFS method to match the nodes (time complexity of O(V + E), V",
"coincide the node-number of megaElement (composed of vertex of outer surface) is shown",
"obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] -",
"makenp: for node in obj.nodes: obj.nodes[node] = np.array(obj.nodes[node]) ## 1.1 make the y0face",
"corresponding face-pairs to coincide file.write('************************** make all corresponding face-pairs to coincide \\n') edgeNodes",
"make all outer edges to coincide file.write('************************** make all outer edges to coincide",
"edge in edges[1:]: for node in range(len(edge['inside'])): for dm in [1, 2, 3]:",
"\"\\033[32;1m write nset- and equations- files for PBC? (y/n): \\033[0m\" ) in [\"y\",",
"0], [5, 4], [6, 7], [2, 3]], # yEdges [[2, 1], [6, 5],",
"in [obj.xlines, obj.ylines, obj.zlines]: for edge in edges: edgeNodes |= ({edge['beg']} | {edge['end']}",
"obj.nodes[node] - obj.nodes[twoFacets[0]] obj.nodesAdjusted = True def adjustCoordinatesForPBC(obj): \"\"\" adjust the nodal coordiantes",
"in face: for dm in [1, 2, 3]: if node not in edgeNodes:",
"else inpFile.split(\"\\\\\")[-1].split(\".inp\")[0] path = inpFile.split(job + \".inp\")[0] obj = ElementsBody(*readInp(inpFile)) key = input(\"\\033[35;1m{}\\033[0m\".format(",
"obj.nodes[obj.baseNodes[iface][1]] obj.nodesAdjusted = True if __name__ == \"__main__\": testState = False # get",
"[1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.outlines[edge1][node], dm)) file.write('{}.N{}, {},",
"for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: obj.nodes[faceMatch[node]] =",
"range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] + \\ obj.nodes[obj.outlines[edge0][node]] - obj.nodes[edge0[0]] # 3. make",
"1 \\n'.format(instance, obj.baseNodes[iface][1], dm)) def write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method to get",
"methods to detect and partition the surface-nodes: 1. graph-method: (recommended, can deal with",
"dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.baseNodes[iface][0], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, face[node], dm))",
"parallel hexahedron for yline in obj.ylines[1:]: obj.nodes[yline['end']] = \\ obj.nodes[yline['beg']] + \\ obj.nodes[obj.ylines[0]['end']]",
"| v2----|-v6 y ^ |/ |/ | v1------v5 ---> / x z \"\"\"",
"(time complexity of O(V + E), V and E are number of nodes",
"for node in nodes: file.write(' {}, {}, {}, {} \\n'.format( node, nodes[node][0], nodes[node][1],",
"edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): obj.nodes[obj.outlines[edge1][node]] = \\ obj.nodes[edge1[0]] +",
"files for PBC? (y/n): \\033[0m\" ) in [\"y\", \"\"]: # write the Nset",
"write the .inp file with PBC inside the file ? \\033[36m{}\\033[0m'.format('(y/n): ') )",
"'name=' in line: instance = line.split(',') instance = instance[1].split('=') instance = instance[-1] print('instance",
"= True for line in oldFile: if \"Section:\" in line and \"**\" in",
"\\n') edgeNodes = set() for edges in [obj.xlines, obj.ylines, obj.zlines]: for edge in",
"4 ylines to coincide \\n') for i, j in [[7, 6], [3, 2],",
"surface-facet is shared by only one element. Construct the node-linking graph of surface,",
"in edgeId: # edges = xEdges or yEdges or zEdges edge0 = (obj.megaElement[edges[0][0]],",
"not in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\": '",
"['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format( 'please insert \"y\" or \"n\": ' )) if",
"3. make all corresponding face-pairs to coincide file.write('************************** make all corresponding face-pairs to",
"dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x1y0z0, dm))",
"edges[1:]: for node in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] -",
"partition the graph into different faces (left-, right-, down-, up-, back-, front- surfaces)",
"obj.megaElement[i], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[j], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.megaElement[4],",
"and 'name=' in line: instance = line.split(',') instance = instance[1].split('=') instance = instance[-1]",
"file.write('{}.N{}, {}, 1 \\n'.format(instance, edge0[0], dm)) # 3. make all corresponding face-pairs to",
"to coincide \\n') xyzEdges = [obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for",
"for edges in xyzEdges: for edge in edges[1:]: for node in range(len(edge['inside'])): for",
"= input(\"\\033[0;33;40m{}\\033[0m\".format(\"please insert the .inp file name (include the path): \")) job =",
"(PBC) make the nodes at face-pair to be strictly coincide at initial state",
"with arbitrary deformed shape): use dictionary-data-structure to map facet-nodes to element-number, where the",
"in range(len(edge['inside'])): obj.nodes[edge['inside'][node]] = \\ obj.nodes[edge['beg']] + \\ obj.nodes[edges[0]['inside'][node]] - obj.nodes[edges[0]['beg']] # 3.",
"isinstance(obj, ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") if not hasattr(obj, 'v_x0y0z0'): obj.getEdgeVertexForPBC() ##",
"iface, face in enumerate(obj.faceMatch): for node in face: if node not in edgeNodes:",
"3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance,",
"edges[1:]: edge1 = (obj.megaElement[edge[0]], obj.megaElement[edge[1]]) for node in range(len(obj.outlines[edge0])): for dm in [1,",
"xEdges [[1, 0], [5, 4], [6, 7], [2, 3]], # yEdges [[2, 1],",
"node-linking graph of surface, and the node-linking graph of the outlines. Using outlines",
"\\n') for twoFacets in obj.faceMatch: faceMatch = obj.faceMatch[twoFacets] for node in faceMatch: for",
"write_PBC_equation_byGraph(file, obj, instance): \"\"\" use graph-method to get the PBC info, write the",
"for node in face: if node not in edgeNodes: obj.nodes[node] = \\ obj.nodes[obj.baseNodes[iface][0]]",
"write the equation for PBC with open(path + '{}_equation.txt'.format(job), 'w') as file: writeEquations(file,",
"[obj.xlines, obj.ylines, obj.zlines] for edges in xyzEdges: for edge in edges[1:]: for node",
"= obj.getFaceForPBC writeEquations = write_PBC_equation adjustCoordinate = adjustCoordinatesForPBC getFaceForPBC() adjustCoor = input(\"do you",
".inp file name (include the path): \")) job = inpFile.split(\"/\")[-1].split(\".inp\")[0] if \"/\" in",
"for i, j in [[7, 6], [3, 2], [0, 1]]: obj.nodes[obj.megaElement[i]] = \\",
"\\ (obj.nodes[obj.v_x1y0z1] - obj.nodes[obj.v_x0y0z1]) ## 1.2 make vertexes of ylines to form parallel",
"as oldFile: clone = True for line in oldFile: if \"Section:\" in line",
"elementsBody import * def write_PBC_equation(file, obj, instance): \"\"\" write the PBC for the",
"all corresponding face-pairs to coincide file.write('************************** make all corresponding face-pairs to coincide \\n')",
"at face-pair to be strictly coincide at initial state \"\"\" if not isinstance(obj,",
"a surface (with time complexity of O(V^2)). \"\"\" import torch as tch import",
"PBC 3. make the inside nodes of face-pair to coincide the node-number of",
"the nodes at face-pair to be strictly coincide at initial state \"\"\" if",
"instance[1].split('=') instance = instance[-1] print('instance =', instance) break writeInp = input( 'ok to",
"{}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.v_x0y0z1, dm)) ## 1.2",
"= obj.faceMatch[twoFacets] for node in faceMatch: for dm in [1, 2, 3]: file.write('*Equation\\n4",
"node in obj.nodes: if type(obj.nodes[node]) == type([]): makenp = True break if makenp:",
"file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x0y0z0, dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.v_x1y0z1, dm)) file.write('{}.N{},",
"{}, -1 \\n'.format(instance, yline['beg'], dm)) file.write('{}.N{}, {}, -1 \\n'.format(instance, obj.ylines[0]['end'], dm)) file.write('{}.N{}, {},",
"for node in obj.nodes: if type(obj.nodes[node]) == type([]): makenp = True break if",
"? \\033[36m{}\\033[0m'.format('(y/n): ') ) while writeInp not in ['y', 'n']: writeInp = input('\\033[31m{}\\033[0m'.format(",
"ElementsBody): raise ValueError(\"error, not isinstance(obj, ElementsBody)\") obj.getFaceForPBC_byGraph() obj.getEdgeForPBC_byGraph() ## 1.1 make the y0face",
"|= ({edge['beg']} | {edge['end']} | set(edge['inside'])) for iface, face in enumerate(obj.faceMatch): for node",
"file.write('*Nset, nset=N{} \\n'.format(node)) file.write('{}, \\n'.format(node)) def write_nodes(file, obj): nodes = obj.nodes for node",
"for dm in [1, 2, 3]: file.write('*Equation\\n4 \\n') file.write('{}.N{}, {}, 1 \\n'.format(instance, obj.megaElement[6],"
] |